Rename ComputeMaskedBits to computeKnownBits. "Masked" has been
[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/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetOptions.h"
39 using namespace llvm;
40
41 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
42 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
43
44 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
45 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
46
47 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
48 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
49
50 // FIXME: Remove this once the bug has been fixed!
51 extern cl::opt<bool> ANDIGlueBug;
52
53 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
54   if (TM.getSubtargetImpl()->isDarwin())
55     return new TargetLoweringObjectFileMachO();
56
57   if (TM.getSubtargetImpl()->isSVR4ABI())
58     return new PPC64LinuxTargetObjectFile();
59
60   return new TargetLoweringObjectFileELF();
61 }
62
63 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
64   : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
65   const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
66
67   setPow2DivIsCheap();
68
69   // Use _setjmp/_longjmp instead of setjmp/longjmp.
70   setUseUnderscoreSetJmp(true);
71   setUseUnderscoreLongJmp(true);
72
73   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
74   // arguments are at least 4/8 bytes aligned.
75   bool isPPC64 = Subtarget->isPPC64();
76   setMinStackArgumentAlignment(isPPC64 ? 8:4);
77
78   // Set up the register classes.
79   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
80   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
81   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
82
83   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
84   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
85   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
86
87   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
88
89   // PowerPC has pre-inc load and store's.
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
94   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
100
101   if (Subtarget->useCRBits()) {
102     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103
104     if (isPPC64 || Subtarget->hasFPCVT()) {
105       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107                          isPPC64 ? MVT::i64 : MVT::i32);
108       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
110                          isPPC64 ? MVT::i64 : MVT::i32);
111     } else {
112       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
114     }
115
116     // PowerPC does not support direct load / store of condition registers
117     setOperationAction(ISD::LOAD, MVT::i1, Custom);
118     setOperationAction(ISD::STORE, MVT::i1, Custom);
119
120     // FIXME: Remove this once the ANDI glue bug is fixed:
121     if (ANDIGlueBug)
122       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123
124     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
125     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
126     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
127     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
128     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
129     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
130
131     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
132   }
133
134   // This is used in the ppcf128->int sequence.  Note it has different semantics
135   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
136   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137
138   // We do not currently implement these libm ops for PowerPC.
139   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
140   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
141   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
142   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
143   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
144   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145
146   // PowerPC has no SREM/UREM instructions
147   setOperationAction(ISD::SREM, MVT::i32, Expand);
148   setOperationAction(ISD::UREM, MVT::i32, Expand);
149   setOperationAction(ISD::SREM, MVT::i64, Expand);
150   setOperationAction(ISD::UREM, MVT::i64, Expand);
151
152   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
153   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
157   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
159   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
160   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161
162   // We don't support sin/cos/sqrt/fmod/pow
163   setOperationAction(ISD::FSIN , MVT::f64, Expand);
164   setOperationAction(ISD::FCOS , MVT::f64, Expand);
165   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
166   setOperationAction(ISD::FREM , MVT::f64, Expand);
167   setOperationAction(ISD::FPOW , MVT::f64, Expand);
168   setOperationAction(ISD::FMA  , MVT::f64, Legal);
169   setOperationAction(ISD::FSIN , MVT::f32, Expand);
170   setOperationAction(ISD::FCOS , MVT::f32, Expand);
171   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
172   setOperationAction(ISD::FREM , MVT::f32, Expand);
173   setOperationAction(ISD::FPOW , MVT::f32, Expand);
174   setOperationAction(ISD::FMA  , MVT::f32, Legal);
175
176   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177
178   // If we're enabling GP optimizations, use hardware square root
179   if (!Subtarget->hasFSQRT() &&
180       !(TM.Options.UnsafeFPMath &&
181         Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
182     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183
184   if (!Subtarget->hasFSQRT() &&
185       !(TM.Options.UnsafeFPMath &&
186         Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
187     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188
189   if (Subtarget->hasFCPSGN()) {
190     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
191     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192   } else {
193     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
195   }
196
197   if (Subtarget->hasFPRND()) {
198     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
199     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
200     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
201     setOperationAction(ISD::FROUND, MVT::f64, Legal);
202
203     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
204     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
205     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
206     setOperationAction(ISD::FROUND, MVT::f32, Legal);
207   }
208
209   // PowerPC does not have BSWAP, CTPOP or CTTZ
210   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
212   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
214   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
216   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
217   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218
219   if (Subtarget->hasPOPCNTD()) {
220     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
221     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
222   } else {
223     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
224     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
225   }
226
227   // PowerPC does not have ROTR
228   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
229   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
230
231   if (!Subtarget->useCRBits()) {
232     // PowerPC does not have Select
233     setOperationAction(ISD::SELECT, MVT::i32, Expand);
234     setOperationAction(ISD::SELECT, MVT::i64, Expand);
235     setOperationAction(ISD::SELECT, MVT::f32, Expand);
236     setOperationAction(ISD::SELECT, MVT::f64, Expand);
237   }
238
239   // PowerPC wants to turn select_cc of FP into fsel when possible.
240   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242
243   // PowerPC wants to optimize integer setcc a bit
244   if (!Subtarget->useCRBits())
245     setOperationAction(ISD::SETCC, MVT::i32, Custom);
246
247   // PowerPC does not have BRCOND which requires SetCC
248   if (!Subtarget->useCRBits())
249     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250
251   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
252
253   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
254   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255
256   // PowerPC does not have [U|S]INT_TO_FP
257   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
258   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259
260   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
262   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
263   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264
265   // We cannot sextinreg(i1).  Expand to shifts.
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267
268   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
269   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
270   // support continuation, user-level threading, and etc.. As a result, no
271   // other SjLj exception interfaces are implemented and please don't build
272   // your own exception handling based on them.
273   // LLVM/Clang supports zero-cost DWARF exception handling.
274   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
275   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276
277   // We want to legalize GlobalAddress and ConstantPool nodes into the
278   // appropriate instructions to materialize the address.
279   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
280   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
281   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
282   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
283   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
284   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
285   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
287   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
288   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
289
290   // TRAP is legal.
291   setOperationAction(ISD::TRAP, MVT::Other, Legal);
292
293   // TRAMPOLINE is custom lowered.
294   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
295   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296
297   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
299
300   if (Subtarget->isSVR4ABI()) {
301     if (isPPC64) {
302       // VAARG always uses double-word chunks, so promote anything smaller.
303       setOperationAction(ISD::VAARG, MVT::i1, Promote);
304       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
305       setOperationAction(ISD::VAARG, MVT::i8, Promote);
306       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
307       setOperationAction(ISD::VAARG, MVT::i16, Promote);
308       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
309       setOperationAction(ISD::VAARG, MVT::i32, Promote);
310       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
311       setOperationAction(ISD::VAARG, MVT::Other, Expand);
312     } else {
313       // VAARG is custom lowered with the 32-bit SVR4 ABI.
314       setOperationAction(ISD::VAARG, MVT::Other, Custom);
315       setOperationAction(ISD::VAARG, MVT::i64, Custom);
316     }
317   } else
318     setOperationAction(ISD::VAARG, MVT::Other, Expand);
319
320   if (Subtarget->isSVR4ABI() && !isPPC64)
321     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
322     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
323   else
324     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
325
326   // Use the default implementation.
327   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
328   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
329   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
331   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
332
333   // We want to custom lower some of our intrinsics.
334   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335
336   // To handle counter-based loop conditions.
337   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338
339   // Comparisons that require checking two conditions.
340   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
341   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
343   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
345   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
347   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
349   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
351   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352
353   if (Subtarget->has64BitSupport()) {
354     // They also have instructions for converting between i64 and fp.
355     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
356     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
357     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
358     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
359     // This is just the low 32 bits of a (signed) fp->i64 conversion.
360     // We cannot do this with Promote because i64 is not a legal type.
361     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362
363     if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
364       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365   } else {
366     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
367     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
368   }
369
370   // With the instructions enabled under FPCVT, we can do everything.
371   if (PPCSubTarget.hasFPCVT()) {
372     if (Subtarget->has64BitSupport()) {
373       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
374       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
375       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
376       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
377     }
378
379     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
383   }
384
385   if (Subtarget->use64BitRegs()) {
386     // 64-bit PowerPC implementations can support i64 types directly
387     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
388     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
389     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
390     // 64-bit PowerPC wants to expand i128 shifts itself.
391     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
393     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394   } else {
395     // 32-bit PowerPC wants to expand i64 shifts itself.
396     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
398     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
399   }
400
401   if (Subtarget->hasAltivec()) {
402     // First set operation action for all vector types to expand. Then we
403     // will selectively turn on ones that can be effectively codegen'd.
404     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
405          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
406       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
407
408       // add/sub are legal for all supported vector VT's.
409       setOperationAction(ISD::ADD , VT, Legal);
410       setOperationAction(ISD::SUB , VT, Legal);
411
412       // We promote all shuffles to v16i8.
413       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
414       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
415
416       // We promote all non-typed operations to v4i32.
417       setOperationAction(ISD::AND   , VT, Promote);
418       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
419       setOperationAction(ISD::OR    , VT, Promote);
420       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
421       setOperationAction(ISD::XOR   , VT, Promote);
422       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
423       setOperationAction(ISD::LOAD  , VT, Promote);
424       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
425       setOperationAction(ISD::SELECT, VT, Promote);
426       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
427       setOperationAction(ISD::STORE, VT, Promote);
428       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
429
430       // No other operations are legal.
431       setOperationAction(ISD::MUL , VT, Expand);
432       setOperationAction(ISD::SDIV, VT, Expand);
433       setOperationAction(ISD::SREM, VT, Expand);
434       setOperationAction(ISD::UDIV, VT, Expand);
435       setOperationAction(ISD::UREM, VT, Expand);
436       setOperationAction(ISD::FDIV, VT, Expand);
437       setOperationAction(ISD::FREM, VT, Expand);
438       setOperationAction(ISD::FNEG, VT, Expand);
439       setOperationAction(ISD::FSQRT, VT, Expand);
440       setOperationAction(ISD::FLOG, VT, Expand);
441       setOperationAction(ISD::FLOG10, VT, Expand);
442       setOperationAction(ISD::FLOG2, VT, Expand);
443       setOperationAction(ISD::FEXP, VT, Expand);
444       setOperationAction(ISD::FEXP2, VT, Expand);
445       setOperationAction(ISD::FSIN, VT, Expand);
446       setOperationAction(ISD::FCOS, VT, Expand);
447       setOperationAction(ISD::FABS, VT, Expand);
448       setOperationAction(ISD::FPOWI, VT, Expand);
449       setOperationAction(ISD::FFLOOR, VT, Expand);
450       setOperationAction(ISD::FCEIL,  VT, Expand);
451       setOperationAction(ISD::FTRUNC, VT, Expand);
452       setOperationAction(ISD::FRINT,  VT, Expand);
453       setOperationAction(ISD::FNEARBYINT, VT, Expand);
454       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
455       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
456       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
457       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
458       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
459       setOperationAction(ISD::UDIVREM, VT, Expand);
460       setOperationAction(ISD::SDIVREM, VT, Expand);
461       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
462       setOperationAction(ISD::FPOW, 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     setStackPointerRegisterToSaveRestore(PPC::X1);
631     setExceptionPointerRegister(PPC::X3);
632     setExceptionSelectorRegister(PPC::X4);
633   } else {
634     setStackPointerRegisterToSaveRestore(PPC::R1);
635     setExceptionPointerRegister(PPC::R3);
636     setExceptionSelectorRegister(PPC::R4);
637   }
638
639   // We have target-specific dag combine patterns for the following nodes:
640   setTargetDAGCombine(ISD::SINT_TO_FP);
641   setTargetDAGCombine(ISD::LOAD);
642   setTargetDAGCombine(ISD::STORE);
643   setTargetDAGCombine(ISD::BR_CC);
644   if (Subtarget->useCRBits())
645     setTargetDAGCombine(ISD::BRCOND);
646   setTargetDAGCombine(ISD::BSWAP);
647   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
648
649   setTargetDAGCombine(ISD::SIGN_EXTEND);
650   setTargetDAGCombine(ISD::ZERO_EXTEND);
651   setTargetDAGCombine(ISD::ANY_EXTEND);
652
653   if (Subtarget->useCRBits()) {
654     setTargetDAGCombine(ISD::TRUNCATE);
655     setTargetDAGCombine(ISD::SETCC);
656     setTargetDAGCombine(ISD::SELECT_CC);
657   }
658
659   // Use reciprocal estimates.
660   if (TM.Options.UnsafeFPMath) {
661     setTargetDAGCombine(ISD::FDIV);
662     setTargetDAGCombine(ISD::FSQRT);
663   }
664
665   // Darwin long double math library functions have $LDBL128 appended.
666   if (Subtarget->isDarwin()) {
667     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
668     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
669     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
670     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
671     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
672     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
673     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
674     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
675     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
676     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
677   }
678
679   // With 32 condition bits, we don't need to sink (and duplicate) compares
680   // aggressively in CodeGenPrep.
681   if (Subtarget->useCRBits())
682     setHasMultipleConditionRegisters();
683
684   setMinFunctionAlignment(2);
685   if (PPCSubTarget.isDarwin())
686     setPrefFunctionAlignment(4);
687
688   if (isPPC64 && Subtarget->isJITCodeModel())
689     // Temporary workaround for the inability of PPC64 JIT to handle jump
690     // tables.
691     setSupportJumpTables(false);
692
693   setInsertFencesForAtomic(true);
694
695   if (Subtarget->enableMachineScheduler())
696     setSchedulingPreference(Sched::Source);
697   else
698     setSchedulingPreference(Sched::Hybrid);
699
700   computeRegisterProperties();
701
702   // The Freescale cores does better with aggressive inlining of memcpy and
703   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
704   if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
705       Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
706     MaxStoresPerMemset = 32;
707     MaxStoresPerMemsetOptSize = 16;
708     MaxStoresPerMemcpy = 32;
709     MaxStoresPerMemcpyOptSize = 8;
710     MaxStoresPerMemmove = 32;
711     MaxStoresPerMemmoveOptSize = 8;
712
713     setPrefFunctionAlignment(4);
714   }
715 }
716
717 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
718 /// the desired ByVal argument alignment.
719 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
720                              unsigned MaxMaxAlign) {
721   if (MaxAlign == MaxMaxAlign)
722     return;
723   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
724     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
725       MaxAlign = 32;
726     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
727       MaxAlign = 16;
728   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
729     unsigned EltAlign = 0;
730     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
731     if (EltAlign > MaxAlign)
732       MaxAlign = EltAlign;
733   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
734     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
735       unsigned EltAlign = 0;
736       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
737       if (EltAlign > MaxAlign)
738         MaxAlign = EltAlign;
739       if (MaxAlign == MaxMaxAlign)
740         break;
741     }
742   }
743 }
744
745 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
746 /// function arguments in the caller parameter area.
747 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
748   // Darwin passes everything on 4 byte boundary.
749   if (PPCSubTarget.isDarwin())
750     return 4;
751
752   // 16byte and wider vectors are passed on 16byte boundary.
753   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
754   unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
755   if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
756     getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
757   return Align;
758 }
759
760 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
761   switch (Opcode) {
762   default: return nullptr;
763   case PPCISD::FSEL:            return "PPCISD::FSEL";
764   case PPCISD::FCFID:           return "PPCISD::FCFID";
765   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
766   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
767   case PPCISD::FRE:             return "PPCISD::FRE";
768   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
769   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
770   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
771   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
772   case PPCISD::VPERM:           return "PPCISD::VPERM";
773   case PPCISD::Hi:              return "PPCISD::Hi";
774   case PPCISD::Lo:              return "PPCISD::Lo";
775   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
776   case PPCISD::TOC_RESTORE:     return "PPCISD::TOC_RESTORE";
777   case PPCISD::LOAD:            return "PPCISD::LOAD";
778   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
779   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
780   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
781   case PPCISD::SRL:             return "PPCISD::SRL";
782   case PPCISD::SRA:             return "PPCISD::SRA";
783   case PPCISD::SHL:             return "PPCISD::SHL";
784   case PPCISD::CALL:            return "PPCISD::CALL";
785   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
786   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
787   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
788   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
789   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
790   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
791   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
792   case PPCISD::VCMP:            return "PPCISD::VCMP";
793   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
794   case PPCISD::LBRX:            return "PPCISD::LBRX";
795   case PPCISD::STBRX:           return "PPCISD::STBRX";
796   case PPCISD::LARX:            return "PPCISD::LARX";
797   case PPCISD::STCX:            return "PPCISD::STCX";
798   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
799   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
800   case PPCISD::BDZ:             return "PPCISD::BDZ";
801   case PPCISD::MFFS:            return "PPCISD::MFFS";
802   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
803   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
804   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
805   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
806   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
807   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
808   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
809   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
810   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
811   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
812   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
813   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
814   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
815   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
816   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
817   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
818   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
819   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
820   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
821   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
822   case PPCISD::SC:              return "PPCISD::SC";
823   }
824 }
825
826 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
827   if (!VT.isVector())
828     return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
829   return VT.changeVectorElementTypeToInteger();
830 }
831
832 //===----------------------------------------------------------------------===//
833 // Node matching predicates, for use by the tblgen matching code.
834 //===----------------------------------------------------------------------===//
835
836 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
837 static bool isFloatingPointZero(SDValue Op) {
838   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
839     return CFP->getValueAPF().isZero();
840   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
841     // Maybe this has already been legalized into the constant pool?
842     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
843       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
844         return CFP->getValueAPF().isZero();
845   }
846   return false;
847 }
848
849 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
850 /// true if Op is undef or if it matches the specified value.
851 static bool isConstantOrUndef(int Op, int Val) {
852   return Op < 0 || Op == Val;
853 }
854
855 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
856 /// VPKUHUM instruction.
857 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
858   if (!isUnary) {
859     for (unsigned i = 0; i != 16; ++i)
860       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+1))
861         return false;
862   } else {
863     for (unsigned i = 0; i != 8; ++i)
864       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+1) ||
865           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+1))
866         return false;
867   }
868   return true;
869 }
870
871 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
872 /// VPKUWUM instruction.
873 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
874   if (!isUnary) {
875     for (unsigned i = 0; i != 16; i += 2)
876       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
877           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
878         return false;
879   } else {
880     for (unsigned i = 0; i != 8; i += 2)
881       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
882           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3) ||
883           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+2) ||
884           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+3))
885         return false;
886   }
887   return true;
888 }
889
890 /// isVMerge - Common function, used to match vmrg* shuffles.
891 ///
892 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
893                      unsigned LHSStart, unsigned RHSStart) {
894   if (N->getValueType(0) != MVT::v16i8)
895     return false;
896   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
897          "Unsupported merge size!");
898
899   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
900     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
901       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
902                              LHSStart+j+i*UnitSize) ||
903           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
904                              RHSStart+j+i*UnitSize))
905         return false;
906     }
907   return true;
908 }
909
910 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
911 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
912 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
913                              bool isUnary) {
914   if (!isUnary)
915     return isVMerge(N, UnitSize, 8, 24);
916   return isVMerge(N, UnitSize, 8, 8);
917 }
918
919 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
920 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
921 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
922                              bool isUnary) {
923   if (!isUnary)
924     return isVMerge(N, UnitSize, 0, 16);
925   return isVMerge(N, UnitSize, 0, 0);
926 }
927
928
929 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
930 /// amount, otherwise return -1.
931 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
932   if (N->getValueType(0) != MVT::v16i8)
933     return -1;
934
935   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
936
937   // Find the first non-undef value in the shuffle mask.
938   unsigned i;
939   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
940     /*search*/;
941
942   if (i == 16) return -1;  // all undef.
943
944   // Otherwise, check to see if the rest of the elements are consecutively
945   // numbered from this value.
946   unsigned ShiftAmt = SVOp->getMaskElt(i);
947   if (ShiftAmt < i) return -1;
948   ShiftAmt -= i;
949
950   if (!isUnary) {
951     // Check the rest of the elements to see if they are consecutive.
952     for (++i; i != 16; ++i)
953       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
954         return -1;
955   } else {
956     // Check the rest of the elements to see if they are consecutive.
957     for (++i; i != 16; ++i)
958       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
959         return -1;
960   }
961   return ShiftAmt;
962 }
963
964 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
965 /// specifies a splat of a single element that is suitable for input to
966 /// VSPLTB/VSPLTH/VSPLTW.
967 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
968   assert(N->getValueType(0) == MVT::v16i8 &&
969          (EltSize == 1 || EltSize == 2 || EltSize == 4));
970
971   // This is a splat operation if each element of the permute is the same, and
972   // if the value doesn't reference the second vector.
973   unsigned ElementBase = N->getMaskElt(0);
974
975   // FIXME: Handle UNDEF elements too!
976   if (ElementBase >= 16)
977     return false;
978
979   // Check that the indices are consecutive, in the case of a multi-byte element
980   // splatted with a v16i8 mask.
981   for (unsigned i = 1; i != EltSize; ++i)
982     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
983       return false;
984
985   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
986     if (N->getMaskElt(i) < 0) continue;
987     for (unsigned j = 0; j != EltSize; ++j)
988       if (N->getMaskElt(i+j) != N->getMaskElt(j))
989         return false;
990   }
991   return true;
992 }
993
994 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
995 /// are -0.0.
996 bool PPC::isAllNegativeZeroVector(SDNode *N) {
997   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
998
999   APInt APVal, APUndef;
1000   unsigned BitSize;
1001   bool HasAnyUndefs;
1002
1003   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1004     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1005       return CFP->getValueAPF().isNegZero();
1006
1007   return false;
1008 }
1009
1010 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1011 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1012 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1013   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1014   assert(isSplatShuffleMask(SVOp, EltSize));
1015   return SVOp->getMaskElt(0) / EltSize;
1016 }
1017
1018 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1019 /// by using a vspltis[bhw] instruction of the specified element size, return
1020 /// the constant being splatted.  The ByteSize field indicates the number of
1021 /// bytes of each element [124] -> [bhw].
1022 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1023   SDValue OpVal(nullptr, 0);
1024
1025   // If ByteSize of the splat is bigger than the element size of the
1026   // build_vector, then we have a case where we are checking for a splat where
1027   // multiple elements of the buildvector are folded together into a single
1028   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1029   unsigned EltSize = 16/N->getNumOperands();
1030   if (EltSize < ByteSize) {
1031     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1032     SDValue UniquedVals[4];
1033     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1034
1035     // See if all of the elements in the buildvector agree across.
1036     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1037       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1038       // If the element isn't a constant, bail fully out.
1039       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1040
1041
1042       if (!UniquedVals[i&(Multiple-1)].getNode())
1043         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1044       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1045         return SDValue();  // no match.
1046     }
1047
1048     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1049     // either constant or undef values that are identical for each chunk.  See
1050     // if these chunks can form into a larger vspltis*.
1051
1052     // Check to see if all of the leading entries are either 0 or -1.  If
1053     // neither, then this won't fit into the immediate field.
1054     bool LeadingZero = true;
1055     bool LeadingOnes = true;
1056     for (unsigned i = 0; i != Multiple-1; ++i) {
1057       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1058
1059       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1060       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1061     }
1062     // Finally, check the least significant entry.
1063     if (LeadingZero) {
1064       if (!UniquedVals[Multiple-1].getNode())
1065         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1066       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1067       if (Val < 16)
1068         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1069     }
1070     if (LeadingOnes) {
1071       if (!UniquedVals[Multiple-1].getNode())
1072         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1073       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1074       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1075         return DAG.getTargetConstant(Val, MVT::i32);
1076     }
1077
1078     return SDValue();
1079   }
1080
1081   // Check to see if this buildvec has a single non-undef value in its elements.
1082   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1083     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1084     if (!OpVal.getNode())
1085       OpVal = N->getOperand(i);
1086     else if (OpVal != N->getOperand(i))
1087       return SDValue();
1088   }
1089
1090   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1091
1092   unsigned ValSizeInBytes = EltSize;
1093   uint64_t Value = 0;
1094   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1095     Value = CN->getZExtValue();
1096   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1097     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1098     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1099   }
1100
1101   // If the splat value is larger than the element value, then we can never do
1102   // this splat.  The only case that we could fit the replicated bits into our
1103   // immediate field for would be zero, and we prefer to use vxor for it.
1104   if (ValSizeInBytes < ByteSize) return SDValue();
1105
1106   // If the element value is larger than the splat value, cut it in half and
1107   // check to see if the two halves are equal.  Continue doing this until we
1108   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1109   while (ValSizeInBytes > ByteSize) {
1110     ValSizeInBytes >>= 1;
1111
1112     // If the top half equals the bottom half, we're still ok.
1113     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1114          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1115       return SDValue();
1116   }
1117
1118   // Properly sign extend the value.
1119   int MaskVal = SignExtend32(Value, ByteSize * 8);
1120
1121   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1122   if (MaskVal == 0) return SDValue();
1123
1124   // Finally, if this value fits in a 5 bit sext field, return it
1125   if (SignExtend32<5>(MaskVal) == MaskVal)
1126     return DAG.getTargetConstant(MaskVal, MVT::i32);
1127   return SDValue();
1128 }
1129
1130 //===----------------------------------------------------------------------===//
1131 //  Addressing Mode Selection
1132 //===----------------------------------------------------------------------===//
1133
1134 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1135 /// or 64-bit immediate, and if the value can be accurately represented as a
1136 /// sign extension from a 16-bit value.  If so, this returns true and the
1137 /// immediate.
1138 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1139   if (N->getOpcode() != ISD::Constant)
1140     return false;
1141
1142   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1143   if (N->getValueType(0) == MVT::i32)
1144     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1145   else
1146     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1147 }
1148 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1149   return isIntS16Immediate(Op.getNode(), Imm);
1150 }
1151
1152
1153 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1154 /// can be represented as an indexed [r+r] operation.  Returns false if it
1155 /// can be more efficiently represented with [r+imm].
1156 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1157                                             SDValue &Index,
1158                                             SelectionDAG &DAG) const {
1159   short imm = 0;
1160   if (N.getOpcode() == ISD::ADD) {
1161     if (isIntS16Immediate(N.getOperand(1), imm))
1162       return false;    // r+i
1163     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1164       return false;    // r+i
1165
1166     Base = N.getOperand(0);
1167     Index = N.getOperand(1);
1168     return true;
1169   } else if (N.getOpcode() == ISD::OR) {
1170     if (isIntS16Immediate(N.getOperand(1), imm))
1171       return false;    // r+i can fold it if we can.
1172
1173     // If this is an or of disjoint bitfields, we can codegen this as an add
1174     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1175     // disjoint.
1176     APInt LHSKnownZero, LHSKnownOne;
1177     APInt RHSKnownZero, RHSKnownOne;
1178     DAG.computeKnownBits(N.getOperand(0),
1179                          LHSKnownZero, LHSKnownOne);
1180
1181     if (LHSKnownZero.getBoolValue()) {
1182       DAG.computeKnownBits(N.getOperand(1),
1183                            RHSKnownZero, RHSKnownOne);
1184       // If all of the bits are known zero on the LHS or RHS, the add won't
1185       // carry.
1186       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1187         Base = N.getOperand(0);
1188         Index = N.getOperand(1);
1189         return true;
1190       }
1191     }
1192   }
1193
1194   return false;
1195 }
1196
1197 // If we happen to be doing an i64 load or store into a stack slot that has
1198 // less than a 4-byte alignment, then the frame-index elimination may need to
1199 // use an indexed load or store instruction (because the offset may not be a
1200 // multiple of 4). The extra register needed to hold the offset comes from the
1201 // register scavenger, and it is possible that the scavenger will need to use
1202 // an emergency spill slot. As a result, we need to make sure that a spill slot
1203 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1204 // stack slot.
1205 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1206   // FIXME: This does not handle the LWA case.
1207   if (VT != MVT::i64)
1208     return;
1209
1210   // NOTE: We'll exclude negative FIs here, which come from argument
1211   // lowering, because there are no known test cases triggering this problem
1212   // using packed structures (or similar). We can remove this exclusion if
1213   // we find such a test case. The reason why this is so test-case driven is
1214   // because this entire 'fixup' is only to prevent crashes (from the
1215   // register scavenger) on not-really-valid inputs. For example, if we have:
1216   //   %a = alloca i1
1217   //   %b = bitcast i1* %a to i64*
1218   //   store i64* a, i64 b
1219   // then the store should really be marked as 'align 1', but is not. If it
1220   // were marked as 'align 1' then the indexed form would have been
1221   // instruction-selected initially, and the problem this 'fixup' is preventing
1222   // won't happen regardless.
1223   if (FrameIdx < 0)
1224     return;
1225
1226   MachineFunction &MF = DAG.getMachineFunction();
1227   MachineFrameInfo *MFI = MF.getFrameInfo();
1228
1229   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1230   if (Align >= 4)
1231     return;
1232
1233   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1234   FuncInfo->setHasNonRISpills();
1235 }
1236
1237 /// Returns true if the address N can be represented by a base register plus
1238 /// a signed 16-bit displacement [r+imm], and if it is not better
1239 /// represented as reg+reg.  If Aligned is true, only accept displacements
1240 /// suitable for STD and friends, i.e. multiples of 4.
1241 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1242                                             SDValue &Base,
1243                                             SelectionDAG &DAG,
1244                                             bool Aligned) const {
1245   // FIXME dl should come from parent load or store, not from address
1246   SDLoc dl(N);
1247   // If this can be more profitably realized as r+r, fail.
1248   if (SelectAddressRegReg(N, Disp, Base, DAG))
1249     return false;
1250
1251   if (N.getOpcode() == ISD::ADD) {
1252     short imm = 0;
1253     if (isIntS16Immediate(N.getOperand(1), imm) &&
1254         (!Aligned || (imm & 3) == 0)) {
1255       Disp = DAG.getTargetConstant(imm, N.getValueType());
1256       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1257         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1258         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1259       } else {
1260         Base = N.getOperand(0);
1261       }
1262       return true; // [r+i]
1263     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1264       // Match LOAD (ADD (X, Lo(G))).
1265       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1266              && "Cannot handle constant offsets yet!");
1267       Disp = N.getOperand(1).getOperand(0);  // The global address.
1268       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1269              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1270              Disp.getOpcode() == ISD::TargetConstantPool ||
1271              Disp.getOpcode() == ISD::TargetJumpTable);
1272       Base = N.getOperand(0);
1273       return true;  // [&g+r]
1274     }
1275   } else if (N.getOpcode() == ISD::OR) {
1276     short imm = 0;
1277     if (isIntS16Immediate(N.getOperand(1), imm) &&
1278         (!Aligned || (imm & 3) == 0)) {
1279       // If this is an or of disjoint bitfields, we can codegen this as an add
1280       // (for better address arithmetic) if the LHS and RHS of the OR are
1281       // provably disjoint.
1282       APInt LHSKnownZero, LHSKnownOne;
1283       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1284
1285       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1286         // If all of the bits are known zero on the LHS or RHS, the add won't
1287         // carry.
1288         Base = N.getOperand(0);
1289         Disp = DAG.getTargetConstant(imm, N.getValueType());
1290         return true;
1291       }
1292     }
1293   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1294     // Loading from a constant address.
1295
1296     // If this address fits entirely in a 16-bit sext immediate field, codegen
1297     // this as "d, 0"
1298     short Imm;
1299     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1300       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1301       Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1302                              CN->getValueType(0));
1303       return true;
1304     }
1305
1306     // Handle 32-bit sext immediates with LIS + addr mode.
1307     if ((CN->getValueType(0) == MVT::i32 ||
1308          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1309         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1310       int Addr = (int)CN->getZExtValue();
1311
1312       // Otherwise, break this down into an LIS + disp.
1313       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1314
1315       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1316       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1317       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1318       return true;
1319     }
1320   }
1321
1322   Disp = DAG.getTargetConstant(0, getPointerTy());
1323   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1324     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1325     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1326   } else
1327     Base = N;
1328   return true;      // [r+0]
1329 }
1330
1331 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1332 /// represented as an indexed [r+r] operation.
1333 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1334                                                 SDValue &Index,
1335                                                 SelectionDAG &DAG) const {
1336   // Check to see if we can easily represent this as an [r+r] address.  This
1337   // will fail if it thinks that the address is more profitably represented as
1338   // reg+imm, e.g. where imm = 0.
1339   if (SelectAddressRegReg(N, Base, Index, DAG))
1340     return true;
1341
1342   // If the operand is an addition, always emit this as [r+r], since this is
1343   // better (for code size, and execution, as the memop does the add for free)
1344   // than emitting an explicit add.
1345   if (N.getOpcode() == ISD::ADD) {
1346     Base = N.getOperand(0);
1347     Index = N.getOperand(1);
1348     return true;
1349   }
1350
1351   // Otherwise, do it the hard way, using R0 as the base register.
1352   Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1353                          N.getValueType());
1354   Index = N;
1355   return true;
1356 }
1357
1358 /// getPreIndexedAddressParts - returns true by value, base pointer and
1359 /// offset pointer and addressing mode by reference if the node's address
1360 /// can be legally represented as pre-indexed load / store address.
1361 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1362                                                   SDValue &Offset,
1363                                                   ISD::MemIndexedMode &AM,
1364                                                   SelectionDAG &DAG) const {
1365   if (DisablePPCPreinc) return false;
1366
1367   bool isLoad = true;
1368   SDValue Ptr;
1369   EVT VT;
1370   unsigned Alignment;
1371   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1372     Ptr = LD->getBasePtr();
1373     VT = LD->getMemoryVT();
1374     Alignment = LD->getAlignment();
1375   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1376     Ptr = ST->getBasePtr();
1377     VT  = ST->getMemoryVT();
1378     Alignment = ST->getAlignment();
1379     isLoad = false;
1380   } else
1381     return false;
1382
1383   // PowerPC doesn't have preinc load/store instructions for vectors.
1384   if (VT.isVector())
1385     return false;
1386
1387   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1388
1389     // Common code will reject creating a pre-inc form if the base pointer
1390     // is a frame index, or if N is a store and the base pointer is either
1391     // the same as or a predecessor of the value being stored.  Check for
1392     // those situations here, and try with swapped Base/Offset instead.
1393     bool Swap = false;
1394
1395     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1396       Swap = true;
1397     else if (!isLoad) {
1398       SDValue Val = cast<StoreSDNode>(N)->getValue();
1399       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1400         Swap = true;
1401     }
1402
1403     if (Swap)
1404       std::swap(Base, Offset);
1405
1406     AM = ISD::PRE_INC;
1407     return true;
1408   }
1409
1410   // LDU/STU can only handle immediates that are a multiple of 4.
1411   if (VT != MVT::i64) {
1412     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1413       return false;
1414   } else {
1415     // LDU/STU need an address with at least 4-byte alignment.
1416     if (Alignment < 4)
1417       return false;
1418
1419     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1420       return false;
1421   }
1422
1423   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1424     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1425     // sext i32 to i64 when addr mode is r+i.
1426     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1427         LD->getExtensionType() == ISD::SEXTLOAD &&
1428         isa<ConstantSDNode>(Offset))
1429       return false;
1430   }
1431
1432   AM = ISD::PRE_INC;
1433   return true;
1434 }
1435
1436 //===----------------------------------------------------------------------===//
1437 //  LowerOperation implementation
1438 //===----------------------------------------------------------------------===//
1439
1440 /// GetLabelAccessInfo - Return true if we should reference labels using a
1441 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1442 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1443                                unsigned &LoOpFlags,
1444                                const GlobalValue *GV = nullptr) {
1445   HiOpFlags = PPCII::MO_HA;
1446   LoOpFlags = PPCII::MO_LO;
1447
1448   // Don't use the pic base if not in PIC relocation model.  Or if we are on a
1449   // non-darwin platform.  We don't support PIC on other platforms yet.
1450   bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1451                TM.getSubtarget<PPCSubtarget>().isDarwin();
1452   if (isPIC) {
1453     HiOpFlags |= PPCII::MO_PIC_FLAG;
1454     LoOpFlags |= PPCII::MO_PIC_FLAG;
1455   }
1456
1457   // If this is a reference to a global value that requires a non-lazy-ptr, make
1458   // sure that instruction lowering adds it.
1459   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1460     HiOpFlags |= PPCII::MO_NLP_FLAG;
1461     LoOpFlags |= PPCII::MO_NLP_FLAG;
1462
1463     if (GV->hasHiddenVisibility()) {
1464       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1465       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1466     }
1467   }
1468
1469   return isPIC;
1470 }
1471
1472 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1473                              SelectionDAG &DAG) {
1474   EVT PtrVT = HiPart.getValueType();
1475   SDValue Zero = DAG.getConstant(0, PtrVT);
1476   SDLoc DL(HiPart);
1477
1478   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1479   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1480
1481   // With PIC, the first instruction is actually "GR+hi(&G)".
1482   if (isPIC)
1483     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1484                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1485
1486   // Generate non-pic code that has direct accesses to the constant pool.
1487   // The address of the global is just (hi(&g)+lo(&g)).
1488   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1489 }
1490
1491 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1492                                              SelectionDAG &DAG) const {
1493   EVT PtrVT = Op.getValueType();
1494   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1495   const Constant *C = CP->getConstVal();
1496
1497   // 64-bit SVR4 ABI code is always position-independent.
1498   // The actual address of the GlobalValue is stored in the TOC.
1499   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1500     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1501     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1502                        DAG.getRegister(PPC::X2, MVT::i64));
1503   }
1504
1505   unsigned MOHiFlag, MOLoFlag;
1506   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1507   SDValue CPIHi =
1508     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1509   SDValue CPILo =
1510     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1511   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1512 }
1513
1514 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1515   EVT PtrVT = Op.getValueType();
1516   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1517
1518   // 64-bit SVR4 ABI code is always position-independent.
1519   // The actual address of the GlobalValue is stored in the TOC.
1520   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1521     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1522     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1523                        DAG.getRegister(PPC::X2, MVT::i64));
1524   }
1525
1526   unsigned MOHiFlag, MOLoFlag;
1527   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1528   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1529   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1530   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1531 }
1532
1533 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1534                                              SelectionDAG &DAG) const {
1535   EVT PtrVT = Op.getValueType();
1536
1537   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1538
1539   unsigned MOHiFlag, MOLoFlag;
1540   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1541   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1542   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1543   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1544 }
1545
1546 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1547                                               SelectionDAG &DAG) const {
1548
1549   // FIXME: TLS addresses currently use medium model code sequences,
1550   // which is the most useful form.  Eventually support for small and
1551   // large models could be added if users need it, at the cost of
1552   // additional complexity.
1553   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1554   SDLoc dl(GA);
1555   const GlobalValue *GV = GA->getGlobal();
1556   EVT PtrVT = getPointerTy();
1557   bool is64bit = PPCSubTarget.isPPC64();
1558
1559   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1560
1561   if (Model == TLSModel::LocalExec) {
1562     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1563                                                PPCII::MO_TPREL_HA);
1564     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1565                                                PPCII::MO_TPREL_LO);
1566     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1567                                      is64bit ? MVT::i64 : MVT::i32);
1568     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1569     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1570   }
1571
1572   if (Model == TLSModel::InitialExec) {
1573     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1574     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1575                                                 PPCII::MO_TLS);
1576     SDValue GOTPtr;
1577     if (is64bit) {
1578       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1579       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1580                            PtrVT, GOTReg, TGA);
1581     } else
1582       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1583     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1584                                    PtrVT, TGA, GOTPtr);
1585     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1586   }
1587
1588   if (Model == TLSModel::GeneralDynamic) {
1589     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1590     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1591     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1592                                      GOTReg, TGA);
1593     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1594                                    GOTEntryHi, TGA);
1595
1596     // We need a chain node, and don't have one handy.  The underlying
1597     // call has no side effects, so using the function entry node
1598     // suffices.
1599     SDValue Chain = DAG.getEntryNode();
1600     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1601     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1602     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1603                                   PtrVT, ParmReg, TGA);
1604     // The return value from GET_TLS_ADDR really is in X3 already, but
1605     // some hacks are needed here to tie everything together.  The extra
1606     // copies dissolve during subsequent transforms.
1607     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1608     return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1609   }
1610
1611   if (Model == TLSModel::LocalDynamic) {
1612     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1613     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1614     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1615                                      GOTReg, TGA);
1616     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1617                                    GOTEntryHi, TGA);
1618
1619     // We need a chain node, and don't have one handy.  The underlying
1620     // call has no side effects, so using the function entry node
1621     // suffices.
1622     SDValue Chain = DAG.getEntryNode();
1623     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1624     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1625     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1626                                   PtrVT, ParmReg, TGA);
1627     // The return value from GET_TLSLD_ADDR really is in X3 already, but
1628     // some hacks are needed here to tie everything together.  The extra
1629     // copies dissolve during subsequent transforms.
1630     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1631     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1632                                       Chain, ParmReg, TGA);
1633     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1634   }
1635
1636   llvm_unreachable("Unknown TLS model!");
1637 }
1638
1639 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1640                                               SelectionDAG &DAG) const {
1641   EVT PtrVT = Op.getValueType();
1642   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1643   SDLoc DL(GSDN);
1644   const GlobalValue *GV = GSDN->getGlobal();
1645
1646   // 64-bit SVR4 ABI code is always position-independent.
1647   // The actual address of the GlobalValue is stored in the TOC.
1648   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1649     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1650     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1651                        DAG.getRegister(PPC::X2, MVT::i64));
1652   }
1653
1654   unsigned MOHiFlag, MOLoFlag;
1655   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1656
1657   SDValue GAHi =
1658     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1659   SDValue GALo =
1660     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1661
1662   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1663
1664   // If the global reference is actually to a non-lazy-pointer, we have to do an
1665   // extra load to get the address of the global.
1666   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1667     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1668                       false, false, false, 0);
1669   return Ptr;
1670 }
1671
1672 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1673   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1674   SDLoc dl(Op);
1675
1676   if (Op.getValueType() == MVT::v2i64) {
1677     // When the operands themselves are v2i64 values, we need to do something
1678     // special because VSX has no underlying comparison operations for these.
1679     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1680       // Equality can be handled by casting to the legal type for Altivec
1681       // comparisons, everything else needs to be expanded.
1682       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1683         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1684                  DAG.getSetCC(dl, MVT::v4i32,
1685                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1686                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1687                    CC));
1688       }
1689
1690       return SDValue();
1691     }
1692
1693     // We handle most of these in the usual way.
1694     return Op;
1695   }
1696
1697   // If we're comparing for equality to zero, expose the fact that this is
1698   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1699   // fold the new nodes.
1700   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1701     if (C->isNullValue() && CC == ISD::SETEQ) {
1702       EVT VT = Op.getOperand(0).getValueType();
1703       SDValue Zext = Op.getOperand(0);
1704       if (VT.bitsLT(MVT::i32)) {
1705         VT = MVT::i32;
1706         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1707       }
1708       unsigned Log2b = Log2_32(VT.getSizeInBits());
1709       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1710       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1711                                 DAG.getConstant(Log2b, MVT::i32));
1712       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1713     }
1714     // Leave comparisons against 0 and -1 alone for now, since they're usually
1715     // optimized.  FIXME: revisit this when we can custom lower all setcc
1716     // optimizations.
1717     if (C->isAllOnesValue() || C->isNullValue())
1718       return SDValue();
1719   }
1720
1721   // If we have an integer seteq/setne, turn it into a compare against zero
1722   // by xor'ing the rhs with the lhs, which is faster than setting a
1723   // condition register, reading it back out, and masking the correct bit.  The
1724   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1725   // the result to other bit-twiddling opportunities.
1726   EVT LHSVT = Op.getOperand(0).getValueType();
1727   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1728     EVT VT = Op.getValueType();
1729     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1730                                 Op.getOperand(1));
1731     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1732   }
1733   return SDValue();
1734 }
1735
1736 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1737                                       const PPCSubtarget &Subtarget) const {
1738   SDNode *Node = Op.getNode();
1739   EVT VT = Node->getValueType(0);
1740   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1741   SDValue InChain = Node->getOperand(0);
1742   SDValue VAListPtr = Node->getOperand(1);
1743   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1744   SDLoc dl(Node);
1745
1746   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1747
1748   // gpr_index
1749   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1750                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1751                                     false, false, 0);
1752   InChain = GprIndex.getValue(1);
1753
1754   if (VT == MVT::i64) {
1755     // Check if GprIndex is even
1756     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1757                                  DAG.getConstant(1, MVT::i32));
1758     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1759                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1760     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1761                                           DAG.getConstant(1, MVT::i32));
1762     // Align GprIndex to be even if it isn't
1763     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1764                            GprIndex);
1765   }
1766
1767   // fpr index is 1 byte after gpr
1768   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1769                                DAG.getConstant(1, MVT::i32));
1770
1771   // fpr
1772   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1773                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1774                                     false, false, 0);
1775   InChain = FprIndex.getValue(1);
1776
1777   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1778                                        DAG.getConstant(8, MVT::i32));
1779
1780   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1781                                         DAG.getConstant(4, MVT::i32));
1782
1783   // areas
1784   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1785                                      MachinePointerInfo(), false, false,
1786                                      false, 0);
1787   InChain = OverflowArea.getValue(1);
1788
1789   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1790                                     MachinePointerInfo(), false, false,
1791                                     false, 0);
1792   InChain = RegSaveArea.getValue(1);
1793
1794   // select overflow_area if index > 8
1795   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1796                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1797
1798   // adjustment constant gpr_index * 4/8
1799   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1800                                     VT.isInteger() ? GprIndex : FprIndex,
1801                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1802                                                     MVT::i32));
1803
1804   // OurReg = RegSaveArea + RegConstant
1805   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1806                                RegConstant);
1807
1808   // Floating types are 32 bytes into RegSaveArea
1809   if (VT.isFloatingPoint())
1810     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1811                          DAG.getConstant(32, MVT::i32));
1812
1813   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1814   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1815                                    VT.isInteger() ? GprIndex : FprIndex,
1816                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1817                                                    MVT::i32));
1818
1819   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1820                               VT.isInteger() ? VAListPtr : FprPtr,
1821                               MachinePointerInfo(SV),
1822                               MVT::i8, false, false, 0);
1823
1824   // determine if we should load from reg_save_area or overflow_area
1825   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1826
1827   // increase overflow_area by 4/8 if gpr/fpr > 8
1828   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1829                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1830                                           MVT::i32));
1831
1832   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1833                              OverflowAreaPlusN);
1834
1835   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1836                               OverflowAreaPtr,
1837                               MachinePointerInfo(),
1838                               MVT::i32, false, false, 0);
1839
1840   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1841                      false, false, false, 0);
1842 }
1843
1844 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1845                                        const PPCSubtarget &Subtarget) const {
1846   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1847
1848   // We have to copy the entire va_list struct:
1849   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1850   return DAG.getMemcpy(Op.getOperand(0), Op,
1851                        Op.getOperand(1), Op.getOperand(2),
1852                        DAG.getConstant(12, MVT::i32), 8, false, true,
1853                        MachinePointerInfo(), MachinePointerInfo());
1854 }
1855
1856 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1857                                                   SelectionDAG &DAG) const {
1858   return Op.getOperand(0);
1859 }
1860
1861 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1862                                                 SelectionDAG &DAG) const {
1863   SDValue Chain = Op.getOperand(0);
1864   SDValue Trmp = Op.getOperand(1); // trampoline
1865   SDValue FPtr = Op.getOperand(2); // nested function
1866   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1867   SDLoc dl(Op);
1868
1869   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1870   bool isPPC64 = (PtrVT == MVT::i64);
1871   Type *IntPtrTy =
1872     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1873                                                              *DAG.getContext());
1874
1875   TargetLowering::ArgListTy Args;
1876   TargetLowering::ArgListEntry Entry;
1877
1878   Entry.Ty = IntPtrTy;
1879   Entry.Node = Trmp; Args.push_back(Entry);
1880
1881   // TrampSize == (isPPC64 ? 48 : 40);
1882   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1883                                isPPC64 ? MVT::i64 : MVT::i32);
1884   Args.push_back(Entry);
1885
1886   Entry.Node = FPtr; Args.push_back(Entry);
1887   Entry.Node = Nest; Args.push_back(Entry);
1888
1889   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1890   TargetLowering::CallLoweringInfo CLI(Chain,
1891                                        Type::getVoidTy(*DAG.getContext()),
1892                                        false, false, false, false, 0,
1893                                        CallingConv::C,
1894                 /*isTailCall=*/false,
1895                                        /*doesNotRet=*/false,
1896                                        /*isReturnValueUsed=*/true,
1897                 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1898                 Args, DAG, dl);
1899   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1900
1901   return CallResult.second;
1902 }
1903
1904 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1905                                         const PPCSubtarget &Subtarget) const {
1906   MachineFunction &MF = DAG.getMachineFunction();
1907   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1908
1909   SDLoc dl(Op);
1910
1911   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1912     // vastart just stores the address of the VarArgsFrameIndex slot into the
1913     // memory location argument.
1914     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1915     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1916     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1917     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1918                         MachinePointerInfo(SV),
1919                         false, false, 0);
1920   }
1921
1922   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1923   // We suppose the given va_list is already allocated.
1924   //
1925   // typedef struct {
1926   //  char gpr;     /* index into the array of 8 GPRs
1927   //                 * stored in the register save area
1928   //                 * gpr=0 corresponds to r3,
1929   //                 * gpr=1 to r4, etc.
1930   //                 */
1931   //  char fpr;     /* index into the array of 8 FPRs
1932   //                 * stored in the register save area
1933   //                 * fpr=0 corresponds to f1,
1934   //                 * fpr=1 to f2, etc.
1935   //                 */
1936   //  char *overflow_arg_area;
1937   //                /* location on stack that holds
1938   //                 * the next overflow argument
1939   //                 */
1940   //  char *reg_save_area;
1941   //               /* where r3:r10 and f1:f8 (if saved)
1942   //                * are stored
1943   //                */
1944   // } va_list[1];
1945
1946
1947   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1948   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1949
1950
1951   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1952
1953   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1954                                             PtrVT);
1955   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1956                                  PtrVT);
1957
1958   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1959   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1960
1961   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1962   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1963
1964   uint64_t FPROffset = 1;
1965   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1966
1967   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1968
1969   // Store first byte : number of int regs
1970   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1971                                          Op.getOperand(1),
1972                                          MachinePointerInfo(SV),
1973                                          MVT::i8, false, false, 0);
1974   uint64_t nextOffset = FPROffset;
1975   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1976                                   ConstFPROffset);
1977
1978   // Store second byte : number of float regs
1979   SDValue secondStore =
1980     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1981                       MachinePointerInfo(SV, nextOffset), MVT::i8,
1982                       false, false, 0);
1983   nextOffset += StackOffset;
1984   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1985
1986   // Store second word : arguments given on stack
1987   SDValue thirdStore =
1988     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1989                  MachinePointerInfo(SV, nextOffset),
1990                  false, false, 0);
1991   nextOffset += FrameOffset;
1992   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1993
1994   // Store third word : arguments given in registers
1995   return DAG.getStore(thirdStore, dl, FR, nextPtr,
1996                       MachinePointerInfo(SV, nextOffset),
1997                       false, false, 0);
1998
1999 }
2000
2001 #include "PPCGenCallingConv.inc"
2002
2003 // Function whose sole purpose is to kill compiler warnings 
2004 // stemming from unused functions included from PPCGenCallingConv.inc.
2005 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2006   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2007 }
2008
2009 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2010                                       CCValAssign::LocInfo &LocInfo,
2011                                       ISD::ArgFlagsTy &ArgFlags,
2012                                       CCState &State) {
2013   return true;
2014 }
2015
2016 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2017                                              MVT &LocVT,
2018                                              CCValAssign::LocInfo &LocInfo,
2019                                              ISD::ArgFlagsTy &ArgFlags,
2020                                              CCState &State) {
2021   static const MCPhysReg ArgRegs[] = {
2022     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2023     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2024   };
2025   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2026
2027   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2028
2029   // Skip one register if the first unallocated register has an even register
2030   // number and there are still argument registers available which have not been
2031   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2032   // need to skip a register if RegNum is odd.
2033   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2034     State.AllocateReg(ArgRegs[RegNum]);
2035   }
2036
2037   // Always return false here, as this function only makes sure that the first
2038   // unallocated register has an odd register number and does not actually
2039   // allocate a register for the current argument.
2040   return false;
2041 }
2042
2043 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2044                                                MVT &LocVT,
2045                                                CCValAssign::LocInfo &LocInfo,
2046                                                ISD::ArgFlagsTy &ArgFlags,
2047                                                CCState &State) {
2048   static const MCPhysReg ArgRegs[] = {
2049     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2050     PPC::F8
2051   };
2052
2053   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2054
2055   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2056
2057   // If there is only one Floating-point register left we need to put both f64
2058   // values of a split ppc_fp128 value on the stack.
2059   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2060     State.AllocateReg(ArgRegs[RegNum]);
2061   }
2062
2063   // Always return false here, as this function only makes sure that the two f64
2064   // values a ppc_fp128 value is split into are both passed in registers or both
2065   // passed on the stack and does not actually allocate a register for the
2066   // current argument.
2067   return false;
2068 }
2069
2070 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2071 /// on Darwin.
2072 static const MCPhysReg *GetFPR() {
2073   static const MCPhysReg FPR[] = {
2074     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2075     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2076   };
2077
2078   return FPR;
2079 }
2080
2081 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2082 /// the stack.
2083 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2084                                        unsigned PtrByteSize) {
2085   unsigned ArgSize = ArgVT.getStoreSize();
2086   if (Flags.isByVal())
2087     ArgSize = Flags.getByValSize();
2088   ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2089
2090   return ArgSize;
2091 }
2092
2093 SDValue
2094 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2095                                         CallingConv::ID CallConv, bool isVarArg,
2096                                         const SmallVectorImpl<ISD::InputArg>
2097                                           &Ins,
2098                                         SDLoc dl, SelectionDAG &DAG,
2099                                         SmallVectorImpl<SDValue> &InVals)
2100                                           const {
2101   if (PPCSubTarget.isSVR4ABI()) {
2102     if (PPCSubTarget.isPPC64())
2103       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2104                                          dl, DAG, InVals);
2105     else
2106       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2107                                          dl, DAG, InVals);
2108   } else {
2109     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2110                                        dl, DAG, InVals);
2111   }
2112 }
2113
2114 SDValue
2115 PPCTargetLowering::LowerFormalArguments_32SVR4(
2116                                       SDValue Chain,
2117                                       CallingConv::ID CallConv, bool isVarArg,
2118                                       const SmallVectorImpl<ISD::InputArg>
2119                                         &Ins,
2120                                       SDLoc dl, SelectionDAG &DAG,
2121                                       SmallVectorImpl<SDValue> &InVals) const {
2122
2123   // 32-bit SVR4 ABI Stack Frame Layout:
2124   //              +-----------------------------------+
2125   //        +-->  |            Back chain             |
2126   //        |     +-----------------------------------+
2127   //        |     | Floating-point register save area |
2128   //        |     +-----------------------------------+
2129   //        |     |    General register save area     |
2130   //        |     +-----------------------------------+
2131   //        |     |          CR save word             |
2132   //        |     +-----------------------------------+
2133   //        |     |         VRSAVE save word          |
2134   //        |     +-----------------------------------+
2135   //        |     |         Alignment padding         |
2136   //        |     +-----------------------------------+
2137   //        |     |     Vector register save area     |
2138   //        |     +-----------------------------------+
2139   //        |     |       Local variable space        |
2140   //        |     +-----------------------------------+
2141   //        |     |        Parameter list area        |
2142   //        |     +-----------------------------------+
2143   //        |     |           LR save word            |
2144   //        |     +-----------------------------------+
2145   // SP-->  +---  |            Back chain             |
2146   //              +-----------------------------------+
2147   //
2148   // Specifications:
2149   //   System V Application Binary Interface PowerPC Processor Supplement
2150   //   AltiVec Technology Programming Interface Manual
2151
2152   MachineFunction &MF = DAG.getMachineFunction();
2153   MachineFrameInfo *MFI = MF.getFrameInfo();
2154   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2155
2156   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2157   // Potential tail calls could cause overwriting of argument stack slots.
2158   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2159                        (CallConv == CallingConv::Fast));
2160   unsigned PtrByteSize = 4;
2161
2162   // Assign locations to all of the incoming arguments.
2163   SmallVector<CCValAssign, 16> ArgLocs;
2164   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2165                  getTargetMachine(), ArgLocs, *DAG.getContext());
2166
2167   // Reserve space for the linkage area on the stack.
2168   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2169
2170   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2171
2172   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2173     CCValAssign &VA = ArgLocs[i];
2174
2175     // Arguments stored in registers.
2176     if (VA.isRegLoc()) {
2177       const TargetRegisterClass *RC;
2178       EVT ValVT = VA.getValVT();
2179
2180       switch (ValVT.getSimpleVT().SimpleTy) {
2181         default:
2182           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2183         case MVT::i1:
2184         case MVT::i32:
2185           RC = &PPC::GPRCRegClass;
2186           break;
2187         case MVT::f32:
2188           RC = &PPC::F4RCRegClass;
2189           break;
2190         case MVT::f64:
2191           if (PPCSubTarget.hasVSX())
2192             RC = &PPC::VSFRCRegClass;
2193           else
2194             RC = &PPC::F8RCRegClass;
2195           break;
2196         case MVT::v16i8:
2197         case MVT::v8i16:
2198         case MVT::v4i32:
2199         case MVT::v4f32:
2200           RC = &PPC::VRRCRegClass;
2201           break;
2202         case MVT::v2f64:
2203         case MVT::v2i64:
2204           RC = &PPC::VSHRCRegClass;
2205           break;
2206       }
2207
2208       // Transform the arguments stored in physical registers into virtual ones.
2209       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2210       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2211                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2212
2213       if (ValVT == MVT::i1)
2214         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2215
2216       InVals.push_back(ArgValue);
2217     } else {
2218       // Argument stored in memory.
2219       assert(VA.isMemLoc());
2220
2221       unsigned ArgSize = VA.getLocVT().getStoreSize();
2222       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2223                                       isImmutable);
2224
2225       // Create load nodes to retrieve arguments from the stack.
2226       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2227       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2228                                    MachinePointerInfo(),
2229                                    false, false, false, 0));
2230     }
2231   }
2232
2233   // Assign locations to all of the incoming aggregate by value arguments.
2234   // Aggregates passed by value are stored in the local variable space of the
2235   // caller's stack frame, right above the parameter list area.
2236   SmallVector<CCValAssign, 16> ByValArgLocs;
2237   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2238                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
2239
2240   // Reserve stack space for the allocations in CCInfo.
2241   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2242
2243   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2244
2245   // Area that is at least reserved in the caller of this function.
2246   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2247
2248   // Set the size that is at least reserved in caller of this function.  Tail
2249   // call optimized function's reserved stack space needs to be aligned so that
2250   // taking the difference between two stack areas will result in an aligned
2251   // stack.
2252   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2253
2254   MinReservedArea =
2255     std::max(MinReservedArea,
2256              PPCFrameLowering::getMinCallFrameSize(false, false));
2257
2258   unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2259     getStackAlignment();
2260   unsigned AlignMask = TargetAlign-1;
2261   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2262
2263   FI->setMinReservedArea(MinReservedArea);
2264
2265   SmallVector<SDValue, 8> MemOps;
2266
2267   // If the function takes variable number of arguments, make a frame index for
2268   // the start of the first vararg value... for expansion of llvm.va_start.
2269   if (isVarArg) {
2270     static const MCPhysReg GPArgRegs[] = {
2271       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2272       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2273     };
2274     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2275
2276     static const MCPhysReg FPArgRegs[] = {
2277       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2278       PPC::F8
2279     };
2280     const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2281
2282     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2283                                                           NumGPArgRegs));
2284     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2285                                                           NumFPArgRegs));
2286
2287     // Make room for NumGPArgRegs and NumFPArgRegs.
2288     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2289                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2290
2291     FuncInfo->setVarArgsStackOffset(
2292       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2293                              CCInfo.getNextStackOffset(), true));
2294
2295     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2296     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2297
2298     // The fixed integer arguments of a variadic function are stored to the
2299     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2300     // the result of va_next.
2301     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2302       // Get an existing live-in vreg, or add a new one.
2303       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2304       if (!VReg)
2305         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2306
2307       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2308       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2309                                    MachinePointerInfo(), false, false, 0);
2310       MemOps.push_back(Store);
2311       // Increment the address by four for the next argument to store
2312       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2313       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2314     }
2315
2316     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2317     // is set.
2318     // The double arguments are stored to the VarArgsFrameIndex
2319     // on the stack.
2320     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2321       // Get an existing live-in vreg, or add a new one.
2322       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2323       if (!VReg)
2324         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2325
2326       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2327       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2328                                    MachinePointerInfo(), false, false, 0);
2329       MemOps.push_back(Store);
2330       // Increment the address by eight for the next argument to store
2331       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2332                                          PtrVT);
2333       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2334     }
2335   }
2336
2337   if (!MemOps.empty())
2338     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2339
2340   return Chain;
2341 }
2342
2343 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2344 // value to MVT::i64 and then truncate to the correct register size.
2345 SDValue
2346 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2347                                      SelectionDAG &DAG, SDValue ArgVal,
2348                                      SDLoc dl) const {
2349   if (Flags.isSExt())
2350     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2351                          DAG.getValueType(ObjectVT));
2352   else if (Flags.isZExt())
2353     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2354                          DAG.getValueType(ObjectVT));
2355
2356   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2357 }
2358
2359 // Set the size that is at least reserved in caller of this function.  Tail
2360 // call optimized functions' reserved stack space needs to be aligned so that
2361 // taking the difference between two stack areas will result in an aligned
2362 // stack.
2363 void
2364 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2365                                       unsigned nAltivecParamsAtEnd,
2366                                       unsigned MinReservedArea,
2367                                       bool isPPC64) const {
2368   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2369   // Add the Altivec parameters at the end, if needed.
2370   if (nAltivecParamsAtEnd) {
2371     MinReservedArea = ((MinReservedArea+15)/16)*16;
2372     MinReservedArea += 16*nAltivecParamsAtEnd;
2373   }
2374   MinReservedArea =
2375     std::max(MinReservedArea,
2376              PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2377   unsigned TargetAlign
2378     = DAG.getMachineFunction().getTarget().getFrameLowering()->
2379         getStackAlignment();
2380   unsigned AlignMask = TargetAlign-1;
2381   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2382   FI->setMinReservedArea(MinReservedArea);
2383 }
2384
2385 SDValue
2386 PPCTargetLowering::LowerFormalArguments_64SVR4(
2387                                       SDValue Chain,
2388                                       CallingConv::ID CallConv, bool isVarArg,
2389                                       const SmallVectorImpl<ISD::InputArg>
2390                                         &Ins,
2391                                       SDLoc dl, SelectionDAG &DAG,
2392                                       SmallVectorImpl<SDValue> &InVals) const {
2393   // TODO: add description of PPC stack frame format, or at least some docs.
2394   //
2395   MachineFunction &MF = DAG.getMachineFunction();
2396   MachineFrameInfo *MFI = MF.getFrameInfo();
2397   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2398
2399   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2400   // Potential tail calls could cause overwriting of argument stack slots.
2401   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2402                        (CallConv == CallingConv::Fast));
2403   unsigned PtrByteSize = 8;
2404
2405   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2406   // Area that is at least reserved in caller of this function.
2407   unsigned MinReservedArea = ArgOffset;
2408
2409   static const MCPhysReg GPR[] = {
2410     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2411     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2412   };
2413
2414   static const MCPhysReg *FPR = GetFPR();
2415
2416   static const MCPhysReg VR[] = {
2417     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2418     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2419   };
2420   static const MCPhysReg VSRH[] = {
2421     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2422     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2423   };
2424
2425   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2426   const unsigned Num_FPR_Regs = 13;
2427   const unsigned Num_VR_Regs  = array_lengthof(VR);
2428
2429   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2430
2431   // Add DAG nodes to load the arguments or copy them out of registers.  On
2432   // entry to a function on PPC, the arguments start after the linkage area,
2433   // although the first ones are often in registers.
2434
2435   SmallVector<SDValue, 8> MemOps;
2436   unsigned nAltivecParamsAtEnd = 0;
2437   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2438   unsigned CurArgIdx = 0;
2439   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2440     SDValue ArgVal;
2441     bool needsLoad = false;
2442     EVT ObjectVT = Ins[ArgNo].VT;
2443     unsigned ObjSize = ObjectVT.getStoreSize();
2444     unsigned ArgSize = ObjSize;
2445     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2446     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2447     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2448
2449     unsigned CurArgOffset = ArgOffset;
2450
2451     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2452     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2453         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2454         ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2455       if (isVarArg) {
2456         MinReservedArea = ((MinReservedArea+15)/16)*16;
2457         MinReservedArea += CalculateStackSlotSize(ObjectVT,
2458                                                   Flags,
2459                                                   PtrByteSize);
2460       } else
2461         nAltivecParamsAtEnd++;
2462     } else
2463       // Calculate min reserved area.
2464       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2465                                                 Flags,
2466                                                 PtrByteSize);
2467
2468     // FIXME the codegen can be much improved in some cases.
2469     // We do not have to keep everything in memory.
2470     if (Flags.isByVal()) {
2471       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2472       ObjSize = Flags.getByValSize();
2473       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2474       // Empty aggregate parameters do not take up registers.  Examples:
2475       //   struct { } a;
2476       //   union  { } b;
2477       //   int c[0];
2478       // etc.  However, we have to provide a place-holder in InVals, so
2479       // pretend we have an 8-byte item at the current address for that
2480       // purpose.
2481       if (!ObjSize) {
2482         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2483         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2484         InVals.push_back(FIN);
2485         continue;
2486       }
2487
2488       unsigned BVAlign = Flags.getByValAlign();
2489       if (BVAlign > 8) {
2490         ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2491         CurArgOffset = ArgOffset;
2492       }
2493
2494       // All aggregates smaller than 8 bytes must be passed right-justified.
2495       if (ObjSize < PtrByteSize)
2496         CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2497       // The value of the object is its address.
2498       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2499       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2500       InVals.push_back(FIN);
2501
2502       if (ObjSize < 8) {
2503         if (GPR_idx != Num_GPR_Regs) {
2504           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2505           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2506           SDValue Store;
2507
2508           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2509             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2510                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2511             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2512                                       MachinePointerInfo(FuncArg),
2513                                       ObjType, false, false, 0);
2514           } else {
2515             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2516             // store the whole register as-is to the parameter save area
2517             // slot.  The address of the parameter was already calculated
2518             // above (InVals.push_back(FIN)) to be the right-justified
2519             // offset within the slot.  For this store, we need a new
2520             // frame index that points at the beginning of the slot.
2521             int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2522             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2523             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2524                                  MachinePointerInfo(FuncArg),
2525                                  false, false, 0);
2526           }
2527
2528           MemOps.push_back(Store);
2529           ++GPR_idx;
2530         }
2531         // Whether we copied from a register or not, advance the offset
2532         // into the parameter save area by a full doubleword.
2533         ArgOffset += PtrByteSize;
2534         continue;
2535       }
2536
2537       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2538         // Store whatever pieces of the object are in registers
2539         // to memory.  ArgOffset will be the address of the beginning
2540         // of the object.
2541         if (GPR_idx != Num_GPR_Regs) {
2542           unsigned VReg;
2543           VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2544           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2545           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2546           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2547           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2548                                        MachinePointerInfo(FuncArg, j),
2549                                        false, false, 0);
2550           MemOps.push_back(Store);
2551           ++GPR_idx;
2552           ArgOffset += PtrByteSize;
2553         } else {
2554           ArgOffset += ArgSize - j;
2555           break;
2556         }
2557       }
2558       continue;
2559     }
2560
2561     switch (ObjectVT.getSimpleVT().SimpleTy) {
2562     default: llvm_unreachable("Unhandled argument type!");
2563     case MVT::i1:
2564     case MVT::i32:
2565     case MVT::i64:
2566       if (GPR_idx != Num_GPR_Regs) {
2567         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2568         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2569
2570         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2571           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2572           // value to MVT::i64 and then truncate to the correct register size.
2573           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2574
2575         ++GPR_idx;
2576       } else {
2577         needsLoad = true;
2578         ArgSize = PtrByteSize;
2579       }
2580       ArgOffset += 8;
2581       break;
2582
2583     case MVT::f32:
2584     case MVT::f64:
2585       // Every 8 bytes of argument space consumes one of the GPRs available for
2586       // argument passing.
2587       if (GPR_idx != Num_GPR_Regs) {
2588         ++GPR_idx;
2589       }
2590       if (FPR_idx != Num_FPR_Regs) {
2591         unsigned VReg;
2592
2593         if (ObjectVT == MVT::f32)
2594           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2595         else
2596           VReg = MF.addLiveIn(FPR[FPR_idx], PPCSubTarget.hasVSX() ?
2597                                             &PPC::VSFRCRegClass :
2598                                             &PPC::F8RCRegClass);
2599
2600         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2601         ++FPR_idx;
2602       } else {
2603         needsLoad = true;
2604         ArgSize = PtrByteSize;
2605       }
2606
2607       ArgOffset += 8;
2608       break;
2609     case MVT::v4f32:
2610     case MVT::v4i32:
2611     case MVT::v8i16:
2612     case MVT::v16i8:
2613     case MVT::v2f64:
2614     case MVT::v2i64:
2615       // Note that vector arguments in registers don't reserve stack space,
2616       // except in varargs functions.
2617       if (VR_idx != Num_VR_Regs) {
2618         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2619                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2620                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2621         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2622         if (isVarArg) {
2623           while ((ArgOffset % 16) != 0) {
2624             ArgOffset += PtrByteSize;
2625             if (GPR_idx != Num_GPR_Regs)
2626               GPR_idx++;
2627           }
2628           ArgOffset += 16;
2629           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2630         }
2631         ++VR_idx;
2632       } else {
2633         // Vectors are aligned.
2634         ArgOffset = ((ArgOffset+15)/16)*16;
2635         CurArgOffset = ArgOffset;
2636         ArgOffset += 16;
2637         needsLoad = true;
2638       }
2639       break;
2640     }
2641
2642     // We need to load the argument to a virtual register if we determined
2643     // above that we ran out of physical registers of the appropriate type.
2644     if (needsLoad) {
2645       int FI = MFI->CreateFixedObject(ObjSize,
2646                                       CurArgOffset + (ArgSize - ObjSize),
2647                                       isImmutable);
2648       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2649       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2650                            false, false, false, 0);
2651     }
2652
2653     InVals.push_back(ArgVal);
2654   }
2655
2656   // Set the size that is at least reserved in caller of this function.  Tail
2657   // call optimized functions' reserved stack space needs to be aligned so that
2658   // taking the difference between two stack areas will result in an aligned
2659   // stack.
2660   setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2661
2662   // If the function takes variable number of arguments, make a frame index for
2663   // the start of the first vararg value... for expansion of llvm.va_start.
2664   if (isVarArg) {
2665     int Depth = ArgOffset;
2666
2667     FuncInfo->setVarArgsFrameIndex(
2668       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2669     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2670
2671     // If this function is vararg, store any remaining integer argument regs
2672     // to their spots on the stack so that they may be loaded by deferencing the
2673     // result of va_next.
2674     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2675       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2676       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2677       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2678                                    MachinePointerInfo(), false, false, 0);
2679       MemOps.push_back(Store);
2680       // Increment the address by four for the next argument to store
2681       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2682       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2683     }
2684   }
2685
2686   if (!MemOps.empty())
2687     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2688
2689   return Chain;
2690 }
2691
2692 SDValue
2693 PPCTargetLowering::LowerFormalArguments_Darwin(
2694                                       SDValue Chain,
2695                                       CallingConv::ID CallConv, bool isVarArg,
2696                                       const SmallVectorImpl<ISD::InputArg>
2697                                         &Ins,
2698                                       SDLoc dl, SelectionDAG &DAG,
2699                                       SmallVectorImpl<SDValue> &InVals) const {
2700   // TODO: add description of PPC stack frame format, or at least some docs.
2701   //
2702   MachineFunction &MF = DAG.getMachineFunction();
2703   MachineFrameInfo *MFI = MF.getFrameInfo();
2704   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2705
2706   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2707   bool isPPC64 = PtrVT == MVT::i64;
2708   // Potential tail calls could cause overwriting of argument stack slots.
2709   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2710                        (CallConv == CallingConv::Fast));
2711   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2712
2713   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2714   // Area that is at least reserved in caller of this function.
2715   unsigned MinReservedArea = ArgOffset;
2716
2717   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2718     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2719     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2720   };
2721   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2722     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2723     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2724   };
2725
2726   static const MCPhysReg *FPR = GetFPR();
2727
2728   static const MCPhysReg VR[] = {
2729     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2730     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2731   };
2732
2733   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2734   const unsigned Num_FPR_Regs = 13;
2735   const unsigned Num_VR_Regs  = array_lengthof( VR);
2736
2737   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2738
2739   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2740
2741   // In 32-bit non-varargs functions, the stack space for vectors is after the
2742   // stack space for non-vectors.  We do not use this space unless we have
2743   // too many vectors to fit in registers, something that only occurs in
2744   // constructed examples:), but we have to walk the arglist to figure
2745   // that out...for the pathological case, compute VecArgOffset as the
2746   // start of the vector parameter area.  Computing VecArgOffset is the
2747   // entire point of the following loop.
2748   unsigned VecArgOffset = ArgOffset;
2749   if (!isVarArg && !isPPC64) {
2750     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2751          ++ArgNo) {
2752       EVT ObjectVT = Ins[ArgNo].VT;
2753       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2754
2755       if (Flags.isByVal()) {
2756         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2757         unsigned ObjSize = Flags.getByValSize();
2758         unsigned ArgSize =
2759                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2760         VecArgOffset += ArgSize;
2761         continue;
2762       }
2763
2764       switch(ObjectVT.getSimpleVT().SimpleTy) {
2765       default: llvm_unreachable("Unhandled argument type!");
2766       case MVT::i1:
2767       case MVT::i32:
2768       case MVT::f32:
2769         VecArgOffset += 4;
2770         break;
2771       case MVT::i64:  // PPC64
2772       case MVT::f64:
2773         // FIXME: We are guaranteed to be !isPPC64 at this point.
2774         // Does MVT::i64 apply?
2775         VecArgOffset += 8;
2776         break;
2777       case MVT::v4f32:
2778       case MVT::v4i32:
2779       case MVT::v8i16:
2780       case MVT::v16i8:
2781         // Nothing to do, we're only looking at Nonvector args here.
2782         break;
2783       }
2784     }
2785   }
2786   // We've found where the vector parameter area in memory is.  Skip the
2787   // first 12 parameters; these don't use that memory.
2788   VecArgOffset = ((VecArgOffset+15)/16)*16;
2789   VecArgOffset += 12*16;
2790
2791   // Add DAG nodes to load the arguments or copy them out of registers.  On
2792   // entry to a function on PPC, the arguments start after the linkage area,
2793   // although the first ones are often in registers.
2794
2795   SmallVector<SDValue, 8> MemOps;
2796   unsigned nAltivecParamsAtEnd = 0;
2797   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2798   unsigned CurArgIdx = 0;
2799   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2800     SDValue ArgVal;
2801     bool needsLoad = false;
2802     EVT ObjectVT = Ins[ArgNo].VT;
2803     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2804     unsigned ArgSize = ObjSize;
2805     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2806     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2807     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2808
2809     unsigned CurArgOffset = ArgOffset;
2810
2811     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2812     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2813         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2814       if (isVarArg || isPPC64) {
2815         MinReservedArea = ((MinReservedArea+15)/16)*16;
2816         MinReservedArea += CalculateStackSlotSize(ObjectVT,
2817                                                   Flags,
2818                                                   PtrByteSize);
2819       } else  nAltivecParamsAtEnd++;
2820     } else
2821       // Calculate min reserved area.
2822       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2823                                                 Flags,
2824                                                 PtrByteSize);
2825
2826     // FIXME the codegen can be much improved in some cases.
2827     // We do not have to keep everything in memory.
2828     if (Flags.isByVal()) {
2829       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2830       ObjSize = Flags.getByValSize();
2831       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2832       // Objects of size 1 and 2 are right justified, everything else is
2833       // left justified.  This means the memory address is adjusted forwards.
2834       if (ObjSize==1 || ObjSize==2) {
2835         CurArgOffset = CurArgOffset + (4 - ObjSize);
2836       }
2837       // The value of the object is its address.
2838       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2839       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2840       InVals.push_back(FIN);
2841       if (ObjSize==1 || ObjSize==2) {
2842         if (GPR_idx != Num_GPR_Regs) {
2843           unsigned VReg;
2844           if (isPPC64)
2845             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2846           else
2847             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2848           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2849           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2850           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2851                                             MachinePointerInfo(FuncArg),
2852                                             ObjType, false, false, 0);
2853           MemOps.push_back(Store);
2854           ++GPR_idx;
2855         }
2856
2857         ArgOffset += PtrByteSize;
2858
2859         continue;
2860       }
2861       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2862         // Store whatever pieces of the object are in registers
2863         // to memory.  ArgOffset will be the address of the beginning
2864         // of the object.
2865         if (GPR_idx != Num_GPR_Regs) {
2866           unsigned VReg;
2867           if (isPPC64)
2868             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2869           else
2870             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2871           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2872           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2873           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2874           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2875                                        MachinePointerInfo(FuncArg, j),
2876                                        false, false, 0);
2877           MemOps.push_back(Store);
2878           ++GPR_idx;
2879           ArgOffset += PtrByteSize;
2880         } else {
2881           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2882           break;
2883         }
2884       }
2885       continue;
2886     }
2887
2888     switch (ObjectVT.getSimpleVT().SimpleTy) {
2889     default: llvm_unreachable("Unhandled argument type!");
2890     case MVT::i1:
2891     case MVT::i32:
2892       if (!isPPC64) {
2893         if (GPR_idx != Num_GPR_Regs) {
2894           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2895           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2896
2897           if (ObjectVT == MVT::i1)
2898             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2899
2900           ++GPR_idx;
2901         } else {
2902           needsLoad = true;
2903           ArgSize = PtrByteSize;
2904         }
2905         // All int arguments reserve stack space in the Darwin ABI.
2906         ArgOffset += PtrByteSize;
2907         break;
2908       }
2909       // FALLTHROUGH
2910     case MVT::i64:  // PPC64
2911       if (GPR_idx != Num_GPR_Regs) {
2912         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2913         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2914
2915         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2916           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2917           // value to MVT::i64 and then truncate to the correct register size.
2918           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2919
2920         ++GPR_idx;
2921       } else {
2922         needsLoad = true;
2923         ArgSize = PtrByteSize;
2924       }
2925       // All int arguments reserve stack space in the Darwin ABI.
2926       ArgOffset += 8;
2927       break;
2928
2929     case MVT::f32:
2930     case MVT::f64:
2931       // Every 4 bytes of argument space consumes one of the GPRs available for
2932       // argument passing.
2933       if (GPR_idx != Num_GPR_Regs) {
2934         ++GPR_idx;
2935         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2936           ++GPR_idx;
2937       }
2938       if (FPR_idx != Num_FPR_Regs) {
2939         unsigned VReg;
2940
2941         if (ObjectVT == MVT::f32)
2942           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2943         else
2944           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2945
2946         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2947         ++FPR_idx;
2948       } else {
2949         needsLoad = true;
2950       }
2951
2952       // All FP arguments reserve stack space in the Darwin ABI.
2953       ArgOffset += isPPC64 ? 8 : ObjSize;
2954       break;
2955     case MVT::v4f32:
2956     case MVT::v4i32:
2957     case MVT::v8i16:
2958     case MVT::v16i8:
2959       // Note that vector arguments in registers don't reserve stack space,
2960       // except in varargs functions.
2961       if (VR_idx != Num_VR_Regs) {
2962         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2963         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2964         if (isVarArg) {
2965           while ((ArgOffset % 16) != 0) {
2966             ArgOffset += PtrByteSize;
2967             if (GPR_idx != Num_GPR_Regs)
2968               GPR_idx++;
2969           }
2970           ArgOffset += 16;
2971           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2972         }
2973         ++VR_idx;
2974       } else {
2975         if (!isVarArg && !isPPC64) {
2976           // Vectors go after all the nonvectors.
2977           CurArgOffset = VecArgOffset;
2978           VecArgOffset += 16;
2979         } else {
2980           // Vectors are aligned.
2981           ArgOffset = ((ArgOffset+15)/16)*16;
2982           CurArgOffset = ArgOffset;
2983           ArgOffset += 16;
2984         }
2985         needsLoad = true;
2986       }
2987       break;
2988     }
2989
2990     // We need to load the argument to a virtual register if we determined above
2991     // that we ran out of physical registers of the appropriate type.
2992     if (needsLoad) {
2993       int FI = MFI->CreateFixedObject(ObjSize,
2994                                       CurArgOffset + (ArgSize - ObjSize),
2995                                       isImmutable);
2996       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2997       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2998                            false, false, false, 0);
2999     }
3000
3001     InVals.push_back(ArgVal);
3002   }
3003
3004   // Set the size that is at least reserved in caller of this function.  Tail
3005   // call optimized functions' reserved stack space needs to be aligned so that
3006   // taking the difference between two stack areas will result in an aligned
3007   // stack.
3008   setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
3009
3010   // If the function takes variable number of arguments, make a frame index for
3011   // the start of the first vararg value... for expansion of llvm.va_start.
3012   if (isVarArg) {
3013     int Depth = ArgOffset;
3014
3015     FuncInfo->setVarArgsFrameIndex(
3016       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3017                              Depth, true));
3018     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3019
3020     // If this function is vararg, store any remaining integer argument regs
3021     // to their spots on the stack so that they may be loaded by deferencing the
3022     // result of va_next.
3023     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3024       unsigned VReg;
3025
3026       if (isPPC64)
3027         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3028       else
3029         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3030
3031       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3032       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3033                                    MachinePointerInfo(), false, false, 0);
3034       MemOps.push_back(Store);
3035       // Increment the address by four for the next argument to store
3036       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3037       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3038     }
3039   }
3040
3041   if (!MemOps.empty())
3042     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3043
3044   return Chain;
3045 }
3046
3047 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3048 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3049 static unsigned
3050 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3051                                      bool isPPC64,
3052                                      bool isVarArg,
3053                                      unsigned CC,
3054                                      const SmallVectorImpl<ISD::OutputArg>
3055                                        &Outs,
3056                                      const SmallVectorImpl<SDValue> &OutVals,
3057                                      unsigned &nAltivecParamsAtEnd) {
3058   // Count how many bytes are to be pushed on the stack, including the linkage
3059   // area, and parameter passing area.  We start with 24/48 bytes, which is
3060   // prereserved space for [SP][CR][LR][3 x unused].
3061   unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3062   unsigned NumOps = Outs.size();
3063   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3064
3065   // Add up all the space actually used.
3066   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3067   // they all go in registers, but we must reserve stack space for them for
3068   // possible use by the caller.  In varargs or 64-bit calls, parameters are
3069   // assigned stack space in order, with padding so Altivec parameters are
3070   // 16-byte aligned.
3071   nAltivecParamsAtEnd = 0;
3072   for (unsigned i = 0; i != NumOps; ++i) {
3073     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3074     EVT ArgVT = Outs[i].VT;
3075     // Varargs Altivec parameters are padded to a 16 byte boundary.
3076     if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3077         ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3078         ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3079       if (!isVarArg && !isPPC64) {
3080         // Non-varargs Altivec parameters go after all the non-Altivec
3081         // parameters; handle those later so we know how much padding we need.
3082         nAltivecParamsAtEnd++;
3083         continue;
3084       }
3085       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3086       NumBytes = ((NumBytes+15)/16)*16;
3087     }
3088     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3089   }
3090
3091    // Allow for Altivec parameters at the end, if needed.
3092   if (nAltivecParamsAtEnd) {
3093     NumBytes = ((NumBytes+15)/16)*16;
3094     NumBytes += 16*nAltivecParamsAtEnd;
3095   }
3096
3097   // The prolog code of the callee may store up to 8 GPR argument registers to
3098   // the stack, allowing va_start to index over them in memory if its varargs.
3099   // Because we cannot tell if this is needed on the caller side, we have to
3100   // conservatively assume that it is needed.  As such, make sure we have at
3101   // least enough stack space for the caller to store the 8 GPRs.
3102   NumBytes = std::max(NumBytes,
3103                       PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3104
3105   // Tail call needs the stack to be aligned.
3106   if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3107     unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3108       getFrameLowering()->getStackAlignment();
3109     unsigned AlignMask = TargetAlign-1;
3110     NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3111   }
3112
3113   return NumBytes;
3114 }
3115
3116 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3117 /// adjusted to accommodate the arguments for the tailcall.
3118 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3119                                    unsigned ParamSize) {
3120
3121   if (!isTailCall) return 0;
3122
3123   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3124   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3125   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3126   // Remember only if the new adjustement is bigger.
3127   if (SPDiff < FI->getTailCallSPDelta())
3128     FI->setTailCallSPDelta(SPDiff);
3129
3130   return SPDiff;
3131 }
3132
3133 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3134 /// for tail call optimization. Targets which want to do tail call
3135 /// optimization should implement this function.
3136 bool
3137 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3138                                                      CallingConv::ID CalleeCC,
3139                                                      bool isVarArg,
3140                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3141                                                      SelectionDAG& DAG) const {
3142   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3143     return false;
3144
3145   // Variable argument functions are not supported.
3146   if (isVarArg)
3147     return false;
3148
3149   MachineFunction &MF = DAG.getMachineFunction();
3150   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3151   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3152     // Functions containing by val parameters are not supported.
3153     for (unsigned i = 0; i != Ins.size(); i++) {
3154        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3155        if (Flags.isByVal()) return false;
3156     }
3157
3158     // Non-PIC/GOT tail calls are supported.
3159     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3160       return true;
3161
3162     // At the moment we can only do local tail calls (in same module, hidden
3163     // or protected) if we are generating PIC.
3164     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3165       return G->getGlobal()->hasHiddenVisibility()
3166           || G->getGlobal()->hasProtectedVisibility();
3167   }
3168
3169   return false;
3170 }
3171
3172 /// isCallCompatibleAddress - Return the immediate to use if the specified
3173 /// 32-bit value is representable in the immediate field of a BxA instruction.
3174 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3175   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3176   if (!C) return nullptr;
3177
3178   int Addr = C->getZExtValue();
3179   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3180       SignExtend32<26>(Addr) != Addr)
3181     return nullptr;  // Top 6 bits have to be sext of immediate.
3182
3183   return DAG.getConstant((int)C->getZExtValue() >> 2,
3184                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3185 }
3186
3187 namespace {
3188
3189 struct TailCallArgumentInfo {
3190   SDValue Arg;
3191   SDValue FrameIdxOp;
3192   int       FrameIdx;
3193
3194   TailCallArgumentInfo() : FrameIdx(0) {}
3195 };
3196
3197 }
3198
3199 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3200 static void
3201 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3202                                            SDValue Chain,
3203                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3204                    SmallVectorImpl<SDValue> &MemOpChains,
3205                    SDLoc dl) {
3206   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3207     SDValue Arg = TailCallArgs[i].Arg;
3208     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3209     int FI = TailCallArgs[i].FrameIdx;
3210     // Store relative to framepointer.
3211     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3212                                        MachinePointerInfo::getFixedStack(FI),
3213                                        false, false, 0));
3214   }
3215 }
3216
3217 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3218 /// the appropriate stack slot for the tail call optimized function call.
3219 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3220                                                MachineFunction &MF,
3221                                                SDValue Chain,
3222                                                SDValue OldRetAddr,
3223                                                SDValue OldFP,
3224                                                int SPDiff,
3225                                                bool isPPC64,
3226                                                bool isDarwinABI,
3227                                                SDLoc dl) {
3228   if (SPDiff) {
3229     // Calculate the new stack slot for the return address.
3230     int SlotSize = isPPC64 ? 8 : 4;
3231     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3232                                                                    isDarwinABI);
3233     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3234                                                           NewRetAddrLoc, true);
3235     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3236     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3237     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3238                          MachinePointerInfo::getFixedStack(NewRetAddr),
3239                          false, false, 0);
3240
3241     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3242     // slot as the FP is never overwritten.
3243     if (isDarwinABI) {
3244       int NewFPLoc =
3245         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3246       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3247                                                           true);
3248       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3249       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3250                            MachinePointerInfo::getFixedStack(NewFPIdx),
3251                            false, false, 0);
3252     }
3253   }
3254   return Chain;
3255 }
3256
3257 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3258 /// the position of the argument.
3259 static void
3260 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3261                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3262                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3263   int Offset = ArgOffset + SPDiff;
3264   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3265   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3266   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3267   SDValue FIN = DAG.getFrameIndex(FI, VT);
3268   TailCallArgumentInfo Info;
3269   Info.Arg = Arg;
3270   Info.FrameIdxOp = FIN;
3271   Info.FrameIdx = FI;
3272   TailCallArguments.push_back(Info);
3273 }
3274
3275 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3276 /// stack slot. Returns the chain as result and the loaded frame pointers in
3277 /// LROpOut/FPOpout. Used when tail calling.
3278 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3279                                                         int SPDiff,
3280                                                         SDValue Chain,
3281                                                         SDValue &LROpOut,
3282                                                         SDValue &FPOpOut,
3283                                                         bool isDarwinABI,
3284                                                         SDLoc dl) const {
3285   if (SPDiff) {
3286     // Load the LR and FP stack slot for later adjusting.
3287     EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3288     LROpOut = getReturnAddrFrameIndex(DAG);
3289     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3290                           false, false, false, 0);
3291     Chain = SDValue(LROpOut.getNode(), 1);
3292
3293     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3294     // slot as the FP is never overwritten.
3295     if (isDarwinABI) {
3296       FPOpOut = getFramePointerFrameIndex(DAG);
3297       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3298                             false, false, false, 0);
3299       Chain = SDValue(FPOpOut.getNode(), 1);
3300     }
3301   }
3302   return Chain;
3303 }
3304
3305 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3306 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3307 /// specified by the specific parameter attribute. The copy will be passed as
3308 /// a byval function parameter.
3309 /// Sometimes what we are copying is the end of a larger object, the part that
3310 /// does not fit in registers.
3311 static SDValue
3312 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3313                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3314                           SDLoc dl) {
3315   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3316   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3317                        false, false, MachinePointerInfo(),
3318                        MachinePointerInfo());
3319 }
3320
3321 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3322 /// tail calls.
3323 static void
3324 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3325                  SDValue Arg, SDValue PtrOff, int SPDiff,
3326                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3327                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3328                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3329                  SDLoc dl) {
3330   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3331   if (!isTailCall) {
3332     if (isVector) {
3333       SDValue StackPtr;
3334       if (isPPC64)
3335         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3336       else
3337         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3338       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3339                            DAG.getConstant(ArgOffset, PtrVT));
3340     }
3341     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3342                                        MachinePointerInfo(), false, false, 0));
3343   // Calculate and remember argument location.
3344   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3345                                   TailCallArguments);
3346 }
3347
3348 static
3349 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3350                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3351                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3352                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3353   MachineFunction &MF = DAG.getMachineFunction();
3354
3355   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3356   // might overwrite each other in case of tail call optimization.
3357   SmallVector<SDValue, 8> MemOpChains2;
3358   // Do not flag preceding copytoreg stuff together with the following stuff.
3359   InFlag = SDValue();
3360   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3361                                     MemOpChains2, dl);
3362   if (!MemOpChains2.empty())
3363     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3364
3365   // Store the return address to the appropriate stack slot.
3366   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3367                                         isPPC64, isDarwinABI, dl);
3368
3369   // Emit callseq_end just before tailcall node.
3370   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3371                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3372   InFlag = Chain.getValue(1);
3373 }
3374
3375 static
3376 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3377                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3378                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3379                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3380                      const PPCSubtarget &PPCSubTarget) {
3381
3382   bool isPPC64 = PPCSubTarget.isPPC64();
3383   bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3384
3385   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3386   NodeTys.push_back(MVT::Other);   // Returns a chain
3387   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3388
3389   unsigned CallOpc = PPCISD::CALL;
3390
3391   bool needIndirectCall = true;
3392   if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3393     // If this is an absolute destination address, use the munged value.
3394     Callee = SDValue(Dest, 0);
3395     needIndirectCall = false;
3396   }
3397
3398   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3399     // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3400     // Use indirect calls for ALL functions calls in JIT mode, since the
3401     // far-call stubs may be outside relocation limits for a BL instruction.
3402     if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3403       unsigned OpFlags = 0;
3404       if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3405           (PPCSubTarget.getTargetTriple().isMacOSX() &&
3406            PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3407           (G->getGlobal()->isDeclaration() ||
3408            G->getGlobal()->isWeakForLinker())) {
3409         // PC-relative references to external symbols should go through $stub,
3410         // unless we're building with the leopard linker or later, which
3411         // automatically synthesizes these stubs.
3412         OpFlags = PPCII::MO_DARWIN_STUB;
3413       }
3414
3415       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3416       // every direct call is) turn it into a TargetGlobalAddress /
3417       // TargetExternalSymbol node so that legalize doesn't hack it.
3418       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3419                                           Callee.getValueType(),
3420                                           0, OpFlags);
3421       needIndirectCall = false;
3422     }
3423   }
3424
3425   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3426     unsigned char OpFlags = 0;
3427
3428     if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3429         (PPCSubTarget.getTargetTriple().isMacOSX() &&
3430          PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3431       // PC-relative references to external symbols should go through $stub,
3432       // unless we're building with the leopard linker or later, which
3433       // automatically synthesizes these stubs.
3434       OpFlags = PPCII::MO_DARWIN_STUB;
3435     }
3436
3437     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3438                                          OpFlags);
3439     needIndirectCall = false;
3440   }
3441
3442   if (needIndirectCall) {
3443     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3444     // to do the call, we can't use PPCISD::CALL.
3445     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3446
3447     if (isSVR4ABI && isPPC64) {
3448       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3449       // entry point, but to the function descriptor (the function entry point
3450       // address is part of the function descriptor though).
3451       // The function descriptor is a three doubleword structure with the
3452       // following fields: function entry point, TOC base address and
3453       // environment pointer.
3454       // Thus for a call through a function pointer, the following actions need
3455       // to be performed:
3456       //   1. Save the TOC of the caller in the TOC save area of its stack
3457       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3458       //   2. Load the address of the function entry point from the function
3459       //      descriptor.
3460       //   3. Load the TOC of the callee from the function descriptor into r2.
3461       //   4. Load the environment pointer from the function descriptor into
3462       //      r11.
3463       //   5. Branch to the function entry point address.
3464       //   6. On return of the callee, the TOC of the caller needs to be
3465       //      restored (this is done in FinishCall()).
3466       //
3467       // All those operations are flagged together to ensure that no other
3468       // operations can be scheduled in between. E.g. without flagging the
3469       // operations together, a TOC access in the caller could be scheduled
3470       // between the load of the callee TOC and the branch to the callee, which
3471       // results in the TOC access going through the TOC of the callee instead
3472       // of going through the TOC of the caller, which leads to incorrect code.
3473
3474       // Load the address of the function entry point from the function
3475       // descriptor.
3476       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3477       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3478                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3479       Chain = LoadFuncPtr.getValue(1);
3480       InFlag = LoadFuncPtr.getValue(2);
3481
3482       // Load environment pointer into r11.
3483       // Offset of the environment pointer within the function descriptor.
3484       SDValue PtrOff = DAG.getIntPtrConstant(16);
3485
3486       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3487       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3488                                        InFlag);
3489       Chain = LoadEnvPtr.getValue(1);
3490       InFlag = LoadEnvPtr.getValue(2);
3491
3492       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3493                                         InFlag);
3494       Chain = EnvVal.getValue(0);
3495       InFlag = EnvVal.getValue(1);
3496
3497       // Load TOC of the callee into r2. We are using a target-specific load
3498       // with r2 hard coded, because the result of a target-independent load
3499       // would never go directly into r2, since r2 is a reserved register (which
3500       // prevents the register allocator from allocating it), resulting in an
3501       // additional register being allocated and an unnecessary move instruction
3502       // being generated.
3503       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3504       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3505                                        Callee, InFlag);
3506       Chain = LoadTOCPtr.getValue(0);
3507       InFlag = LoadTOCPtr.getValue(1);
3508
3509       MTCTROps[0] = Chain;
3510       MTCTROps[1] = LoadFuncPtr;
3511       MTCTROps[2] = InFlag;
3512     }
3513
3514     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3515                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3516     InFlag = Chain.getValue(1);
3517
3518     NodeTys.clear();
3519     NodeTys.push_back(MVT::Other);
3520     NodeTys.push_back(MVT::Glue);
3521     Ops.push_back(Chain);
3522     CallOpc = PPCISD::BCTRL;
3523     Callee.setNode(nullptr);
3524     // Add use of X11 (holding environment pointer)
3525     if (isSVR4ABI && isPPC64)
3526       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3527     // Add CTR register as callee so a bctr can be emitted later.
3528     if (isTailCall)
3529       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3530   }
3531
3532   // If this is a direct call, pass the chain and the callee.
3533   if (Callee.getNode()) {
3534     Ops.push_back(Chain);
3535     Ops.push_back(Callee);
3536   }
3537   // If this is a tail call add stack pointer delta.
3538   if (isTailCall)
3539     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3540
3541   // Add argument registers to the end of the list so that they are known live
3542   // into the call.
3543   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3544     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3545                                   RegsToPass[i].second.getValueType()));
3546
3547   return CallOpc;
3548 }
3549
3550 static
3551 bool isLocalCall(const SDValue &Callee)
3552 {
3553   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3554     return !G->getGlobal()->isDeclaration() &&
3555            !G->getGlobal()->isWeakForLinker();
3556   return false;
3557 }
3558
3559 SDValue
3560 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3561                                    CallingConv::ID CallConv, bool isVarArg,
3562                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3563                                    SDLoc dl, SelectionDAG &DAG,
3564                                    SmallVectorImpl<SDValue> &InVals) const {
3565
3566   SmallVector<CCValAssign, 16> RVLocs;
3567   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3568                     getTargetMachine(), RVLocs, *DAG.getContext());
3569   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3570
3571   // Copy all of the result registers out of their specified physreg.
3572   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3573     CCValAssign &VA = RVLocs[i];
3574     assert(VA.isRegLoc() && "Can only return in registers!");
3575
3576     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3577                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3578     Chain = Val.getValue(1);
3579     InFlag = Val.getValue(2);
3580
3581     switch (VA.getLocInfo()) {
3582     default: llvm_unreachable("Unknown loc info!");
3583     case CCValAssign::Full: break;
3584     case CCValAssign::AExt:
3585       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3586       break;
3587     case CCValAssign::ZExt:
3588       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3589                         DAG.getValueType(VA.getValVT()));
3590       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3591       break;
3592     case CCValAssign::SExt:
3593       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3594                         DAG.getValueType(VA.getValVT()));
3595       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3596       break;
3597     }
3598
3599     InVals.push_back(Val);
3600   }
3601
3602   return Chain;
3603 }
3604
3605 SDValue
3606 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3607                               bool isTailCall, bool isVarArg,
3608                               SelectionDAG &DAG,
3609                               SmallVector<std::pair<unsigned, SDValue>, 8>
3610                                 &RegsToPass,
3611                               SDValue InFlag, SDValue Chain,
3612                               SDValue &Callee,
3613                               int SPDiff, unsigned NumBytes,
3614                               const SmallVectorImpl<ISD::InputArg> &Ins,
3615                               SmallVectorImpl<SDValue> &InVals) const {
3616   std::vector<EVT> NodeTys;
3617   SmallVector<SDValue, 8> Ops;
3618   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3619                                  isTailCall, RegsToPass, Ops, NodeTys,
3620                                  PPCSubTarget);
3621
3622   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3623   if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3624     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3625
3626   // When performing tail call optimization the callee pops its arguments off
3627   // the stack. Account for this here so these bytes can be pushed back on in
3628   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3629   int BytesCalleePops =
3630     (CallConv == CallingConv::Fast &&
3631      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3632
3633   // Add a register mask operand representing the call-preserved registers.
3634   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3635   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3636   assert(Mask && "Missing call preserved mask for calling convention");
3637   Ops.push_back(DAG.getRegisterMask(Mask));
3638
3639   if (InFlag.getNode())
3640     Ops.push_back(InFlag);
3641
3642   // Emit tail call.
3643   if (isTailCall) {
3644     assert(((Callee.getOpcode() == ISD::Register &&
3645              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3646             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3647             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3648             isa<ConstantSDNode>(Callee)) &&
3649     "Expecting an global address, external symbol, absolute value or register");
3650
3651     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3652   }
3653
3654   // Add a NOP immediately after the branch instruction when using the 64-bit
3655   // SVR4 ABI. At link time, if caller and callee are in a different module and
3656   // thus have a different TOC, the call will be replaced with a call to a stub
3657   // function which saves the current TOC, loads the TOC of the callee and
3658   // branches to the callee. The NOP will be replaced with a load instruction
3659   // which restores the TOC of the caller from the TOC save slot of the current
3660   // stack frame. If caller and callee belong to the same module (and have the
3661   // same TOC), the NOP will remain unchanged.
3662
3663   bool needsTOCRestore = false;
3664   if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3665     if (CallOpc == PPCISD::BCTRL) {
3666       // This is a call through a function pointer.
3667       // Restore the caller TOC from the save area into R2.
3668       // See PrepareCall() for more information about calls through function
3669       // pointers in the 64-bit SVR4 ABI.
3670       // We are using a target-specific load with r2 hard coded, because the
3671       // result of a target-independent load would never go directly into r2,
3672       // since r2 is a reserved register (which prevents the register allocator
3673       // from allocating it), resulting in an additional register being
3674       // allocated and an unnecessary move instruction being generated.
3675       needsTOCRestore = true;
3676     } else if ((CallOpc == PPCISD::CALL) &&
3677                (!isLocalCall(Callee) ||
3678                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3679       // Otherwise insert NOP for non-local calls.
3680       CallOpc = PPCISD::CALL_NOP;
3681     }
3682   }
3683
3684   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3685   InFlag = Chain.getValue(1);
3686
3687   if (needsTOCRestore) {
3688     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3689     Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3690     InFlag = Chain.getValue(1);
3691   }
3692
3693   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3694                              DAG.getIntPtrConstant(BytesCalleePops, true),
3695                              InFlag, dl);
3696   if (!Ins.empty())
3697     InFlag = Chain.getValue(1);
3698
3699   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3700                          Ins, dl, DAG, InVals);
3701 }
3702
3703 SDValue
3704 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3705                              SmallVectorImpl<SDValue> &InVals) const {
3706   SelectionDAG &DAG                     = CLI.DAG;
3707   SDLoc &dl                             = CLI.DL;
3708   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3709   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3710   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3711   SDValue Chain                         = CLI.Chain;
3712   SDValue Callee                        = CLI.Callee;
3713   bool &isTailCall                      = CLI.IsTailCall;
3714   CallingConv::ID CallConv              = CLI.CallConv;
3715   bool isVarArg                         = CLI.IsVarArg;
3716
3717   if (isTailCall)
3718     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3719                                                    Ins, DAG);
3720
3721   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3722     report_fatal_error("failed to perform tail call elimination on a call "
3723                        "site marked musttail");
3724
3725   if (PPCSubTarget.isSVR4ABI()) {
3726     if (PPCSubTarget.isPPC64())
3727       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3728                               isTailCall, Outs, OutVals, Ins,
3729                               dl, DAG, InVals);
3730     else
3731       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3732                               isTailCall, Outs, OutVals, Ins,
3733                               dl, DAG, InVals);
3734   }
3735
3736   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3737                           isTailCall, Outs, OutVals, Ins,
3738                           dl, DAG, InVals);
3739 }
3740
3741 SDValue
3742 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3743                                     CallingConv::ID CallConv, bool isVarArg,
3744                                     bool isTailCall,
3745                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3746                                     const SmallVectorImpl<SDValue> &OutVals,
3747                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3748                                     SDLoc dl, SelectionDAG &DAG,
3749                                     SmallVectorImpl<SDValue> &InVals) const {
3750   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3751   // of the 32-bit SVR4 ABI stack frame layout.
3752
3753   assert((CallConv == CallingConv::C ||
3754           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3755
3756   unsigned PtrByteSize = 4;
3757
3758   MachineFunction &MF = DAG.getMachineFunction();
3759
3760   // Mark this function as potentially containing a function that contains a
3761   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3762   // and restoring the callers stack pointer in this functions epilog. This is
3763   // done because by tail calling the called function might overwrite the value
3764   // in this function's (MF) stack pointer stack slot 0(SP).
3765   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3766       CallConv == CallingConv::Fast)
3767     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3768
3769   // Count how many bytes are to be pushed on the stack, including the linkage
3770   // area, parameter list area and the part of the local variable space which
3771   // contains copies of aggregates which are passed by value.
3772
3773   // Assign locations to all of the outgoing arguments.
3774   SmallVector<CCValAssign, 16> ArgLocs;
3775   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3776                  getTargetMachine(), ArgLocs, *DAG.getContext());
3777
3778   // Reserve space for the linkage area on the stack.
3779   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3780
3781   if (isVarArg) {
3782     // Handle fixed and variable vector arguments differently.
3783     // Fixed vector arguments go into registers as long as registers are
3784     // available. Variable vector arguments always go into memory.
3785     unsigned NumArgs = Outs.size();
3786
3787     for (unsigned i = 0; i != NumArgs; ++i) {
3788       MVT ArgVT = Outs[i].VT;
3789       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3790       bool Result;
3791
3792       if (Outs[i].IsFixed) {
3793         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3794                                CCInfo);
3795       } else {
3796         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3797                                       ArgFlags, CCInfo);
3798       }
3799
3800       if (Result) {
3801 #ifndef NDEBUG
3802         errs() << "Call operand #" << i << " has unhandled type "
3803              << EVT(ArgVT).getEVTString() << "\n";
3804 #endif
3805         llvm_unreachable(nullptr);
3806       }
3807     }
3808   } else {
3809     // All arguments are treated the same.
3810     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3811   }
3812
3813   // Assign locations to all of the outgoing aggregate by value arguments.
3814   SmallVector<CCValAssign, 16> ByValArgLocs;
3815   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3816                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
3817
3818   // Reserve stack space for the allocations in CCInfo.
3819   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3820
3821   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3822
3823   // Size of the linkage area, parameter list area and the part of the local
3824   // space variable where copies of aggregates which are passed by value are
3825   // stored.
3826   unsigned NumBytes = CCByValInfo.getNextStackOffset();
3827
3828   // Calculate by how many bytes the stack has to be adjusted in case of tail
3829   // call optimization.
3830   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3831
3832   // Adjust the stack pointer for the new arguments...
3833   // These operations are automatically eliminated by the prolog/epilog pass
3834   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3835                                dl);
3836   SDValue CallSeqStart = Chain;
3837
3838   // Load the return address and frame pointer so it can be moved somewhere else
3839   // later.
3840   SDValue LROp, FPOp;
3841   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3842                                        dl);
3843
3844   // Set up a copy of the stack pointer for use loading and storing any
3845   // arguments that may not fit in the registers available for argument
3846   // passing.
3847   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3848
3849   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3850   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3851   SmallVector<SDValue, 8> MemOpChains;
3852
3853   bool seenFloatArg = false;
3854   // Walk the register/memloc assignments, inserting copies/loads.
3855   for (unsigned i = 0, j = 0, e = ArgLocs.size();
3856        i != e;
3857        ++i) {
3858     CCValAssign &VA = ArgLocs[i];
3859     SDValue Arg = OutVals[i];
3860     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3861
3862     if (Flags.isByVal()) {
3863       // Argument is an aggregate which is passed by value, thus we need to
3864       // create a copy of it in the local variable space of the current stack
3865       // frame (which is the stack frame of the caller) and pass the address of
3866       // this copy to the callee.
3867       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3868       CCValAssign &ByValVA = ByValArgLocs[j++];
3869       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3870
3871       // Memory reserved in the local variable space of the callers stack frame.
3872       unsigned LocMemOffset = ByValVA.getLocMemOffset();
3873
3874       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3875       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3876
3877       // Create a copy of the argument in the local area of the current
3878       // stack frame.
3879       SDValue MemcpyCall =
3880         CreateCopyOfByValArgument(Arg, PtrOff,
3881                                   CallSeqStart.getNode()->getOperand(0),
3882                                   Flags, DAG, dl);
3883
3884       // This must go outside the CALLSEQ_START..END.
3885       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3886                            CallSeqStart.getNode()->getOperand(1),
3887                            SDLoc(MemcpyCall));
3888       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3889                              NewCallSeqStart.getNode());
3890       Chain = CallSeqStart = NewCallSeqStart;
3891
3892       // Pass the address of the aggregate copy on the stack either in a
3893       // physical register or in the parameter list area of the current stack
3894       // frame to the callee.
3895       Arg = PtrOff;
3896     }
3897
3898     if (VA.isRegLoc()) {
3899       if (Arg.getValueType() == MVT::i1)
3900         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3901
3902       seenFloatArg |= VA.getLocVT().isFloatingPoint();
3903       // Put argument in a physical register.
3904       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3905     } else {
3906       // Put argument in the parameter list area of the current stack frame.
3907       assert(VA.isMemLoc());
3908       unsigned LocMemOffset = VA.getLocMemOffset();
3909
3910       if (!isTailCall) {
3911         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3912         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3913
3914         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3915                                            MachinePointerInfo(),
3916                                            false, false, 0));
3917       } else {
3918         // Calculate and remember argument location.
3919         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3920                                  TailCallArguments);
3921       }
3922     }
3923   }
3924
3925   if (!MemOpChains.empty())
3926     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3927
3928   // Build a sequence of copy-to-reg nodes chained together with token chain
3929   // and flag operands which copy the outgoing args into the appropriate regs.
3930   SDValue InFlag;
3931   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3932     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3933                              RegsToPass[i].second, InFlag);
3934     InFlag = Chain.getValue(1);
3935   }
3936
3937   // Set CR bit 6 to true if this is a vararg call with floating args passed in
3938   // registers.
3939   if (isVarArg) {
3940     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3941     SDValue Ops[] = { Chain, InFlag };
3942
3943     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3944                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
3945
3946     InFlag = Chain.getValue(1);
3947   }
3948
3949   if (isTailCall)
3950     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3951                     false, TailCallArguments);
3952
3953   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3954                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3955                     Ins, InVals);
3956 }
3957
3958 // Copy an argument into memory, being careful to do this outside the
3959 // call sequence for the call to which the argument belongs.
3960 SDValue
3961 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3962                                               SDValue CallSeqStart,
3963                                               ISD::ArgFlagsTy Flags,
3964                                               SelectionDAG &DAG,
3965                                               SDLoc dl) const {
3966   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3967                         CallSeqStart.getNode()->getOperand(0),
3968                         Flags, DAG, dl);
3969   // The MEMCPY must go outside the CALLSEQ_START..END.
3970   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3971                              CallSeqStart.getNode()->getOperand(1),
3972                              SDLoc(MemcpyCall));
3973   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3974                          NewCallSeqStart.getNode());
3975   return NewCallSeqStart;
3976 }
3977
3978 SDValue
3979 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3980                                     CallingConv::ID CallConv, bool isVarArg,
3981                                     bool isTailCall,
3982                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3983                                     const SmallVectorImpl<SDValue> &OutVals,
3984                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3985                                     SDLoc dl, SelectionDAG &DAG,
3986                                     SmallVectorImpl<SDValue> &InVals) const {
3987
3988   unsigned NumOps = Outs.size();
3989
3990   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3991   unsigned PtrByteSize = 8;
3992
3993   MachineFunction &MF = DAG.getMachineFunction();
3994
3995   // Mark this function as potentially containing a function that contains a
3996   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3997   // and restoring the callers stack pointer in this functions epilog. This is
3998   // done because by tail calling the called function might overwrite the value
3999   // in this function's (MF) stack pointer stack slot 0(SP).
4000   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4001       CallConv == CallingConv::Fast)
4002     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4003
4004   unsigned nAltivecParamsAtEnd = 0;
4005
4006   // Count how many bytes are to be pushed on the stack, including the linkage
4007   // area, and parameter passing area.  We start with at least 48 bytes, which
4008   // is reserved space for [SP][CR][LR][3 x unused].
4009   // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
4010   // of this call.
4011   unsigned NumBytes =
4012     CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
4013                                          Outs, OutVals, nAltivecParamsAtEnd);
4014
4015   // Calculate by how many bytes the stack has to be adjusted in case of tail
4016   // call optimization.
4017   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4018
4019   // To protect arguments on the stack from being clobbered in a tail call,
4020   // force all the loads to happen before doing any other lowering.
4021   if (isTailCall)
4022     Chain = DAG.getStackArgumentTokenFactor(Chain);
4023
4024   // Adjust the stack pointer for the new arguments...
4025   // These operations are automatically eliminated by the prolog/epilog pass
4026   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4027                                dl);
4028   SDValue CallSeqStart = Chain;
4029
4030   // Load the return address and frame pointer so it can be move somewhere else
4031   // later.
4032   SDValue LROp, FPOp;
4033   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4034                                        dl);
4035
4036   // Set up a copy of the stack pointer for use loading and storing any
4037   // arguments that may not fit in the registers available for argument
4038   // passing.
4039   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4040
4041   // Figure out which arguments are going to go in registers, and which in
4042   // memory.  Also, if this is a vararg function, floating point operations
4043   // must be stored to our stack, and loaded into integer regs as well, if
4044   // any integer regs are available for argument passing.
4045   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4046   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4047
4048   static const MCPhysReg GPR[] = {
4049     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4050     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4051   };
4052   static const MCPhysReg *FPR = GetFPR();
4053
4054   static const MCPhysReg VR[] = {
4055     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4056     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4057   };
4058   static const MCPhysReg VSRH[] = {
4059     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4060     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4061   };
4062
4063   const unsigned NumGPRs = array_lengthof(GPR);
4064   const unsigned NumFPRs = 13;
4065   const unsigned NumVRs  = array_lengthof(VR);
4066
4067   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4068   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4069
4070   SmallVector<SDValue, 8> MemOpChains;
4071   for (unsigned i = 0; i != NumOps; ++i) {
4072     SDValue Arg = OutVals[i];
4073     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4074
4075     // PtrOff will be used to store the current argument to the stack if a
4076     // register cannot be found for it.
4077     SDValue PtrOff;
4078
4079     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4080
4081     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4082
4083     // Promote integers to 64-bit values.
4084     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4085       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4086       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4087       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4088     }
4089
4090     // FIXME memcpy is used way more than necessary.  Correctness first.
4091     // Note: "by value" is code for passing a structure by value, not
4092     // basic types.
4093     if (Flags.isByVal()) {
4094       // Note: Size includes alignment padding, so
4095       //   struct x { short a; char b; }
4096       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4097       // These are the proper values we need for right-justifying the
4098       // aggregate in a parameter register.
4099       unsigned Size = Flags.getByValSize();
4100
4101       // An empty aggregate parameter takes up no storage and no
4102       // registers.
4103       if (Size == 0)
4104         continue;
4105
4106       unsigned BVAlign = Flags.getByValAlign();
4107       if (BVAlign > 8) {
4108         if (BVAlign % PtrByteSize != 0)
4109           llvm_unreachable(
4110             "ByVal alignment is not a multiple of the pointer size");
4111
4112         ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4113       }
4114
4115       // All aggregates smaller than 8 bytes must be passed right-justified.
4116       if (Size==1 || Size==2 || Size==4) {
4117         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4118         if (GPR_idx != NumGPRs) {
4119           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4120                                         MachinePointerInfo(), VT,
4121                                         false, false, 0);
4122           MemOpChains.push_back(Load.getValue(1));
4123           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4124
4125           ArgOffset += PtrByteSize;
4126           continue;
4127         }
4128       }
4129
4130       if (GPR_idx == NumGPRs && Size < 8) {
4131         SDValue Const = DAG.getConstant(PtrByteSize - Size,
4132                                         PtrOff.getValueType());
4133         SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4134         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4135                                                           CallSeqStart,
4136                                                           Flags, DAG, dl);
4137         ArgOffset += PtrByteSize;
4138         continue;
4139       }
4140       // Copy entire object into memory.  There are cases where gcc-generated
4141       // code assumes it is there, even if it could be put entirely into
4142       // registers.  (This is not what the doc says.)
4143
4144       // FIXME: The above statement is likely due to a misunderstanding of the
4145       // documents.  All arguments must be copied into the parameter area BY
4146       // THE CALLEE in the event that the callee takes the address of any
4147       // formal argument.  That has not yet been implemented.  However, it is
4148       // reasonable to use the stack area as a staging area for the register
4149       // load.
4150
4151       // Skip this for small aggregates, as we will use the same slot for a
4152       // right-justified copy, below.
4153       if (Size >= 8)
4154         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4155                                                           CallSeqStart,
4156                                                           Flags, DAG, dl);
4157
4158       // When a register is available, pass a small aggregate right-justified.
4159       if (Size < 8 && GPR_idx != NumGPRs) {
4160         // The easiest way to get this right-justified in a register
4161         // is to copy the structure into the rightmost portion of a
4162         // local variable slot, then load the whole slot into the
4163         // register.
4164         // FIXME: The memcpy seems to produce pretty awful code for
4165         // small aggregates, particularly for packed ones.
4166         // FIXME: It would be preferable to use the slot in the
4167         // parameter save area instead of a new local variable.
4168         SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4169         SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4170         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4171                                                           CallSeqStart,
4172                                                           Flags, DAG, dl);
4173
4174         // Load the slot into the register.
4175         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4176                                    MachinePointerInfo(),
4177                                    false, false, false, 0);
4178         MemOpChains.push_back(Load.getValue(1));
4179         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4180
4181         // Done with this argument.
4182         ArgOffset += PtrByteSize;
4183         continue;
4184       }
4185
4186       // For aggregates larger than PtrByteSize, copy the pieces of the
4187       // object that fit into registers from the parameter save area.
4188       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4189         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4190         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4191         if (GPR_idx != NumGPRs) {
4192           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4193                                      MachinePointerInfo(),
4194                                      false, false, false, 0);
4195           MemOpChains.push_back(Load.getValue(1));
4196           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4197           ArgOffset += PtrByteSize;
4198         } else {
4199           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4200           break;
4201         }
4202       }
4203       continue;
4204     }
4205
4206     switch (Arg.getSimpleValueType().SimpleTy) {
4207     default: llvm_unreachable("Unexpected ValueType for argument!");
4208     case MVT::i1:
4209     case MVT::i32:
4210     case MVT::i64:
4211       if (GPR_idx != NumGPRs) {
4212         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4213       } else {
4214         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4215                          true, isTailCall, false, MemOpChains,
4216                          TailCallArguments, dl);
4217       }
4218       ArgOffset += PtrByteSize;
4219       break;
4220     case MVT::f32:
4221     case MVT::f64:
4222       if (FPR_idx != NumFPRs) {
4223         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4224
4225         if (isVarArg) {
4226           // A single float or an aggregate containing only a single float
4227           // must be passed right-justified in the stack doubleword, and
4228           // in the GPR, if one is available.
4229           SDValue StoreOff;
4230           if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4231             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4232             StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4233           } else
4234             StoreOff = PtrOff;
4235
4236           SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4237                                        MachinePointerInfo(), false, false, 0);
4238           MemOpChains.push_back(Store);
4239
4240           // Float varargs are always shadowed in available integer registers
4241           if (GPR_idx != NumGPRs) {
4242             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4243                                        MachinePointerInfo(), false, false,
4244                                        false, 0);
4245             MemOpChains.push_back(Load.getValue(1));
4246             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4247           }
4248         } else if (GPR_idx != NumGPRs)
4249           // If we have any FPRs remaining, we may also have GPRs remaining.
4250           ++GPR_idx;
4251       } else {
4252         // Single-precision floating-point values are mapped to the
4253         // second (rightmost) word of the stack doubleword.
4254         if (Arg.getValueType() == MVT::f32) {
4255           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4256           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4257         }
4258
4259         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4260                          true, isTailCall, false, MemOpChains,
4261                          TailCallArguments, dl);
4262       }
4263       ArgOffset += 8;
4264       break;
4265     case MVT::v4f32:
4266     case MVT::v4i32:
4267     case MVT::v8i16:
4268     case MVT::v16i8:
4269     case MVT::v2f64:
4270     case MVT::v2i64:
4271       if (isVarArg) {
4272         // These go aligned on the stack, or in the corresponding R registers
4273         // when within range.  The Darwin PPC ABI doc claims they also go in
4274         // V registers; in fact gcc does this only for arguments that are
4275         // prototyped, not for those that match the ...  We do it for all
4276         // arguments, seems to work.
4277         while (ArgOffset % 16 !=0) {
4278           ArgOffset += PtrByteSize;
4279           if (GPR_idx != NumGPRs)
4280             GPR_idx++;
4281         }
4282         // We could elide this store in the case where the object fits
4283         // entirely in R registers.  Maybe later.
4284         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4285                             DAG.getConstant(ArgOffset, PtrVT));
4286         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4287                                      MachinePointerInfo(), false, false, 0);
4288         MemOpChains.push_back(Store);
4289         if (VR_idx != NumVRs) {
4290           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4291                                      MachinePointerInfo(),
4292                                      false, false, false, 0);
4293           MemOpChains.push_back(Load.getValue(1));
4294
4295           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4296                            Arg.getSimpleValueType() == MVT::v2i64) ?
4297                           VSRH[VR_idx] : VR[VR_idx];
4298           ++VR_idx;
4299
4300           RegsToPass.push_back(std::make_pair(VReg, Load));
4301         }
4302         ArgOffset += 16;
4303         for (unsigned i=0; i<16; i+=PtrByteSize) {
4304           if (GPR_idx == NumGPRs)
4305             break;
4306           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4307                                   DAG.getConstant(i, PtrVT));
4308           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4309                                      false, false, false, 0);
4310           MemOpChains.push_back(Load.getValue(1));
4311           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4312         }
4313         break;
4314       }
4315
4316       // Non-varargs Altivec params generally go in registers, but have
4317       // stack space allocated at the end.
4318       if (VR_idx != NumVRs) {
4319         // Doesn't have GPR space allocated.
4320         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4321                          Arg.getSimpleValueType() == MVT::v2i64) ?
4322                         VSRH[VR_idx] : VR[VR_idx];
4323         ++VR_idx;
4324
4325         RegsToPass.push_back(std::make_pair(VReg, Arg));
4326       } else {
4327         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4328                          true, isTailCall, true, MemOpChains,
4329                          TailCallArguments, dl);
4330         ArgOffset += 16;
4331       }
4332       break;
4333     }
4334   }
4335
4336   if (!MemOpChains.empty())
4337     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4338
4339   // Check if this is an indirect call (MTCTR/BCTRL).
4340   // See PrepareCall() for more information about calls through function
4341   // pointers in the 64-bit SVR4 ABI.
4342   if (!isTailCall &&
4343       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4344       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4345       !isBLACompatibleAddress(Callee, DAG)) {
4346     // Load r2 into a virtual register and store it to the TOC save area.
4347     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4348     // TOC save area offset.
4349     SDValue PtrOff = DAG.getIntPtrConstant(40);
4350     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4351     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4352                          false, false, 0);
4353     // R12 must contain the address of an indirect callee.  This does not
4354     // mean the MTCTR instruction must use R12; it's easier to model this
4355     // as an extra parameter, so do that.
4356     RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4357   }
4358
4359   // Build a sequence of copy-to-reg nodes chained together with token chain
4360   // and flag operands which copy the outgoing args into the appropriate regs.
4361   SDValue InFlag;
4362   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4363     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4364                              RegsToPass[i].second, InFlag);
4365     InFlag = Chain.getValue(1);
4366   }
4367
4368   if (isTailCall)
4369     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4370                     FPOp, true, TailCallArguments);
4371
4372   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4373                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4374                     Ins, InVals);
4375 }
4376
4377 SDValue
4378 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4379                                     CallingConv::ID CallConv, bool isVarArg,
4380                                     bool isTailCall,
4381                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4382                                     const SmallVectorImpl<SDValue> &OutVals,
4383                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4384                                     SDLoc dl, SelectionDAG &DAG,
4385                                     SmallVectorImpl<SDValue> &InVals) const {
4386
4387   unsigned NumOps = Outs.size();
4388
4389   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4390   bool isPPC64 = PtrVT == MVT::i64;
4391   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4392
4393   MachineFunction &MF = DAG.getMachineFunction();
4394
4395   // Mark this function as potentially containing a function that contains a
4396   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4397   // and restoring the callers stack pointer in this functions epilog. This is
4398   // done because by tail calling the called function might overwrite the value
4399   // in this function's (MF) stack pointer stack slot 0(SP).
4400   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4401       CallConv == CallingConv::Fast)
4402     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4403
4404   unsigned nAltivecParamsAtEnd = 0;
4405
4406   // Count how many bytes are to be pushed on the stack, including the linkage
4407   // area, and parameter passing area.  We start with 24/48 bytes, which is
4408   // prereserved space for [SP][CR][LR][3 x unused].
4409   unsigned NumBytes =
4410     CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4411                                          Outs, OutVals,
4412                                          nAltivecParamsAtEnd);
4413
4414   // Calculate by how many bytes the stack has to be adjusted in case of tail
4415   // call optimization.
4416   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4417
4418   // To protect arguments on the stack from being clobbered in a tail call,
4419   // force all the loads to happen before doing any other lowering.
4420   if (isTailCall)
4421     Chain = DAG.getStackArgumentTokenFactor(Chain);
4422
4423   // Adjust the stack pointer for the new arguments...
4424   // These operations are automatically eliminated by the prolog/epilog pass
4425   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4426                                dl);
4427   SDValue CallSeqStart = Chain;
4428
4429   // Load the return address and frame pointer so it can be move somewhere else
4430   // later.
4431   SDValue LROp, FPOp;
4432   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4433                                        dl);
4434
4435   // Set up a copy of the stack pointer for use loading and storing any
4436   // arguments that may not fit in the registers available for argument
4437   // passing.
4438   SDValue StackPtr;
4439   if (isPPC64)
4440     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4441   else
4442     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4443
4444   // Figure out which arguments are going to go in registers, and which in
4445   // memory.  Also, if this is a vararg function, floating point operations
4446   // must be stored to our stack, and loaded into integer regs as well, if
4447   // any integer regs are available for argument passing.
4448   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4449   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4450
4451   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4452     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4453     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4454   };
4455   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4456     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4457     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4458   };
4459   static const MCPhysReg *FPR = GetFPR();
4460
4461   static const MCPhysReg VR[] = {
4462     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4463     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4464   };
4465   const unsigned NumGPRs = array_lengthof(GPR_32);
4466   const unsigned NumFPRs = 13;
4467   const unsigned NumVRs  = array_lengthof(VR);
4468
4469   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4470
4471   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4472   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4473
4474   SmallVector<SDValue, 8> MemOpChains;
4475   for (unsigned i = 0; i != NumOps; ++i) {
4476     SDValue Arg = OutVals[i];
4477     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4478
4479     // PtrOff will be used to store the current argument to the stack if a
4480     // register cannot be found for it.
4481     SDValue PtrOff;
4482
4483     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4484
4485     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4486
4487     // On PPC64, promote integers to 64-bit values.
4488     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4489       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4490       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4491       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4492     }
4493
4494     // FIXME memcpy is used way more than necessary.  Correctness first.
4495     // Note: "by value" is code for passing a structure by value, not
4496     // basic types.
4497     if (Flags.isByVal()) {
4498       unsigned Size = Flags.getByValSize();
4499       // Very small objects are passed right-justified.  Everything else is
4500       // passed left-justified.
4501       if (Size==1 || Size==2) {
4502         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4503         if (GPR_idx != NumGPRs) {
4504           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4505                                         MachinePointerInfo(), VT,
4506                                         false, false, 0);
4507           MemOpChains.push_back(Load.getValue(1));
4508           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4509
4510           ArgOffset += PtrByteSize;
4511         } else {
4512           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4513                                           PtrOff.getValueType());
4514           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4515           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4516                                                             CallSeqStart,
4517                                                             Flags, DAG, dl);
4518           ArgOffset += PtrByteSize;
4519         }
4520         continue;
4521       }
4522       // Copy entire object into memory.  There are cases where gcc-generated
4523       // code assumes it is there, even if it could be put entirely into
4524       // registers.  (This is not what the doc says.)
4525       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4526                                                         CallSeqStart,
4527                                                         Flags, DAG, dl);
4528
4529       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4530       // copy the pieces of the object that fit into registers from the
4531       // parameter save area.
4532       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4533         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4534         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4535         if (GPR_idx != NumGPRs) {
4536           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4537                                      MachinePointerInfo(),
4538                                      false, false, false, 0);
4539           MemOpChains.push_back(Load.getValue(1));
4540           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4541           ArgOffset += PtrByteSize;
4542         } else {
4543           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4544           break;
4545         }
4546       }
4547       continue;
4548     }
4549
4550     switch (Arg.getSimpleValueType().SimpleTy) {
4551     default: llvm_unreachable("Unexpected ValueType for argument!");
4552     case MVT::i1:
4553     case MVT::i32:
4554     case MVT::i64:
4555       if (GPR_idx != NumGPRs) {
4556         if (Arg.getValueType() == MVT::i1)
4557           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4558
4559         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4560       } else {
4561         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4562                          isPPC64, isTailCall, false, MemOpChains,
4563                          TailCallArguments, dl);
4564       }
4565       ArgOffset += PtrByteSize;
4566       break;
4567     case MVT::f32:
4568     case MVT::f64:
4569       if (FPR_idx != NumFPRs) {
4570         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4571
4572         if (isVarArg) {
4573           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4574                                        MachinePointerInfo(), false, false, 0);
4575           MemOpChains.push_back(Store);
4576
4577           // Float varargs are always shadowed in available integer registers
4578           if (GPR_idx != NumGPRs) {
4579             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4580                                        MachinePointerInfo(), false, false,
4581                                        false, 0);
4582             MemOpChains.push_back(Load.getValue(1));
4583             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4584           }
4585           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4586             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4587             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4588             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4589                                        MachinePointerInfo(),
4590                                        false, false, false, 0);
4591             MemOpChains.push_back(Load.getValue(1));
4592             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4593           }
4594         } else {
4595           // If we have any FPRs remaining, we may also have GPRs remaining.
4596           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4597           // GPRs.
4598           if (GPR_idx != NumGPRs)
4599             ++GPR_idx;
4600           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4601               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4602             ++GPR_idx;
4603         }
4604       } else
4605         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4606                          isPPC64, isTailCall, false, MemOpChains,
4607                          TailCallArguments, dl);
4608       if (isPPC64)
4609         ArgOffset += 8;
4610       else
4611         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4612       break;
4613     case MVT::v4f32:
4614     case MVT::v4i32:
4615     case MVT::v8i16:
4616     case MVT::v16i8:
4617       if (isVarArg) {
4618         // These go aligned on the stack, or in the corresponding R registers
4619         // when within range.  The Darwin PPC ABI doc claims they also go in
4620         // V registers; in fact gcc does this only for arguments that are
4621         // prototyped, not for those that match the ...  We do it for all
4622         // arguments, seems to work.
4623         while (ArgOffset % 16 !=0) {
4624           ArgOffset += PtrByteSize;
4625           if (GPR_idx != NumGPRs)
4626             GPR_idx++;
4627         }
4628         // We could elide this store in the case where the object fits
4629         // entirely in R registers.  Maybe later.
4630         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4631                             DAG.getConstant(ArgOffset, PtrVT));
4632         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4633                                      MachinePointerInfo(), false, false, 0);
4634         MemOpChains.push_back(Store);
4635         if (VR_idx != NumVRs) {
4636           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4637                                      MachinePointerInfo(),
4638                                      false, false, false, 0);
4639           MemOpChains.push_back(Load.getValue(1));
4640           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4641         }
4642         ArgOffset += 16;
4643         for (unsigned i=0; i<16; i+=PtrByteSize) {
4644           if (GPR_idx == NumGPRs)
4645             break;
4646           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4647                                   DAG.getConstant(i, PtrVT));
4648           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4649                                      false, false, false, 0);
4650           MemOpChains.push_back(Load.getValue(1));
4651           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4652         }
4653         break;
4654       }
4655
4656       // Non-varargs Altivec params generally go in registers, but have
4657       // stack space allocated at the end.
4658       if (VR_idx != NumVRs) {
4659         // Doesn't have GPR space allocated.
4660         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4661       } else if (nAltivecParamsAtEnd==0) {
4662         // We are emitting Altivec params in order.
4663         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4664                          isPPC64, isTailCall, true, MemOpChains,
4665                          TailCallArguments, dl);
4666         ArgOffset += 16;
4667       }
4668       break;
4669     }
4670   }
4671   // If all Altivec parameters fit in registers, as they usually do,
4672   // they get stack space following the non-Altivec parameters.  We
4673   // don't track this here because nobody below needs it.
4674   // If there are more Altivec parameters than fit in registers emit
4675   // the stores here.
4676   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4677     unsigned j = 0;
4678     // Offset is aligned; skip 1st 12 params which go in V registers.
4679     ArgOffset = ((ArgOffset+15)/16)*16;
4680     ArgOffset += 12*16;
4681     for (unsigned i = 0; i != NumOps; ++i) {
4682       SDValue Arg = OutVals[i];
4683       EVT ArgType = Outs[i].VT;
4684       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4685           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4686         if (++j > NumVRs) {
4687           SDValue PtrOff;
4688           // We are emitting Altivec params in order.
4689           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4690                            isPPC64, isTailCall, true, MemOpChains,
4691                            TailCallArguments, dl);
4692           ArgOffset += 16;
4693         }
4694       }
4695     }
4696   }
4697
4698   if (!MemOpChains.empty())
4699     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4700
4701   // On Darwin, R12 must contain the address of an indirect callee.  This does
4702   // not mean the MTCTR instruction must use R12; it's easier to model this as
4703   // an extra parameter, so do that.
4704   if (!isTailCall &&
4705       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4706       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4707       !isBLACompatibleAddress(Callee, DAG))
4708     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4709                                                    PPC::R12), Callee));
4710
4711   // Build a sequence of copy-to-reg nodes chained together with token chain
4712   // and flag operands which copy the outgoing args into the appropriate regs.
4713   SDValue InFlag;
4714   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4715     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4716                              RegsToPass[i].second, InFlag);
4717     InFlag = Chain.getValue(1);
4718   }
4719
4720   if (isTailCall)
4721     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4722                     FPOp, true, TailCallArguments);
4723
4724   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4725                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4726                     Ins, InVals);
4727 }
4728
4729 bool
4730 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4731                                   MachineFunction &MF, bool isVarArg,
4732                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
4733                                   LLVMContext &Context) const {
4734   SmallVector<CCValAssign, 16> RVLocs;
4735   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4736                  RVLocs, Context);
4737   return CCInfo.CheckReturn(Outs, RetCC_PPC);
4738 }
4739
4740 SDValue
4741 PPCTargetLowering::LowerReturn(SDValue Chain,
4742                                CallingConv::ID CallConv, bool isVarArg,
4743                                const SmallVectorImpl<ISD::OutputArg> &Outs,
4744                                const SmallVectorImpl<SDValue> &OutVals,
4745                                SDLoc dl, SelectionDAG &DAG) const {
4746
4747   SmallVector<CCValAssign, 16> RVLocs;
4748   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4749                  getTargetMachine(), RVLocs, *DAG.getContext());
4750   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4751
4752   SDValue Flag;
4753   SmallVector<SDValue, 4> RetOps(1, Chain);
4754
4755   // Copy the result values into the output registers.
4756   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4757     CCValAssign &VA = RVLocs[i];
4758     assert(VA.isRegLoc() && "Can only return in registers!");
4759
4760     SDValue Arg = OutVals[i];
4761
4762     switch (VA.getLocInfo()) {
4763     default: llvm_unreachable("Unknown loc info!");
4764     case CCValAssign::Full: break;
4765     case CCValAssign::AExt:
4766       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4767       break;
4768     case CCValAssign::ZExt:
4769       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4770       break;
4771     case CCValAssign::SExt:
4772       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4773       break;
4774     }
4775
4776     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4777     Flag = Chain.getValue(1);
4778     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4779   }
4780
4781   RetOps[0] = Chain;  // Update chain.
4782
4783   // Add the flag if we have it.
4784   if (Flag.getNode())
4785     RetOps.push_back(Flag);
4786
4787   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
4788 }
4789
4790 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4791                                    const PPCSubtarget &Subtarget) const {
4792   // When we pop the dynamic allocation we need to restore the SP link.
4793   SDLoc dl(Op);
4794
4795   // Get the corect type for pointers.
4796   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4797
4798   // Construct the stack pointer operand.
4799   bool isPPC64 = Subtarget.isPPC64();
4800   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4801   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4802
4803   // Get the operands for the STACKRESTORE.
4804   SDValue Chain = Op.getOperand(0);
4805   SDValue SaveSP = Op.getOperand(1);
4806
4807   // Load the old link SP.
4808   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4809                                    MachinePointerInfo(),
4810                                    false, false, false, 0);
4811
4812   // Restore the stack pointer.
4813   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4814
4815   // Store the old link SP.
4816   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4817                       false, false, 0);
4818 }
4819
4820
4821
4822 SDValue
4823 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4824   MachineFunction &MF = DAG.getMachineFunction();
4825   bool isPPC64 = PPCSubTarget.isPPC64();
4826   bool isDarwinABI = PPCSubTarget.isDarwinABI();
4827   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4828
4829   // Get current frame pointer save index.  The users of this index will be
4830   // primarily DYNALLOC instructions.
4831   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4832   int RASI = FI->getReturnAddrSaveIndex();
4833
4834   // If the frame pointer save index hasn't been defined yet.
4835   if (!RASI) {
4836     // Find out what the fix offset of the frame pointer save area.
4837     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4838     // Allocate the frame index for frame pointer save area.
4839     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4840     // Save the result.
4841     FI->setReturnAddrSaveIndex(RASI);
4842   }
4843   return DAG.getFrameIndex(RASI, PtrVT);
4844 }
4845
4846 SDValue
4847 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4848   MachineFunction &MF = DAG.getMachineFunction();
4849   bool isPPC64 = PPCSubTarget.isPPC64();
4850   bool isDarwinABI = PPCSubTarget.isDarwinABI();
4851   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4852
4853   // Get current frame pointer save index.  The users of this index will be
4854   // primarily DYNALLOC instructions.
4855   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4856   int FPSI = FI->getFramePointerSaveIndex();
4857
4858   // If the frame pointer save index hasn't been defined yet.
4859   if (!FPSI) {
4860     // Find out what the fix offset of the frame pointer save area.
4861     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4862                                                            isDarwinABI);
4863
4864     // Allocate the frame index for frame pointer save area.
4865     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4866     // Save the result.
4867     FI->setFramePointerSaveIndex(FPSI);
4868   }
4869   return DAG.getFrameIndex(FPSI, PtrVT);
4870 }
4871
4872 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4873                                          SelectionDAG &DAG,
4874                                          const PPCSubtarget &Subtarget) const {
4875   // Get the inputs.
4876   SDValue Chain = Op.getOperand(0);
4877   SDValue Size  = Op.getOperand(1);
4878   SDLoc dl(Op);
4879
4880   // Get the corect type for pointers.
4881   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4882   // Negate the size.
4883   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4884                                   DAG.getConstant(0, PtrVT), Size);
4885   // Construct a node for the frame pointer save index.
4886   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4887   // Build a DYNALLOC node.
4888   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4889   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4890   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
4891 }
4892
4893 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4894                                                SelectionDAG &DAG) const {
4895   SDLoc DL(Op);
4896   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4897                      DAG.getVTList(MVT::i32, MVT::Other),
4898                      Op.getOperand(0), Op.getOperand(1));
4899 }
4900
4901 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4902                                                 SelectionDAG &DAG) const {
4903   SDLoc DL(Op);
4904   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4905                      Op.getOperand(0), Op.getOperand(1));
4906 }
4907
4908 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4909   assert(Op.getValueType() == MVT::i1 &&
4910          "Custom lowering only for i1 loads");
4911
4912   // First, load 8 bits into 32 bits, then truncate to 1 bit.
4913
4914   SDLoc dl(Op);
4915   LoadSDNode *LD = cast<LoadSDNode>(Op);
4916
4917   SDValue Chain = LD->getChain();
4918   SDValue BasePtr = LD->getBasePtr();
4919   MachineMemOperand *MMO = LD->getMemOperand();
4920
4921   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4922                                  BasePtr, MVT::i8, MMO);
4923   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4924
4925   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4926   return DAG.getMergeValues(Ops, dl);
4927 }
4928
4929 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4930   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4931          "Custom lowering only for i1 stores");
4932
4933   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4934
4935   SDLoc dl(Op);
4936   StoreSDNode *ST = cast<StoreSDNode>(Op);
4937
4938   SDValue Chain = ST->getChain();
4939   SDValue BasePtr = ST->getBasePtr();
4940   SDValue Value = ST->getValue();
4941   MachineMemOperand *MMO = ST->getMemOperand();
4942
4943   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4944   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4945 }
4946
4947 // FIXME: Remove this once the ANDI glue bug is fixed:
4948 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4949   assert(Op.getValueType() == MVT::i1 &&
4950          "Custom lowering only for i1 results");
4951
4952   SDLoc DL(Op);
4953   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4954                      Op.getOperand(0));
4955 }
4956
4957 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4958 /// possible.
4959 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4960   // Not FP? Not a fsel.
4961   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4962       !Op.getOperand(2).getValueType().isFloatingPoint())
4963     return Op;
4964
4965   // We might be able to do better than this under some circumstances, but in
4966   // general, fsel-based lowering of select is a finite-math-only optimization.
4967   // For more information, see section F.3 of the 2.06 ISA specification.
4968   if (!DAG.getTarget().Options.NoInfsFPMath ||
4969       !DAG.getTarget().Options.NoNaNsFPMath)
4970     return Op;
4971
4972   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4973
4974   EVT ResVT = Op.getValueType();
4975   EVT CmpVT = Op.getOperand(0).getValueType();
4976   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4977   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
4978   SDLoc dl(Op);
4979
4980   // If the RHS of the comparison is a 0.0, we don't need to do the
4981   // subtraction at all.
4982   SDValue Sel1;
4983   if (isFloatingPointZero(RHS))
4984     switch (CC) {
4985     default: break;       // SETUO etc aren't handled by fsel.
4986     case ISD::SETNE:
4987       std::swap(TV, FV);
4988     case ISD::SETEQ:
4989       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
4990         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4991       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4992       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
4993         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4994       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4995                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4996     case ISD::SETULT:
4997     case ISD::SETLT:
4998       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
4999     case ISD::SETOGE:
5000     case ISD::SETGE:
5001       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5002         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5003       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5004     case ISD::SETUGT:
5005     case ISD::SETGT:
5006       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5007     case ISD::SETOLE:
5008     case ISD::SETLE:
5009       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5010         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5011       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5012                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5013     }
5014
5015   SDValue Cmp;
5016   switch (CC) {
5017   default: break;       // SETUO etc aren't handled by fsel.
5018   case ISD::SETNE:
5019     std::swap(TV, FV);
5020   case ISD::SETEQ:
5021     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5022     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5023       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5024     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5025     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5026       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5027     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5028                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5029   case ISD::SETULT:
5030   case ISD::SETLT:
5031     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5032     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5033       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5034     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5035   case ISD::SETOGE:
5036   case ISD::SETGE:
5037     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5038     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5039       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5040     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5041   case ISD::SETUGT:
5042   case ISD::SETGT:
5043     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5044     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5045       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5046     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5047   case ISD::SETOLE:
5048   case ISD::SETLE:
5049     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5050     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5051       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5052     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5053   }
5054   return Op;
5055 }
5056
5057 // FIXME: Split this code up when LegalizeDAGTypes lands.
5058 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5059                                            SDLoc dl) const {
5060   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5061   SDValue Src = Op.getOperand(0);
5062   if (Src.getValueType() == MVT::f32)
5063     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5064
5065   SDValue Tmp;
5066   switch (Op.getSimpleValueType().SimpleTy) {
5067   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5068   case MVT::i32:
5069     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5070                         (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5071                                                    PPCISD::FCTIDZ),
5072                       dl, MVT::f64, Src);
5073     break;
5074   case MVT::i64:
5075     assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5076            "i64 FP_TO_UINT is supported only with FPCVT");
5077     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5078                                                         PPCISD::FCTIDUZ,
5079                       dl, MVT::f64, Src);
5080     break;
5081   }
5082
5083   // Convert the FP value to an int value through memory.
5084   bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5085     (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5086   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5087   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5088   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5089
5090   // Emit a store to the stack slot.
5091   SDValue Chain;
5092   if (i32Stack) {
5093     MachineFunction &MF = DAG.getMachineFunction();
5094     MachineMemOperand *MMO =
5095       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5096     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5097     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5098               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5099   } else
5100     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5101                          MPI, false, false, 0);
5102
5103   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5104   // add in a bias.
5105   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5106     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5107                         DAG.getConstant(4, FIPtr.getValueType()));
5108     MPI = MachinePointerInfo();
5109   }
5110
5111   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5112                      false, false, false, 0);
5113 }
5114
5115 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5116                                            SelectionDAG &DAG) const {
5117   SDLoc dl(Op);
5118   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5119   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5120     return SDValue();
5121
5122   if (Op.getOperand(0).getValueType() == MVT::i1)
5123     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5124                        DAG.getConstantFP(1.0, Op.getValueType()),
5125                        DAG.getConstantFP(0.0, Op.getValueType()));
5126
5127   assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5128          "UINT_TO_FP is supported only with FPCVT");
5129
5130   // If we have FCFIDS, then use it when converting to single-precision.
5131   // Otherwise, convert to double-precision and then round.
5132   unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5133                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5134                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5135                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5136                     PPCISD::FCFIDU : PPCISD::FCFID);
5137   MVT      FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5138                    MVT::f32 : MVT::f64;
5139
5140   if (Op.getOperand(0).getValueType() == MVT::i64) {
5141     SDValue SINT = Op.getOperand(0);
5142     // When converting to single-precision, we actually need to convert
5143     // to double-precision first and then round to single-precision.
5144     // To avoid double-rounding effects during that operation, we have
5145     // to prepare the input operand.  Bits that might be truncated when
5146     // converting to double-precision are replaced by a bit that won't
5147     // be lost at this stage, but is below the single-precision rounding
5148     // position.
5149     //
5150     // However, if -enable-unsafe-fp-math is in effect, accept double
5151     // rounding to avoid the extra overhead.
5152     if (Op.getValueType() == MVT::f32 &&
5153         !PPCSubTarget.hasFPCVT() &&
5154         !DAG.getTarget().Options.UnsafeFPMath) {
5155
5156       // Twiddle input to make sure the low 11 bits are zero.  (If this
5157       // is the case, we are guaranteed the value will fit into the 53 bit
5158       // mantissa of an IEEE double-precision value without rounding.)
5159       // If any of those low 11 bits were not zero originally, make sure
5160       // bit 12 (value 2048) is set instead, so that the final rounding
5161       // to single-precision gets the correct result.
5162       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5163                                   SINT, DAG.getConstant(2047, MVT::i64));
5164       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5165                           Round, DAG.getConstant(2047, MVT::i64));
5166       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5167       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5168                           Round, DAG.getConstant(-2048, MVT::i64));
5169
5170       // However, we cannot use that value unconditionally: if the magnitude
5171       // of the input value is small, the bit-twiddling we did above might
5172       // end up visibly changing the output.  Fortunately, in that case, we
5173       // don't need to twiddle bits since the original input will convert
5174       // exactly to double-precision floating-point already.  Therefore,
5175       // construct a conditional to use the original value if the top 11
5176       // bits are all sign-bit copies, and use the rounded value computed
5177       // above otherwise.
5178       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5179                                  SINT, DAG.getConstant(53, MVT::i32));
5180       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5181                          Cond, DAG.getConstant(1, MVT::i64));
5182       Cond = DAG.getSetCC(dl, MVT::i32,
5183                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5184
5185       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5186     }
5187
5188     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5189     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5190
5191     if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5192       FP = DAG.getNode(ISD::FP_ROUND, dl,
5193                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5194     return FP;
5195   }
5196
5197   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5198          "Unhandled INT_TO_FP type in custom expander!");
5199   // Since we only generate this in 64-bit mode, we can take advantage of
5200   // 64-bit registers.  In particular, sign extend the input value into the
5201   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5202   // then lfd it and fcfid it.
5203   MachineFunction &MF = DAG.getMachineFunction();
5204   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5205   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5206
5207   SDValue Ld;
5208   if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5209     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5210     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5211
5212     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5213                                  MachinePointerInfo::getFixedStack(FrameIdx),
5214                                  false, false, 0);
5215
5216     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5217            "Expected an i32 store");
5218     MachineMemOperand *MMO =
5219       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5220                               MachineMemOperand::MOLoad, 4, 4);
5221     SDValue Ops[] = { Store, FIdx };
5222     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5223                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5224                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5225                                  Ops, MVT::i32, MMO);
5226   } else {
5227     assert(PPCSubTarget.isPPC64() &&
5228            "i32->FP without LFIWAX supported only on PPC64");
5229
5230     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5231     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5232
5233     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5234                                 Op.getOperand(0));
5235
5236     // STD the extended value into the stack slot.
5237     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5238                                  MachinePointerInfo::getFixedStack(FrameIdx),
5239                                  false, false, 0);
5240
5241     // Load the value as a double.
5242     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5243                      MachinePointerInfo::getFixedStack(FrameIdx),
5244                      false, false, false, 0);
5245   }
5246
5247   // FCFID it and return it.
5248   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5249   if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5250     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5251   return FP;
5252 }
5253
5254 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5255                                             SelectionDAG &DAG) const {
5256   SDLoc dl(Op);
5257   /*
5258    The rounding mode is in bits 30:31 of FPSR, and has the following
5259    settings:
5260      00 Round to nearest
5261      01 Round to 0
5262      10 Round to +inf
5263      11 Round to -inf
5264
5265   FLT_ROUNDS, on the other hand, expects the following:
5266     -1 Undefined
5267      0 Round to 0
5268      1 Round to nearest
5269      2 Round to +inf
5270      3 Round to -inf
5271
5272   To perform the conversion, we do:
5273     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5274   */
5275
5276   MachineFunction &MF = DAG.getMachineFunction();
5277   EVT VT = Op.getValueType();
5278   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5279
5280   // Save FP Control Word to register
5281   EVT NodeTys[] = {
5282     MVT::f64,    // return register
5283     MVT::Glue    // unused in this context
5284   };
5285   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5286
5287   // Save FP register to stack slot
5288   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5289   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5290   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5291                                StackSlot, MachinePointerInfo(), false, false,0);
5292
5293   // Load FP Control Word from low 32 bits of stack slot.
5294   SDValue Four = DAG.getConstant(4, PtrVT);
5295   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5296   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5297                             false, false, false, 0);
5298
5299   // Transform as necessary
5300   SDValue CWD1 =
5301     DAG.getNode(ISD::AND, dl, MVT::i32,
5302                 CWD, DAG.getConstant(3, MVT::i32));
5303   SDValue CWD2 =
5304     DAG.getNode(ISD::SRL, dl, MVT::i32,
5305                 DAG.getNode(ISD::AND, dl, MVT::i32,
5306                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5307                                         CWD, DAG.getConstant(3, MVT::i32)),
5308                             DAG.getConstant(3, MVT::i32)),
5309                 DAG.getConstant(1, MVT::i32));
5310
5311   SDValue RetVal =
5312     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5313
5314   return DAG.getNode((VT.getSizeInBits() < 16 ?
5315                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5316 }
5317
5318 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5319   EVT VT = Op.getValueType();
5320   unsigned BitWidth = VT.getSizeInBits();
5321   SDLoc dl(Op);
5322   assert(Op.getNumOperands() == 3 &&
5323          VT == Op.getOperand(1).getValueType() &&
5324          "Unexpected SHL!");
5325
5326   // Expand into a bunch of logical ops.  Note that these ops
5327   // depend on the PPC behavior for oversized shift amounts.
5328   SDValue Lo = Op.getOperand(0);
5329   SDValue Hi = Op.getOperand(1);
5330   SDValue Amt = Op.getOperand(2);
5331   EVT AmtVT = Amt.getValueType();
5332
5333   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5334                              DAG.getConstant(BitWidth, AmtVT), Amt);
5335   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5336   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5337   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5338   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5339                              DAG.getConstant(-BitWidth, AmtVT));
5340   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5341   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5342   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5343   SDValue OutOps[] = { OutLo, OutHi };
5344   return DAG.getMergeValues(OutOps, dl);
5345 }
5346
5347 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5348   EVT VT = Op.getValueType();
5349   SDLoc dl(Op);
5350   unsigned BitWidth = VT.getSizeInBits();
5351   assert(Op.getNumOperands() == 3 &&
5352          VT == Op.getOperand(1).getValueType() &&
5353          "Unexpected SRL!");
5354
5355   // Expand into a bunch of logical ops.  Note that these ops
5356   // depend on the PPC behavior for oversized shift amounts.
5357   SDValue Lo = Op.getOperand(0);
5358   SDValue Hi = Op.getOperand(1);
5359   SDValue Amt = Op.getOperand(2);
5360   EVT AmtVT = Amt.getValueType();
5361
5362   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5363                              DAG.getConstant(BitWidth, AmtVT), Amt);
5364   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5365   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5366   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5367   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5368                              DAG.getConstant(-BitWidth, AmtVT));
5369   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5370   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5371   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5372   SDValue OutOps[] = { OutLo, OutHi };
5373   return DAG.getMergeValues(OutOps, dl);
5374 }
5375
5376 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5377   SDLoc dl(Op);
5378   EVT VT = Op.getValueType();
5379   unsigned BitWidth = VT.getSizeInBits();
5380   assert(Op.getNumOperands() == 3 &&
5381          VT == Op.getOperand(1).getValueType() &&
5382          "Unexpected SRA!");
5383
5384   // Expand into a bunch of logical ops, followed by a select_cc.
5385   SDValue Lo = Op.getOperand(0);
5386   SDValue Hi = Op.getOperand(1);
5387   SDValue Amt = Op.getOperand(2);
5388   EVT AmtVT = Amt.getValueType();
5389
5390   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5391                              DAG.getConstant(BitWidth, AmtVT), Amt);
5392   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5393   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5394   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5395   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5396                              DAG.getConstant(-BitWidth, AmtVT));
5397   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5398   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5399   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5400                                   Tmp4, Tmp6, ISD::SETLE);
5401   SDValue OutOps[] = { OutLo, OutHi };
5402   return DAG.getMergeValues(OutOps, dl);
5403 }
5404
5405 //===----------------------------------------------------------------------===//
5406 // Vector related lowering.
5407 //
5408
5409 /// BuildSplatI - Build a canonical splati of Val with an element size of
5410 /// SplatSize.  Cast the result to VT.
5411 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5412                              SelectionDAG &DAG, SDLoc dl) {
5413   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5414
5415   static const EVT VTys[] = { // canonical VT to use for each size.
5416     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5417   };
5418
5419   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5420
5421   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5422   if (Val == -1)
5423     SplatSize = 1;
5424
5425   EVT CanonicalVT = VTys[SplatSize-1];
5426
5427   // Build a canonical splat for this value.
5428   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5429   SmallVector<SDValue, 8> Ops;
5430   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5431   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5432   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5433 }
5434
5435 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5436 /// specified intrinsic ID.
5437 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5438                                 SelectionDAG &DAG, SDLoc dl,
5439                                 EVT DestVT = MVT::Other) {
5440   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5441   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5442                      DAG.getConstant(IID, MVT::i32), Op);
5443 }
5444
5445 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5446 /// specified intrinsic ID.
5447 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5448                                 SelectionDAG &DAG, SDLoc dl,
5449                                 EVT DestVT = MVT::Other) {
5450   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5451   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5452                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5453 }
5454
5455 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5456 /// specified intrinsic ID.
5457 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5458                                 SDValue Op2, SelectionDAG &DAG,
5459                                 SDLoc dl, EVT DestVT = MVT::Other) {
5460   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5461   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5462                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5463 }
5464
5465
5466 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5467 /// amount.  The result has the specified value type.
5468 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5469                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5470   // Force LHS/RHS to be the right type.
5471   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5472   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5473
5474   int Ops[16];
5475   for (unsigned i = 0; i != 16; ++i)
5476     Ops[i] = i + Amt;
5477   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5478   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5479 }
5480
5481 // If this is a case we can't handle, return null and let the default
5482 // expansion code take care of it.  If we CAN select this case, and if it
5483 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5484 // this case more efficiently than a constant pool load, lower it to the
5485 // sequence of ops that should be used.
5486 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5487                                              SelectionDAG &DAG) const {
5488   SDLoc dl(Op);
5489   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5490   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5491
5492   // Check if this is a splat of a constant value.
5493   APInt APSplatBits, APSplatUndef;
5494   unsigned SplatBitSize;
5495   bool HasAnyUndefs;
5496   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5497                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5498     return SDValue();
5499
5500   unsigned SplatBits = APSplatBits.getZExtValue();
5501   unsigned SplatUndef = APSplatUndef.getZExtValue();
5502   unsigned SplatSize = SplatBitSize / 8;
5503
5504   // First, handle single instruction cases.
5505
5506   // All zeros?
5507   if (SplatBits == 0) {
5508     // Canonicalize all zero vectors to be v4i32.
5509     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5510       SDValue Z = DAG.getConstant(0, MVT::i32);
5511       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5512       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5513     }
5514     return Op;
5515   }
5516
5517   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5518   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5519                     (32-SplatBitSize));
5520   if (SextVal >= -16 && SextVal <= 15)
5521     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5522
5523
5524   // Two instruction sequences.
5525
5526   // If this value is in the range [-32,30] and is even, use:
5527   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5528   // If this value is in the range [17,31] and is odd, use:
5529   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5530   // If this value is in the range [-31,-17] and is odd, use:
5531   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5532   // Note the last two are three-instruction sequences.
5533   if (SextVal >= -32 && SextVal <= 31) {
5534     // To avoid having these optimizations undone by constant folding,
5535     // we convert to a pseudo that will be expanded later into one of
5536     // the above forms.
5537     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5538     EVT VT = Op.getValueType();
5539     int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5540     SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5541     return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5542   }
5543
5544   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5545   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5546   // for fneg/fabs.
5547   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5548     // Make -1 and vspltisw -1:
5549     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5550
5551     // Make the VSLW intrinsic, computing 0x8000_0000.
5552     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5553                                    OnesV, DAG, dl);
5554
5555     // xor by OnesV to invert it.
5556     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5557     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5558   }
5559
5560   // Check to see if this is a wide variety of vsplti*, binop self cases.
5561   static const signed char SplatCsts[] = {
5562     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5563     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5564   };
5565
5566   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5567     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5568     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5569     int i = SplatCsts[idx];
5570
5571     // Figure out what shift amount will be used by altivec if shifted by i in
5572     // this splat size.
5573     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5574
5575     // vsplti + shl self.
5576     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5577       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5578       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5579         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5580         Intrinsic::ppc_altivec_vslw
5581       };
5582       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5583       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5584     }
5585
5586     // vsplti + srl self.
5587     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5588       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5589       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5590         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5591         Intrinsic::ppc_altivec_vsrw
5592       };
5593       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5594       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5595     }
5596
5597     // vsplti + sra self.
5598     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5599       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5600       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5601         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5602         Intrinsic::ppc_altivec_vsraw
5603       };
5604       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5605       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5606     }
5607
5608     // vsplti + rol self.
5609     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5610                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5611       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5612       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5613         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5614         Intrinsic::ppc_altivec_vrlw
5615       };
5616       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5617       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5618     }
5619
5620     // t = vsplti c, result = vsldoi t, t, 1
5621     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5622       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5623       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5624     }
5625     // t = vsplti c, result = vsldoi t, t, 2
5626     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5627       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5628       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5629     }
5630     // t = vsplti c, result = vsldoi t, t, 3
5631     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5632       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5633       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5634     }
5635   }
5636
5637   return SDValue();
5638 }
5639
5640 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5641 /// the specified operations to build the shuffle.
5642 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5643                                       SDValue RHS, SelectionDAG &DAG,
5644                                       SDLoc dl) {
5645   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5646   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5647   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5648
5649   enum {
5650     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5651     OP_VMRGHW,
5652     OP_VMRGLW,
5653     OP_VSPLTISW0,
5654     OP_VSPLTISW1,
5655     OP_VSPLTISW2,
5656     OP_VSPLTISW3,
5657     OP_VSLDOI4,
5658     OP_VSLDOI8,
5659     OP_VSLDOI12
5660   };
5661
5662   if (OpNum == OP_COPY) {
5663     if (LHSID == (1*9+2)*9+3) return LHS;
5664     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5665     return RHS;
5666   }
5667
5668   SDValue OpLHS, OpRHS;
5669   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5670   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5671
5672   int ShufIdxs[16];
5673   switch (OpNum) {
5674   default: llvm_unreachable("Unknown i32 permute!");
5675   case OP_VMRGHW:
5676     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
5677     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5678     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
5679     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5680     break;
5681   case OP_VMRGLW:
5682     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5683     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5684     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5685     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5686     break;
5687   case OP_VSPLTISW0:
5688     for (unsigned i = 0; i != 16; ++i)
5689       ShufIdxs[i] = (i&3)+0;
5690     break;
5691   case OP_VSPLTISW1:
5692     for (unsigned i = 0; i != 16; ++i)
5693       ShufIdxs[i] = (i&3)+4;
5694     break;
5695   case OP_VSPLTISW2:
5696     for (unsigned i = 0; i != 16; ++i)
5697       ShufIdxs[i] = (i&3)+8;
5698     break;
5699   case OP_VSPLTISW3:
5700     for (unsigned i = 0; i != 16; ++i)
5701       ShufIdxs[i] = (i&3)+12;
5702     break;
5703   case OP_VSLDOI4:
5704     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5705   case OP_VSLDOI8:
5706     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5707   case OP_VSLDOI12:
5708     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5709   }
5710   EVT VT = OpLHS.getValueType();
5711   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5712   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5713   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5714   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5715 }
5716
5717 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
5718 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
5719 /// return the code it can be lowered into.  Worst case, it can always be
5720 /// lowered into a vperm.
5721 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5722                                                SelectionDAG &DAG) const {
5723   SDLoc dl(Op);
5724   SDValue V1 = Op.getOperand(0);
5725   SDValue V2 = Op.getOperand(1);
5726   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5727   EVT VT = Op.getValueType();
5728
5729   // Cases that are handled by instructions that take permute immediates
5730   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5731   // selected by the instruction selector.
5732   if (V2.getOpcode() == ISD::UNDEF) {
5733     if (PPC::isSplatShuffleMask(SVOp, 1) ||
5734         PPC::isSplatShuffleMask(SVOp, 2) ||
5735         PPC::isSplatShuffleMask(SVOp, 4) ||
5736         PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5737         PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5738         PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5739         PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5740         PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5741         PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5742         PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5743         PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5744         PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5745       return Op;
5746     }
5747   }
5748
5749   // Altivec has a variety of "shuffle immediates" that take two vector inputs
5750   // and produce a fixed permutation.  If any of these match, do not lower to
5751   // VPERM.
5752   if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5753       PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5754       PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5755       PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5756       PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5757       PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5758       PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5759       PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5760       PPC::isVMRGHShuffleMask(SVOp, 4, false))
5761     return Op;
5762
5763   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
5764   // perfect shuffle table to emit an optimal matching sequence.
5765   ArrayRef<int> PermMask = SVOp->getMask();
5766
5767   unsigned PFIndexes[4];
5768   bool isFourElementShuffle = true;
5769   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5770     unsigned EltNo = 8;   // Start out undef.
5771     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
5772       if (PermMask[i*4+j] < 0)
5773         continue;   // Undef, ignore it.
5774
5775       unsigned ByteSource = PermMask[i*4+j];
5776       if ((ByteSource & 3) != j) {
5777         isFourElementShuffle = false;
5778         break;
5779       }
5780
5781       if (EltNo == 8) {
5782         EltNo = ByteSource/4;
5783       } else if (EltNo != ByteSource/4) {
5784         isFourElementShuffle = false;
5785         break;
5786       }
5787     }
5788     PFIndexes[i] = EltNo;
5789   }
5790
5791   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5792   // perfect shuffle vector to determine if it is cost effective to do this as
5793   // discrete instructions, or whether we should use a vperm.
5794   if (isFourElementShuffle) {
5795     // Compute the index in the perfect shuffle table.
5796     unsigned PFTableIndex =
5797       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5798
5799     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5800     unsigned Cost  = (PFEntry >> 30);
5801
5802     // Determining when to avoid vperm is tricky.  Many things affect the cost
5803     // of vperm, particularly how many times the perm mask needs to be computed.
5804     // For example, if the perm mask can be hoisted out of a loop or is already
5805     // used (perhaps because there are multiple permutes with the same shuffle
5806     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
5807     // the loop requires an extra register.
5808     //
5809     // As a compromise, we only emit discrete instructions if the shuffle can be
5810     // generated in 3 or fewer operations.  When we have loop information
5811     // available, if this block is within a loop, we should avoid using vperm
5812     // for 3-operation perms and use a constant pool load instead.
5813     if (Cost < 3)
5814       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5815   }
5816
5817   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5818   // vector that will get spilled to the constant pool.
5819   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5820
5821   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5822   // that it is in input element units, not in bytes.  Convert now.
5823   EVT EltVT = V1.getValueType().getVectorElementType();
5824   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5825
5826   SmallVector<SDValue, 16> ResultMask;
5827   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5828     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5829
5830     for (unsigned j = 0; j != BytesPerElement; ++j)
5831       ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5832                                            MVT::i32));
5833   }
5834
5835   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5836                                   ResultMask);
5837   return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5838 }
5839
5840 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5841 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
5842 /// information about the intrinsic.
5843 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5844                                   bool &isDot) {
5845   unsigned IntrinsicID =
5846     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5847   CompareOpc = -1;
5848   isDot = false;
5849   switch (IntrinsicID) {
5850   default: return false;
5851     // Comparison predicates.
5852   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
5853   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5854   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
5855   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
5856   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5857   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5858   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5859   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5860   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5861   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5862   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5863   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5864   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5865
5866     // Normal Comparisons.
5867   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
5868   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
5869   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
5870   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
5871   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
5872   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
5873   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
5874   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
5875   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
5876   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
5877   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
5878   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
5879   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
5880   }
5881   return true;
5882 }
5883
5884 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5885 /// lower, do it, otherwise return null.
5886 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5887                                                    SelectionDAG &DAG) const {
5888   // If this is a lowered altivec predicate compare, CompareOpc is set to the
5889   // opcode number of the comparison.
5890   SDLoc dl(Op);
5891   int CompareOpc;
5892   bool isDot;
5893   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5894     return SDValue();    // Don't custom lower most intrinsics.
5895
5896   // If this is a non-dot comparison, make the VCMP node and we are done.
5897   if (!isDot) {
5898     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5899                               Op.getOperand(1), Op.getOperand(2),
5900                               DAG.getConstant(CompareOpc, MVT::i32));
5901     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5902   }
5903
5904   // Create the PPCISD altivec 'dot' comparison node.
5905   SDValue Ops[] = {
5906     Op.getOperand(2),  // LHS
5907     Op.getOperand(3),  // RHS
5908     DAG.getConstant(CompareOpc, MVT::i32)
5909   };
5910   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5911   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
5912
5913   // Now that we have the comparison, emit a copy from the CR to a GPR.
5914   // This is flagged to the above dot comparison.
5915   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5916                                 DAG.getRegister(PPC::CR6, MVT::i32),
5917                                 CompNode.getValue(1));
5918
5919   // Unpack the result based on how the target uses it.
5920   unsigned BitNo;   // Bit # of CR6.
5921   bool InvertBit;   // Invert result?
5922   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5923   default:  // Can't happen, don't crash on invalid number though.
5924   case 0:   // Return the value of the EQ bit of CR6.
5925     BitNo = 0; InvertBit = false;
5926     break;
5927   case 1:   // Return the inverted value of the EQ bit of CR6.
5928     BitNo = 0; InvertBit = true;
5929     break;
5930   case 2:   // Return the value of the LT bit of CR6.
5931     BitNo = 2; InvertBit = false;
5932     break;
5933   case 3:   // Return the inverted value of the LT bit of CR6.
5934     BitNo = 2; InvertBit = true;
5935     break;
5936   }
5937
5938   // Shift the bit into the low position.
5939   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5940                       DAG.getConstant(8-(3-BitNo), MVT::i32));
5941   // Isolate the bit.
5942   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5943                       DAG.getConstant(1, MVT::i32));
5944
5945   // If we are supposed to, toggle the bit.
5946   if (InvertBit)
5947     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5948                         DAG.getConstant(1, MVT::i32));
5949   return Flags;
5950 }
5951
5952 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
5953                                                   SelectionDAG &DAG) const {
5954   SDLoc dl(Op);
5955   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
5956   // instructions), but for smaller types, we need to first extend up to v2i32
5957   // before doing going farther.
5958   if (Op.getValueType() == MVT::v2i64) {
5959     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5960     if (ExtVT != MVT::v2i32) {
5961       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
5962       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
5963                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
5964                                         ExtVT.getVectorElementType(), 4)));
5965       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
5966       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
5967                        DAG.getValueType(MVT::v2i32));
5968     }
5969
5970     return Op;
5971   }
5972
5973   return SDValue();
5974 }
5975
5976 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5977                                                    SelectionDAG &DAG) const {
5978   SDLoc dl(Op);
5979   // Create a stack slot that is 16-byte aligned.
5980   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5981   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5982   EVT PtrVT = getPointerTy();
5983   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5984
5985   // Store the input value into Value#0 of the stack slot.
5986   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5987                                Op.getOperand(0), FIdx, MachinePointerInfo(),
5988                                false, false, 0);
5989   // Load it out.
5990   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5991                      false, false, false, 0);
5992 }
5993
5994 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5995   SDLoc dl(Op);
5996   if (Op.getValueType() == MVT::v4i32) {
5997     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5998
5999     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6000     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6001
6002     SDValue RHSSwap =   // = vrlw RHS, 16
6003       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6004
6005     // Shrinkify inputs to v8i16.
6006     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6007     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6008     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6009
6010     // Low parts multiplied together, generating 32-bit results (we ignore the
6011     // top parts).
6012     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6013                                         LHS, RHS, DAG, dl, MVT::v4i32);
6014
6015     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6016                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6017     // Shift the high parts up 16 bits.
6018     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6019                               Neg16, DAG, dl);
6020     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6021   } else if (Op.getValueType() == MVT::v8i16) {
6022     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6023
6024     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6025
6026     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6027                             LHS, RHS, Zero, DAG, dl);
6028   } else if (Op.getValueType() == MVT::v16i8) {
6029     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6030
6031     // Multiply the even 8-bit parts, producing 16-bit sums.
6032     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6033                                            LHS, RHS, DAG, dl, MVT::v8i16);
6034     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6035
6036     // Multiply the odd 8-bit parts, producing 16-bit sums.
6037     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6038                                           LHS, RHS, DAG, dl, MVT::v8i16);
6039     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6040
6041     // Merge the results together.
6042     int Ops[16];
6043     for (unsigned i = 0; i != 8; ++i) {
6044       Ops[i*2  ] = 2*i+1;
6045       Ops[i*2+1] = 2*i+1+16;
6046     }
6047     return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6048   } else {
6049     llvm_unreachable("Unknown mul to lower!");
6050   }
6051 }
6052
6053 /// LowerOperation - Provide custom lowering hooks for some operations.
6054 ///
6055 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6056   switch (Op.getOpcode()) {
6057   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6058   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6059   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6060   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6061   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6062   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6063   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6064   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6065   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6066   case ISD::VASTART:
6067     return LowerVASTART(Op, DAG, PPCSubTarget);
6068
6069   case ISD::VAARG:
6070     return LowerVAARG(Op, DAG, PPCSubTarget);
6071
6072   case ISD::VACOPY:
6073     return LowerVACOPY(Op, DAG, PPCSubTarget);
6074
6075   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
6076   case ISD::DYNAMIC_STACKALLOC:
6077     return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
6078
6079   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6080   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6081
6082   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6083   case ISD::STORE:              return LowerSTORE(Op, DAG);
6084   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6085   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6086   case ISD::FP_TO_UINT:
6087   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6088                                                        SDLoc(Op));
6089   case ISD::UINT_TO_FP:
6090   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6091   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6092
6093   // Lower 64-bit shifts.
6094   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6095   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6096   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6097
6098   // Vector-related lowering.
6099   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6100   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6101   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6102   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6103   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6104   case ISD::MUL:                return LowerMUL(Op, DAG);
6105
6106   // For counter-based loop handling.
6107   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6108
6109   // Frame & Return address.
6110   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6111   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6112   }
6113 }
6114
6115 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6116                                            SmallVectorImpl<SDValue>&Results,
6117                                            SelectionDAG &DAG) const {
6118   const TargetMachine &TM = getTargetMachine();
6119   SDLoc dl(N);
6120   switch (N->getOpcode()) {
6121   default:
6122     llvm_unreachable("Do not know how to custom type legalize this operation!");
6123   case ISD::INTRINSIC_W_CHAIN: {
6124     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6125         Intrinsic::ppc_is_decremented_ctr_nonzero)
6126       break;
6127
6128     assert(N->getValueType(0) == MVT::i1 &&
6129            "Unexpected result type for CTR decrement intrinsic");
6130     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6131     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6132     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6133                                  N->getOperand(1)); 
6134
6135     Results.push_back(NewInt);
6136     Results.push_back(NewInt.getValue(1));
6137     break;
6138   }
6139   case ISD::VAARG: {
6140     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6141         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6142       return;
6143
6144     EVT VT = N->getValueType(0);
6145
6146     if (VT == MVT::i64) {
6147       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6148
6149       Results.push_back(NewNode);
6150       Results.push_back(NewNode.getValue(1));
6151     }
6152     return;
6153   }
6154   case ISD::FP_ROUND_INREG: {
6155     assert(N->getValueType(0) == MVT::ppcf128);
6156     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6157     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6158                              MVT::f64, N->getOperand(0),
6159                              DAG.getIntPtrConstant(0));
6160     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6161                              MVT::f64, N->getOperand(0),
6162                              DAG.getIntPtrConstant(1));
6163
6164     // Add the two halves of the long double in round-to-zero mode.
6165     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6166
6167     // We know the low half is about to be thrown away, so just use something
6168     // convenient.
6169     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6170                                 FPreg, FPreg));
6171     return;
6172   }
6173   case ISD::FP_TO_SINT:
6174     // LowerFP_TO_INT() can only handle f32 and f64.
6175     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6176       return;
6177     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6178     return;
6179   }
6180 }
6181
6182
6183 //===----------------------------------------------------------------------===//
6184 //  Other Lowering Code
6185 //===----------------------------------------------------------------------===//
6186
6187 MachineBasicBlock *
6188 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6189                                     bool is64bit, unsigned BinOpcode) const {
6190   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6191   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6192
6193   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6194   MachineFunction *F = BB->getParent();
6195   MachineFunction::iterator It = BB;
6196   ++It;
6197
6198   unsigned dest = MI->getOperand(0).getReg();
6199   unsigned ptrA = MI->getOperand(1).getReg();
6200   unsigned ptrB = MI->getOperand(2).getReg();
6201   unsigned incr = MI->getOperand(3).getReg();
6202   DebugLoc dl = MI->getDebugLoc();
6203
6204   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6205   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6206   F->insert(It, loopMBB);
6207   F->insert(It, exitMBB);
6208   exitMBB->splice(exitMBB->begin(), BB,
6209                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6210   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6211
6212   MachineRegisterInfo &RegInfo = F->getRegInfo();
6213   unsigned TmpReg = (!BinOpcode) ? incr :
6214     RegInfo.createVirtualRegister(
6215        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6216                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
6217
6218   //  thisMBB:
6219   //   ...
6220   //   fallthrough --> loopMBB
6221   BB->addSuccessor(loopMBB);
6222
6223   //  loopMBB:
6224   //   l[wd]arx dest, ptr
6225   //   add r0, dest, incr
6226   //   st[wd]cx. r0, ptr
6227   //   bne- loopMBB
6228   //   fallthrough --> exitMBB
6229   BB = loopMBB;
6230   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6231     .addReg(ptrA).addReg(ptrB);
6232   if (BinOpcode)
6233     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6234   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6235     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6236   BuildMI(BB, dl, TII->get(PPC::BCC))
6237     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6238   BB->addSuccessor(loopMBB);
6239   BB->addSuccessor(exitMBB);
6240
6241   //  exitMBB:
6242   //   ...
6243   BB = exitMBB;
6244   return BB;
6245 }
6246
6247 MachineBasicBlock *
6248 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6249                                             MachineBasicBlock *BB,
6250                                             bool is8bit,    // operation
6251                                             unsigned BinOpcode) const {
6252   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6253   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6254   // In 64 bit mode we have to use 64 bits for addresses, even though the
6255   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6256   // registers without caring whether they're 32 or 64, but here we're
6257   // doing actual arithmetic on the addresses.
6258   bool is64bit = PPCSubTarget.isPPC64();
6259   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6260
6261   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6262   MachineFunction *F = BB->getParent();
6263   MachineFunction::iterator It = BB;
6264   ++It;
6265
6266   unsigned dest = MI->getOperand(0).getReg();
6267   unsigned ptrA = MI->getOperand(1).getReg();
6268   unsigned ptrB = MI->getOperand(2).getReg();
6269   unsigned incr = MI->getOperand(3).getReg();
6270   DebugLoc dl = MI->getDebugLoc();
6271
6272   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6273   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6274   F->insert(It, loopMBB);
6275   F->insert(It, exitMBB);
6276   exitMBB->splice(exitMBB->begin(), BB,
6277                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6278   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6279
6280   MachineRegisterInfo &RegInfo = F->getRegInfo();
6281   const TargetRegisterClass *RC =
6282     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6283               (const TargetRegisterClass *) &PPC::GPRCRegClass;
6284   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6285   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6286   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6287   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6288   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6289   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6290   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6291   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6292   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6293   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6294   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6295   unsigned Ptr1Reg;
6296   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6297
6298   //  thisMBB:
6299   //   ...
6300   //   fallthrough --> loopMBB
6301   BB->addSuccessor(loopMBB);
6302
6303   // The 4-byte load must be aligned, while a char or short may be
6304   // anywhere in the word.  Hence all this nasty bookkeeping code.
6305   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6306   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6307   //   xori shift, shift1, 24 [16]
6308   //   rlwinm ptr, ptr1, 0, 0, 29
6309   //   slw incr2, incr, shift
6310   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6311   //   slw mask, mask2, shift
6312   //  loopMBB:
6313   //   lwarx tmpDest, ptr
6314   //   add tmp, tmpDest, incr2
6315   //   andc tmp2, tmpDest, mask
6316   //   and tmp3, tmp, mask
6317   //   or tmp4, tmp3, tmp2
6318   //   stwcx. tmp4, ptr
6319   //   bne- loopMBB
6320   //   fallthrough --> exitMBB
6321   //   srw dest, tmpDest, shift
6322   if (ptrA != ZeroReg) {
6323     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6324     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6325       .addReg(ptrA).addReg(ptrB);
6326   } else {
6327     Ptr1Reg = ptrB;
6328   }
6329   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6330       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6331   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6332       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6333   if (is64bit)
6334     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6335       .addReg(Ptr1Reg).addImm(0).addImm(61);
6336   else
6337     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6338       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6339   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6340       .addReg(incr).addReg(ShiftReg);
6341   if (is8bit)
6342     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6343   else {
6344     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6345     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6346   }
6347   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6348       .addReg(Mask2Reg).addReg(ShiftReg);
6349
6350   BB = loopMBB;
6351   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6352     .addReg(ZeroReg).addReg(PtrReg);
6353   if (BinOpcode)
6354     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6355       .addReg(Incr2Reg).addReg(TmpDestReg);
6356   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6357     .addReg(TmpDestReg).addReg(MaskReg);
6358   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6359     .addReg(TmpReg).addReg(MaskReg);
6360   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6361     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6362   BuildMI(BB, dl, TII->get(PPC::STWCX))
6363     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6364   BuildMI(BB, dl, TII->get(PPC::BCC))
6365     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6366   BB->addSuccessor(loopMBB);
6367   BB->addSuccessor(exitMBB);
6368
6369   //  exitMBB:
6370   //   ...
6371   BB = exitMBB;
6372   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6373     .addReg(ShiftReg);
6374   return BB;
6375 }
6376
6377 llvm::MachineBasicBlock*
6378 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6379                                     MachineBasicBlock *MBB) const {
6380   DebugLoc DL = MI->getDebugLoc();
6381   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6382
6383   MachineFunction *MF = MBB->getParent();
6384   MachineRegisterInfo &MRI = MF->getRegInfo();
6385
6386   const BasicBlock *BB = MBB->getBasicBlock();
6387   MachineFunction::iterator I = MBB;
6388   ++I;
6389
6390   // Memory Reference
6391   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6392   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6393
6394   unsigned DstReg = MI->getOperand(0).getReg();
6395   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6396   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6397   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6398   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6399
6400   MVT PVT = getPointerTy();
6401   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6402          "Invalid Pointer Size!");
6403   // For v = setjmp(buf), we generate
6404   //
6405   // thisMBB:
6406   //  SjLjSetup mainMBB
6407   //  bl mainMBB
6408   //  v_restore = 1
6409   //  b sinkMBB
6410   //
6411   // mainMBB:
6412   //  buf[LabelOffset] = LR
6413   //  v_main = 0
6414   //
6415   // sinkMBB:
6416   //  v = phi(main, restore)
6417   //
6418
6419   MachineBasicBlock *thisMBB = MBB;
6420   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6421   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6422   MF->insert(I, mainMBB);
6423   MF->insert(I, sinkMBB);
6424
6425   MachineInstrBuilder MIB;
6426
6427   // Transfer the remainder of BB and its successor edges to sinkMBB.
6428   sinkMBB->splice(sinkMBB->begin(), MBB,
6429                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6430   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6431
6432   // Note that the structure of the jmp_buf used here is not compatible
6433   // with that used by libc, and is not designed to be. Specifically, it
6434   // stores only those 'reserved' registers that LLVM does not otherwise
6435   // understand how to spill. Also, by convention, by the time this
6436   // intrinsic is called, Clang has already stored the frame address in the
6437   // first slot of the buffer and stack address in the third. Following the
6438   // X86 target code, we'll store the jump address in the second slot. We also
6439   // need to save the TOC pointer (R2) to handle jumps between shared
6440   // libraries, and that will be stored in the fourth slot. The thread
6441   // identifier (R13) is not affected.
6442
6443   // thisMBB:
6444   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6445   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6446   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6447
6448   // Prepare IP either in reg.
6449   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6450   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6451   unsigned BufReg = MI->getOperand(1).getReg();
6452
6453   if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6454     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6455             .addReg(PPC::X2)
6456             .addImm(TOCOffset)
6457             .addReg(BufReg);
6458     MIB.setMemRefs(MMOBegin, MMOEnd);
6459   }
6460
6461   // Naked functions never have a base pointer, and so we use r1. For all
6462   // other functions, this decision must be delayed until during PEI.
6463   unsigned BaseReg;
6464   if (MF->getFunction()->getAttributes().hasAttribute(
6465           AttributeSet::FunctionIndex, Attribute::Naked))
6466     BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6467   else
6468     BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6469
6470   MIB = BuildMI(*thisMBB, MI, DL,
6471                 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6472           .addReg(BaseReg)
6473           .addImm(BPOffset)
6474           .addReg(BufReg);
6475   MIB.setMemRefs(MMOBegin, MMOEnd);
6476
6477   // Setup
6478   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6479   const PPCRegisterInfo *TRI =
6480     static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6481   MIB.addRegMask(TRI->getNoPreservedMask());
6482
6483   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6484
6485   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6486           .addMBB(mainMBB);
6487   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6488
6489   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6490   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6491
6492   // mainMBB:
6493   //  mainDstReg = 0
6494   MIB = BuildMI(mainMBB, DL,
6495     TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6496
6497   // Store IP
6498   if (PPCSubTarget.isPPC64()) {
6499     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6500             .addReg(LabelReg)
6501             .addImm(LabelOffset)
6502             .addReg(BufReg);
6503   } else {
6504     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6505             .addReg(LabelReg)
6506             .addImm(LabelOffset)
6507             .addReg(BufReg);
6508   }
6509
6510   MIB.setMemRefs(MMOBegin, MMOEnd);
6511
6512   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6513   mainMBB->addSuccessor(sinkMBB);
6514
6515   // sinkMBB:
6516   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6517           TII->get(PPC::PHI), DstReg)
6518     .addReg(mainDstReg).addMBB(mainMBB)
6519     .addReg(restoreDstReg).addMBB(thisMBB);
6520
6521   MI->eraseFromParent();
6522   return sinkMBB;
6523 }
6524
6525 MachineBasicBlock *
6526 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6527                                      MachineBasicBlock *MBB) const {
6528   DebugLoc DL = MI->getDebugLoc();
6529   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6530
6531   MachineFunction *MF = MBB->getParent();
6532   MachineRegisterInfo &MRI = MF->getRegInfo();
6533
6534   // Memory Reference
6535   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6536   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6537
6538   MVT PVT = getPointerTy();
6539   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6540          "Invalid Pointer Size!");
6541
6542   const TargetRegisterClass *RC =
6543     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6544   unsigned Tmp = MRI.createVirtualRegister(RC);
6545   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6546   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6547   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6548   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6549
6550   MachineInstrBuilder MIB;
6551
6552   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6553   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6554   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6555   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6556
6557   unsigned BufReg = MI->getOperand(0).getReg();
6558
6559   // Reload FP (the jumped-to function may not have had a
6560   // frame pointer, and if so, then its r31 will be restored
6561   // as necessary).
6562   if (PVT == MVT::i64) {
6563     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6564             .addImm(0)
6565             .addReg(BufReg);
6566   } else {
6567     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6568             .addImm(0)
6569             .addReg(BufReg);
6570   }
6571   MIB.setMemRefs(MMOBegin, MMOEnd);
6572
6573   // Reload IP
6574   if (PVT == MVT::i64) {
6575     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6576             .addImm(LabelOffset)
6577             .addReg(BufReg);
6578   } else {
6579     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6580             .addImm(LabelOffset)
6581             .addReg(BufReg);
6582   }
6583   MIB.setMemRefs(MMOBegin, MMOEnd);
6584
6585   // Reload SP
6586   if (PVT == MVT::i64) {
6587     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6588             .addImm(SPOffset)
6589             .addReg(BufReg);
6590   } else {
6591     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6592             .addImm(SPOffset)
6593             .addReg(BufReg);
6594   }
6595   MIB.setMemRefs(MMOBegin, MMOEnd);
6596
6597   // Reload BP
6598   if (PVT == MVT::i64) {
6599     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6600             .addImm(BPOffset)
6601             .addReg(BufReg);
6602   } else {
6603     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6604             .addImm(BPOffset)
6605             .addReg(BufReg);
6606   }
6607   MIB.setMemRefs(MMOBegin, MMOEnd);
6608
6609   // Reload TOC
6610   if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6611     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6612             .addImm(TOCOffset)
6613             .addReg(BufReg);
6614
6615     MIB.setMemRefs(MMOBegin, MMOEnd);
6616   }
6617
6618   // Jump
6619   BuildMI(*MBB, MI, DL,
6620           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6621   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6622
6623   MI->eraseFromParent();
6624   return MBB;
6625 }
6626
6627 MachineBasicBlock *
6628 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6629                                                MachineBasicBlock *BB) const {
6630   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6631       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6632     return emitEHSjLjSetJmp(MI, BB);
6633   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6634              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6635     return emitEHSjLjLongJmp(MI, BB);
6636   }
6637
6638   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6639
6640   // To "insert" these instructions we actually have to insert their
6641   // control-flow patterns.
6642   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6643   MachineFunction::iterator It = BB;
6644   ++It;
6645
6646   MachineFunction *F = BB->getParent();
6647
6648   if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6649                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
6650                                  MI->getOpcode() == PPC::SELECT_I4 ||
6651                                  MI->getOpcode() == PPC::SELECT_I8)) {
6652     SmallVector<MachineOperand, 2> Cond;
6653     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6654         MI->getOpcode() == PPC::SELECT_CC_I8)
6655       Cond.push_back(MI->getOperand(4));
6656     else
6657       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6658     Cond.push_back(MI->getOperand(1));
6659
6660     DebugLoc dl = MI->getDebugLoc();
6661     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6662     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6663                       Cond, MI->getOperand(2).getReg(),
6664                       MI->getOperand(3).getReg());
6665   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6666              MI->getOpcode() == PPC::SELECT_CC_I8 ||
6667              MI->getOpcode() == PPC::SELECT_CC_F4 ||
6668              MI->getOpcode() == PPC::SELECT_CC_F8 ||
6669              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6670              MI->getOpcode() == PPC::SELECT_I4 ||
6671              MI->getOpcode() == PPC::SELECT_I8 ||
6672              MI->getOpcode() == PPC::SELECT_F4 ||
6673              MI->getOpcode() == PPC::SELECT_F8 ||
6674              MI->getOpcode() == PPC::SELECT_VRRC) {
6675     // The incoming instruction knows the destination vreg to set, the
6676     // condition code register to branch on, the true/false values to
6677     // select between, and a branch opcode to use.
6678
6679     //  thisMBB:
6680     //  ...
6681     //   TrueVal = ...
6682     //   cmpTY ccX, r1, r2
6683     //   bCC copy1MBB
6684     //   fallthrough --> copy0MBB
6685     MachineBasicBlock *thisMBB = BB;
6686     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6687     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6688     DebugLoc dl = MI->getDebugLoc();
6689     F->insert(It, copy0MBB);
6690     F->insert(It, sinkMBB);
6691
6692     // Transfer the remainder of BB and its successor edges to sinkMBB.
6693     sinkMBB->splice(sinkMBB->begin(), BB,
6694                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
6695     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6696
6697     // Next, add the true and fallthrough blocks as its successors.
6698     BB->addSuccessor(copy0MBB);
6699     BB->addSuccessor(sinkMBB);
6700
6701     if (MI->getOpcode() == PPC::SELECT_I4 ||
6702         MI->getOpcode() == PPC::SELECT_I8 ||
6703         MI->getOpcode() == PPC::SELECT_F4 ||
6704         MI->getOpcode() == PPC::SELECT_F8 ||
6705         MI->getOpcode() == PPC::SELECT_VRRC) {
6706       BuildMI(BB, dl, TII->get(PPC::BC))
6707         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6708     } else {
6709       unsigned SelectPred = MI->getOperand(4).getImm();
6710       BuildMI(BB, dl, TII->get(PPC::BCC))
6711         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6712     }
6713
6714     //  copy0MBB:
6715     //   %FalseValue = ...
6716     //   # fallthrough to sinkMBB
6717     BB = copy0MBB;
6718
6719     // Update machine-CFG edges
6720     BB->addSuccessor(sinkMBB);
6721
6722     //  sinkMBB:
6723     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6724     //  ...
6725     BB = sinkMBB;
6726     BuildMI(*BB, BB->begin(), dl,
6727             TII->get(PPC::PHI), MI->getOperand(0).getReg())
6728       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6729       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6730   }
6731   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6732     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6733   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6734     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6735   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6736     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6737   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6738     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6739
6740   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6741     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6742   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6743     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6744   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6745     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6746   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6747     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6748
6749   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6750     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6751   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6752     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6753   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6754     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6755   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6756     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6757
6758   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6759     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6760   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6761     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6762   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6763     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6764   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6765     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6766
6767   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6768     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6769   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6770     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6771   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6772     BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6773   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6774     BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6775
6776   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6777     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6778   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6779     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6780   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6781     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6782   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6783     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6784
6785   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6786     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6787   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6788     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6789   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6790     BB = EmitAtomicBinary(MI, BB, false, 0);
6791   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6792     BB = EmitAtomicBinary(MI, BB, true, 0);
6793
6794   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6795            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6796     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6797
6798     unsigned dest   = MI->getOperand(0).getReg();
6799     unsigned ptrA   = MI->getOperand(1).getReg();
6800     unsigned ptrB   = MI->getOperand(2).getReg();
6801     unsigned oldval = MI->getOperand(3).getReg();
6802     unsigned newval = MI->getOperand(4).getReg();
6803     DebugLoc dl     = MI->getDebugLoc();
6804
6805     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6806     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6807     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6808     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6809     F->insert(It, loop1MBB);
6810     F->insert(It, loop2MBB);
6811     F->insert(It, midMBB);
6812     F->insert(It, exitMBB);
6813     exitMBB->splice(exitMBB->begin(), BB,
6814                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
6815     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6816
6817     //  thisMBB:
6818     //   ...
6819     //   fallthrough --> loopMBB
6820     BB->addSuccessor(loop1MBB);
6821
6822     // loop1MBB:
6823     //   l[wd]arx dest, ptr
6824     //   cmp[wd] dest, oldval
6825     //   bne- midMBB
6826     // loop2MBB:
6827     //   st[wd]cx. newval, ptr
6828     //   bne- loopMBB
6829     //   b exitBB
6830     // midMBB:
6831     //   st[wd]cx. dest, ptr
6832     // exitBB:
6833     BB = loop1MBB;
6834     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6835       .addReg(ptrA).addReg(ptrB);
6836     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6837       .addReg(oldval).addReg(dest);
6838     BuildMI(BB, dl, TII->get(PPC::BCC))
6839       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6840     BB->addSuccessor(loop2MBB);
6841     BB->addSuccessor(midMBB);
6842
6843     BB = loop2MBB;
6844     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6845       .addReg(newval).addReg(ptrA).addReg(ptrB);
6846     BuildMI(BB, dl, TII->get(PPC::BCC))
6847       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6848     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6849     BB->addSuccessor(loop1MBB);
6850     BB->addSuccessor(exitMBB);
6851
6852     BB = midMBB;
6853     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6854       .addReg(dest).addReg(ptrA).addReg(ptrB);
6855     BB->addSuccessor(exitMBB);
6856
6857     //  exitMBB:
6858     //   ...
6859     BB = exitMBB;
6860   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6861              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6862     // We must use 64-bit registers for addresses when targeting 64-bit,
6863     // since we're actually doing arithmetic on them.  Other registers
6864     // can be 32-bit.
6865     bool is64bit = PPCSubTarget.isPPC64();
6866     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6867
6868     unsigned dest   = MI->getOperand(0).getReg();
6869     unsigned ptrA   = MI->getOperand(1).getReg();
6870     unsigned ptrB   = MI->getOperand(2).getReg();
6871     unsigned oldval = MI->getOperand(3).getReg();
6872     unsigned newval = MI->getOperand(4).getReg();
6873     DebugLoc dl     = MI->getDebugLoc();
6874
6875     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6876     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6877     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6878     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6879     F->insert(It, loop1MBB);
6880     F->insert(It, loop2MBB);
6881     F->insert(It, midMBB);
6882     F->insert(It, exitMBB);
6883     exitMBB->splice(exitMBB->begin(), BB,
6884                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
6885     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6886
6887     MachineRegisterInfo &RegInfo = F->getRegInfo();
6888     const TargetRegisterClass *RC =
6889       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6890                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6891     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6892     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6893     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6894     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6895     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6896     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6897     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6898     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6899     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6900     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6901     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6902     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6903     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6904     unsigned Ptr1Reg;
6905     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6906     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6907     //  thisMBB:
6908     //   ...
6909     //   fallthrough --> loopMBB
6910     BB->addSuccessor(loop1MBB);
6911
6912     // The 4-byte load must be aligned, while a char or short may be
6913     // anywhere in the word.  Hence all this nasty bookkeeping code.
6914     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6915     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6916     //   xori shift, shift1, 24 [16]
6917     //   rlwinm ptr, ptr1, 0, 0, 29
6918     //   slw newval2, newval, shift
6919     //   slw oldval2, oldval,shift
6920     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6921     //   slw mask, mask2, shift
6922     //   and newval3, newval2, mask
6923     //   and oldval3, oldval2, mask
6924     // loop1MBB:
6925     //   lwarx tmpDest, ptr
6926     //   and tmp, tmpDest, mask
6927     //   cmpw tmp, oldval3
6928     //   bne- midMBB
6929     // loop2MBB:
6930     //   andc tmp2, tmpDest, mask
6931     //   or tmp4, tmp2, newval3
6932     //   stwcx. tmp4, ptr
6933     //   bne- loop1MBB
6934     //   b exitBB
6935     // midMBB:
6936     //   stwcx. tmpDest, ptr
6937     // exitBB:
6938     //   srw dest, tmpDest, shift
6939     if (ptrA != ZeroReg) {
6940       Ptr1Reg = RegInfo.createVirtualRegister(RC);
6941       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6942         .addReg(ptrA).addReg(ptrB);
6943     } else {
6944       Ptr1Reg = ptrB;
6945     }
6946     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6947         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6948     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6949         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6950     if (is64bit)
6951       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6952         .addReg(Ptr1Reg).addImm(0).addImm(61);
6953     else
6954       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6955         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6956     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6957         .addReg(newval).addReg(ShiftReg);
6958     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6959         .addReg(oldval).addReg(ShiftReg);
6960     if (is8bit)
6961       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6962     else {
6963       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6964       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6965         .addReg(Mask3Reg).addImm(65535);
6966     }
6967     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6968         .addReg(Mask2Reg).addReg(ShiftReg);
6969     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6970         .addReg(NewVal2Reg).addReg(MaskReg);
6971     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6972         .addReg(OldVal2Reg).addReg(MaskReg);
6973
6974     BB = loop1MBB;
6975     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6976         .addReg(ZeroReg).addReg(PtrReg);
6977     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6978         .addReg(TmpDestReg).addReg(MaskReg);
6979     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6980         .addReg(TmpReg).addReg(OldVal3Reg);
6981     BuildMI(BB, dl, TII->get(PPC::BCC))
6982         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6983     BB->addSuccessor(loop2MBB);
6984     BB->addSuccessor(midMBB);
6985
6986     BB = loop2MBB;
6987     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6988         .addReg(TmpDestReg).addReg(MaskReg);
6989     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6990         .addReg(Tmp2Reg).addReg(NewVal3Reg);
6991     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6992         .addReg(ZeroReg).addReg(PtrReg);
6993     BuildMI(BB, dl, TII->get(PPC::BCC))
6994       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6995     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6996     BB->addSuccessor(loop1MBB);
6997     BB->addSuccessor(exitMBB);
6998
6999     BB = midMBB;
7000     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7001       .addReg(ZeroReg).addReg(PtrReg);
7002     BB->addSuccessor(exitMBB);
7003
7004     //  exitMBB:
7005     //   ...
7006     BB = exitMBB;
7007     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7008       .addReg(ShiftReg);
7009   } else if (MI->getOpcode() == PPC::FADDrtz) {
7010     // This pseudo performs an FADD with rounding mode temporarily forced
7011     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7012     // is not modeled at the SelectionDAG level.
7013     unsigned Dest = MI->getOperand(0).getReg();
7014     unsigned Src1 = MI->getOperand(1).getReg();
7015     unsigned Src2 = MI->getOperand(2).getReg();
7016     DebugLoc dl   = MI->getDebugLoc();
7017
7018     MachineRegisterInfo &RegInfo = F->getRegInfo();
7019     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7020
7021     // Save FPSCR value.
7022     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7023
7024     // Set rounding mode to round-to-zero.
7025     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7026     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7027
7028     // Perform addition.
7029     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7030
7031     // Restore FPSCR value.
7032     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7033   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7034              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7035              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7036              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7037     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7038                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7039                       PPC::ANDIo8 : PPC::ANDIo;
7040     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7041                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7042
7043     MachineRegisterInfo &RegInfo = F->getRegInfo();
7044     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7045                                                   &PPC::GPRCRegClass :
7046                                                   &PPC::G8RCRegClass);
7047
7048     DebugLoc dl   = MI->getDebugLoc();
7049     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7050       .addReg(MI->getOperand(1).getReg()).addImm(1);
7051     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7052             MI->getOperand(0).getReg())
7053       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7054   } else {
7055     llvm_unreachable("Unexpected instr type to insert");
7056   }
7057
7058   MI->eraseFromParent();   // The pseudo instruction is gone now.
7059   return BB;
7060 }
7061
7062 //===----------------------------------------------------------------------===//
7063 // Target Optimization Hooks
7064 //===----------------------------------------------------------------------===//
7065
7066 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7067                                                DAGCombinerInfo &DCI) const {
7068   if (DCI.isAfterLegalizeVectorOps())
7069     return SDValue();
7070
7071   EVT VT = Op.getValueType();
7072
7073   if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
7074       (VT == MVT::f64 && PPCSubTarget.hasFRE())  ||
7075       (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7076       (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7077
7078     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7079     // For the reciprocal, we need to find the zero of the function:
7080     //   F(X) = A X - 1 [which has a zero at X = 1/A]
7081     //     =>
7082     //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7083     //     does not require additional intermediate precision]
7084
7085     // Convergence is quadratic, so we essentially double the number of digits
7086     // correct after every iteration. The minimum architected relative
7087     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7088     // 23 digits and double has 52 digits.
7089     int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7090     if (VT.getScalarType() == MVT::f64)
7091       ++Iterations;
7092
7093     SelectionDAG &DAG = DCI.DAG;
7094     SDLoc dl(Op);
7095
7096     SDValue FPOne =
7097       DAG.getConstantFP(1.0, VT.getScalarType());
7098     if (VT.isVector()) {
7099       assert(VT.getVectorNumElements() == 4 &&
7100              "Unknown vector type");
7101       FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7102                           FPOne, FPOne, FPOne, FPOne);
7103     }
7104
7105     SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7106     DCI.AddToWorklist(Est.getNode());
7107
7108     // Newton iterations: Est = Est + Est (1 - Arg * Est)
7109     for (int i = 0; i < Iterations; ++i) {
7110       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7111       DCI.AddToWorklist(NewEst.getNode());
7112
7113       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7114       DCI.AddToWorklist(NewEst.getNode());
7115
7116       NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7117       DCI.AddToWorklist(NewEst.getNode());
7118
7119       Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7120       DCI.AddToWorklist(Est.getNode());
7121     }
7122
7123     return Est;
7124   }
7125
7126   return SDValue();
7127 }
7128
7129 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7130                                              DAGCombinerInfo &DCI) const {
7131   if (DCI.isAfterLegalizeVectorOps())
7132     return SDValue();
7133
7134   EVT VT = Op.getValueType();
7135
7136   if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7137       (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE())  ||
7138       (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7139       (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7140
7141     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7142     // For the reciprocal sqrt, we need to find the zero of the function:
7143     //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7144     //     =>
7145     //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7146     // As a result, we precompute A/2 prior to the iteration loop.
7147
7148     // Convergence is quadratic, so we essentially double the number of digits
7149     // correct after every iteration. The minimum architected relative
7150     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7151     // 23 digits and double has 52 digits.
7152     int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7153     if (VT.getScalarType() == MVT::f64)
7154       ++Iterations;
7155
7156     SelectionDAG &DAG = DCI.DAG;
7157     SDLoc dl(Op);
7158
7159     SDValue FPThreeHalves =
7160       DAG.getConstantFP(1.5, VT.getScalarType());
7161     if (VT.isVector()) {
7162       assert(VT.getVectorNumElements() == 4 &&
7163              "Unknown vector type");
7164       FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7165                                   FPThreeHalves, FPThreeHalves,
7166                                   FPThreeHalves, FPThreeHalves);
7167     }
7168
7169     SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7170     DCI.AddToWorklist(Est.getNode());
7171
7172     // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7173     // this entire sequence requires only one FP constant.
7174     SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7175     DCI.AddToWorklist(HalfArg.getNode());
7176
7177     HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7178     DCI.AddToWorklist(HalfArg.getNode());
7179
7180     // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7181     for (int i = 0; i < Iterations; ++i) {
7182       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7183       DCI.AddToWorklist(NewEst.getNode());
7184
7185       NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7186       DCI.AddToWorklist(NewEst.getNode());
7187
7188       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7189       DCI.AddToWorklist(NewEst.getNode());
7190
7191       Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7192       DCI.AddToWorklist(Est.getNode());
7193     }
7194
7195     return Est;
7196   }
7197
7198   return SDValue();
7199 }
7200
7201 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7202 // not enforce equality of the chain operands.
7203 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7204                             unsigned Bytes, int Dist,
7205                             SelectionDAG &DAG) {
7206   EVT VT = LS->getMemoryVT();
7207   if (VT.getSizeInBits() / 8 != Bytes)
7208     return false;
7209
7210   SDValue Loc = LS->getBasePtr();
7211   SDValue BaseLoc = Base->getBasePtr();
7212   if (Loc.getOpcode() == ISD::FrameIndex) {
7213     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7214       return false;
7215     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7216     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7217     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7218     int FS  = MFI->getObjectSize(FI);
7219     int BFS = MFI->getObjectSize(BFI);
7220     if (FS != BFS || FS != (int)Bytes) return false;
7221     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7222   }
7223
7224   // Handle X+C
7225   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7226       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7227     return true;
7228
7229   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7230   const GlobalValue *GV1 = nullptr;
7231   const GlobalValue *GV2 = nullptr;
7232   int64_t Offset1 = 0;
7233   int64_t Offset2 = 0;
7234   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7235   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7236   if (isGA1 && isGA2 && GV1 == GV2)
7237     return Offset1 == (Offset2 + Dist*Bytes);
7238   return false;
7239 }
7240
7241 // Return true is there is a nearyby consecutive load to the one provided
7242 // (regardless of alignment). We search up and down the chain, looking though
7243 // token factors and other loads (but nothing else). As a result, a true
7244 // results indicates that it is safe to create a new consecutive load adjacent
7245 // to the load provided.
7246 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7247   SDValue Chain = LD->getChain();
7248   EVT VT = LD->getMemoryVT();
7249
7250   SmallSet<SDNode *, 16> LoadRoots;
7251   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7252   SmallSet<SDNode *, 16> Visited;
7253
7254   // First, search up the chain, branching to follow all token-factor operands.
7255   // If we find a consecutive load, then we're done, otherwise, record all
7256   // nodes just above the top-level loads and token factors.
7257   while (!Queue.empty()) {
7258     SDNode *ChainNext = Queue.pop_back_val();
7259     if (!Visited.insert(ChainNext))
7260       continue;
7261
7262     if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7263       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7264         return true;
7265
7266       if (!Visited.count(ChainLD->getChain().getNode()))
7267         Queue.push_back(ChainLD->getChain().getNode());
7268     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7269       for (SDNode::op_iterator O = ChainNext->op_begin(),
7270            OE = ChainNext->op_end(); O != OE; ++O)
7271         if (!Visited.count(O->getNode()))
7272           Queue.push_back(O->getNode());
7273     } else
7274       LoadRoots.insert(ChainNext);
7275   }
7276
7277   // Second, search down the chain, starting from the top-level nodes recorded
7278   // in the first phase. These top-level nodes are the nodes just above all
7279   // loads and token factors. Starting with their uses, recursively look though
7280   // all loads (just the chain uses) and token factors to find a consecutive
7281   // load.
7282   Visited.clear();
7283   Queue.clear();
7284
7285   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7286        IE = LoadRoots.end(); I != IE; ++I) {
7287     Queue.push_back(*I);
7288        
7289     while (!Queue.empty()) {
7290       SDNode *LoadRoot = Queue.pop_back_val();
7291       if (!Visited.insert(LoadRoot))
7292         continue;
7293
7294       if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7295         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7296           return true;
7297
7298       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7299            UE = LoadRoot->use_end(); UI != UE; ++UI)
7300         if (((isa<LoadSDNode>(*UI) &&
7301             cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7302             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7303           Queue.push_back(*UI);
7304     }
7305   }
7306
7307   return false;
7308 }
7309
7310 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7311                                                   DAGCombinerInfo &DCI) const {
7312   SelectionDAG &DAG = DCI.DAG;
7313   SDLoc dl(N);
7314
7315   assert(PPCSubTarget.useCRBits() &&
7316          "Expecting to be tracking CR bits");
7317   // If we're tracking CR bits, we need to be careful that we don't have:
7318   //   trunc(binary-ops(zext(x), zext(y)))
7319   // or
7320   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7321   // such that we're unnecessarily moving things into GPRs when it would be
7322   // better to keep them in CR bits.
7323
7324   // Note that trunc here can be an actual i1 trunc, or can be the effective
7325   // truncation that comes from a setcc or select_cc.
7326   if (N->getOpcode() == ISD::TRUNCATE &&
7327       N->getValueType(0) != MVT::i1)
7328     return SDValue();
7329
7330   if (N->getOperand(0).getValueType() != MVT::i32 &&
7331       N->getOperand(0).getValueType() != MVT::i64)
7332     return SDValue();
7333
7334   if (N->getOpcode() == ISD::SETCC ||
7335       N->getOpcode() == ISD::SELECT_CC) {
7336     // If we're looking at a comparison, then we need to make sure that the
7337     // high bits (all except for the first) don't matter the result.
7338     ISD::CondCode CC =
7339       cast<CondCodeSDNode>(N->getOperand(
7340         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7341     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7342
7343     if (ISD::isSignedIntSetCC(CC)) {
7344       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7345           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7346         return SDValue();
7347     } else if (ISD::isUnsignedIntSetCC(CC)) {
7348       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7349                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7350           !DAG.MaskedValueIsZero(N->getOperand(1),
7351                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7352         return SDValue();
7353     } else {
7354       // This is neither a signed nor an unsigned comparison, just make sure
7355       // that the high bits are equal.
7356       APInt Op1Zero, Op1One;
7357       APInt Op2Zero, Op2One;
7358       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7359       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7360
7361       // We don't really care about what is known about the first bit (if
7362       // anything), so clear it in all masks prior to comparing them.
7363       Op1Zero.clearBit(0); Op1One.clearBit(0);
7364       Op2Zero.clearBit(0); Op2One.clearBit(0);
7365
7366       if (Op1Zero != Op2Zero || Op1One != Op2One)
7367         return SDValue();
7368     }
7369   }
7370
7371   // We now know that the higher-order bits are irrelevant, we just need to
7372   // make sure that all of the intermediate operations are bit operations, and
7373   // all inputs are extensions.
7374   if (N->getOperand(0).getOpcode() != ISD::AND &&
7375       N->getOperand(0).getOpcode() != ISD::OR  &&
7376       N->getOperand(0).getOpcode() != ISD::XOR &&
7377       N->getOperand(0).getOpcode() != ISD::SELECT &&
7378       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7379       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7380       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7381       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7382       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7383     return SDValue();
7384
7385   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7386       N->getOperand(1).getOpcode() != ISD::AND &&
7387       N->getOperand(1).getOpcode() != ISD::OR  &&
7388       N->getOperand(1).getOpcode() != ISD::XOR &&
7389       N->getOperand(1).getOpcode() != ISD::SELECT &&
7390       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7391       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7392       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7393       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7394       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7395     return SDValue();
7396
7397   SmallVector<SDValue, 4> Inputs;
7398   SmallVector<SDValue, 8> BinOps, PromOps;
7399   SmallPtrSet<SDNode *, 16> Visited;
7400
7401   for (unsigned i = 0; i < 2; ++i) {
7402     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7403           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7404           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7405           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7406         isa<ConstantSDNode>(N->getOperand(i)))
7407       Inputs.push_back(N->getOperand(i));
7408     else
7409       BinOps.push_back(N->getOperand(i));
7410
7411     if (N->getOpcode() == ISD::TRUNCATE)
7412       break;
7413   }
7414
7415   // Visit all inputs, collect all binary operations (and, or, xor and
7416   // select) that are all fed by extensions. 
7417   while (!BinOps.empty()) {
7418     SDValue BinOp = BinOps.back();
7419     BinOps.pop_back();
7420
7421     if (!Visited.insert(BinOp.getNode()))
7422       continue;
7423
7424     PromOps.push_back(BinOp);
7425
7426     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7427       // The condition of the select is not promoted.
7428       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7429         continue;
7430       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7431         continue;
7432
7433       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7434             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7435             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7436            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7437           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7438         Inputs.push_back(BinOp.getOperand(i)); 
7439       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7440                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7441                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7442                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7443                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7444                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7445                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7446                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7447                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7448         BinOps.push_back(BinOp.getOperand(i));
7449       } else {
7450         // We have an input that is not an extension or another binary
7451         // operation; we'll abort this transformation.
7452         return SDValue();
7453       }
7454     }
7455   }
7456
7457   // Make sure that this is a self-contained cluster of operations (which
7458   // is not quite the same thing as saying that everything has only one
7459   // use).
7460   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7461     if (isa<ConstantSDNode>(Inputs[i]))
7462       continue;
7463
7464     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7465                               UE = Inputs[i].getNode()->use_end();
7466          UI != UE; ++UI) {
7467       SDNode *User = *UI;
7468       if (User != N && !Visited.count(User))
7469         return SDValue();
7470
7471       // Make sure that we're not going to promote the non-output-value
7472       // operand(s) or SELECT or SELECT_CC.
7473       // FIXME: Although we could sometimes handle this, and it does occur in
7474       // practice that one of the condition inputs to the select is also one of
7475       // the outputs, we currently can't deal with this.
7476       if (User->getOpcode() == ISD::SELECT) {
7477         if (User->getOperand(0) == Inputs[i])
7478           return SDValue();
7479       } else if (User->getOpcode() == ISD::SELECT_CC) {
7480         if (User->getOperand(0) == Inputs[i] ||
7481             User->getOperand(1) == Inputs[i])
7482           return SDValue();
7483       }
7484     }
7485   }
7486
7487   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7488     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7489                               UE = PromOps[i].getNode()->use_end();
7490          UI != UE; ++UI) {
7491       SDNode *User = *UI;
7492       if (User != N && !Visited.count(User))
7493         return SDValue();
7494
7495       // Make sure that we're not going to promote the non-output-value
7496       // operand(s) or SELECT or SELECT_CC.
7497       // FIXME: Although we could sometimes handle this, and it does occur in
7498       // practice that one of the condition inputs to the select is also one of
7499       // the outputs, we currently can't deal with this.
7500       if (User->getOpcode() == ISD::SELECT) {
7501         if (User->getOperand(0) == PromOps[i])
7502           return SDValue();
7503       } else if (User->getOpcode() == ISD::SELECT_CC) {
7504         if (User->getOperand(0) == PromOps[i] ||
7505             User->getOperand(1) == PromOps[i])
7506           return SDValue();
7507       }
7508     }
7509   }
7510
7511   // Replace all inputs with the extension operand.
7512   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7513     // Constants may have users outside the cluster of to-be-promoted nodes,
7514     // and so we need to replace those as we do the promotions.
7515     if (isa<ConstantSDNode>(Inputs[i]))
7516       continue;
7517     else
7518       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
7519   }
7520
7521   // Replace all operations (these are all the same, but have a different
7522   // (i1) return type). DAG.getNode will validate that the types of
7523   // a binary operator match, so go through the list in reverse so that
7524   // we've likely promoted both operands first. Any intermediate truncations or
7525   // extensions disappear.
7526   while (!PromOps.empty()) {
7527     SDValue PromOp = PromOps.back();
7528     PromOps.pop_back();
7529
7530     if (PromOp.getOpcode() == ISD::TRUNCATE ||
7531         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7532         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7533         PromOp.getOpcode() == ISD::ANY_EXTEND) {
7534       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7535           PromOp.getOperand(0).getValueType() != MVT::i1) {
7536         // The operand is not yet ready (see comment below).
7537         PromOps.insert(PromOps.begin(), PromOp);
7538         continue;
7539       }
7540
7541       SDValue RepValue = PromOp.getOperand(0);
7542       if (isa<ConstantSDNode>(RepValue))
7543         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7544
7545       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7546       continue;
7547     }
7548
7549     unsigned C;
7550     switch (PromOp.getOpcode()) {
7551     default:             C = 0; break;
7552     case ISD::SELECT:    C = 1; break;
7553     case ISD::SELECT_CC: C = 2; break;
7554     }
7555
7556     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7557          PromOp.getOperand(C).getValueType() != MVT::i1) ||
7558         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7559          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7560       // The to-be-promoted operands of this node have not yet been
7561       // promoted (this should be rare because we're going through the
7562       // list backward, but if one of the operands has several users in
7563       // this cluster of to-be-promoted nodes, it is possible).
7564       PromOps.insert(PromOps.begin(), PromOp);
7565       continue;
7566     }
7567
7568     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7569                                 PromOp.getNode()->op_end());
7570
7571     // If there are any constant inputs, make sure they're replaced now.
7572     for (unsigned i = 0; i < 2; ++i)
7573       if (isa<ConstantSDNode>(Ops[C+i]))
7574         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7575
7576     DAG.ReplaceAllUsesOfValueWith(PromOp,
7577       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7578   }
7579
7580   // Now we're left with the initial truncation itself.
7581   if (N->getOpcode() == ISD::TRUNCATE)
7582     return N->getOperand(0);
7583
7584   // Otherwise, this is a comparison. The operands to be compared have just
7585   // changed type (to i1), but everything else is the same.
7586   return SDValue(N, 0);
7587 }
7588
7589 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7590                                                   DAGCombinerInfo &DCI) const {
7591   SelectionDAG &DAG = DCI.DAG;
7592   SDLoc dl(N);
7593
7594   // If we're tracking CR bits, we need to be careful that we don't have:
7595   //   zext(binary-ops(trunc(x), trunc(y)))
7596   // or
7597   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7598   // such that we're unnecessarily moving things into CR bits that can more
7599   // efficiently stay in GPRs. Note that if we're not certain that the high
7600   // bits are set as required by the final extension, we still may need to do
7601   // some masking to get the proper behavior.
7602
7603   // This same functionality is important on PPC64 when dealing with
7604   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7605   // the return values of functions. Because it is so similar, it is handled
7606   // here as well.
7607
7608   if (N->getValueType(0) != MVT::i32 &&
7609       N->getValueType(0) != MVT::i64)
7610     return SDValue();
7611
7612   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7613         PPCSubTarget.useCRBits()) ||
7614        (N->getOperand(0).getValueType() == MVT::i32 &&
7615         PPCSubTarget.isPPC64())))
7616     return SDValue();
7617
7618   if (N->getOperand(0).getOpcode() != ISD::AND &&
7619       N->getOperand(0).getOpcode() != ISD::OR  &&
7620       N->getOperand(0).getOpcode() != ISD::XOR &&
7621       N->getOperand(0).getOpcode() != ISD::SELECT &&
7622       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7623     return SDValue();
7624
7625   SmallVector<SDValue, 4> Inputs;
7626   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7627   SmallPtrSet<SDNode *, 16> Visited;
7628
7629   // Visit all inputs, collect all binary operations (and, or, xor and
7630   // select) that are all fed by truncations. 
7631   while (!BinOps.empty()) {
7632     SDValue BinOp = BinOps.back();
7633     BinOps.pop_back();
7634
7635     if (!Visited.insert(BinOp.getNode()))
7636       continue;
7637
7638     PromOps.push_back(BinOp);
7639
7640     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7641       // The condition of the select is not promoted.
7642       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7643         continue;
7644       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7645         continue;
7646
7647       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7648           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7649         Inputs.push_back(BinOp.getOperand(i)); 
7650       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7651                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7652                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7653                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7654                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7655         BinOps.push_back(BinOp.getOperand(i));
7656       } else {
7657         // We have an input that is not a truncation or another binary
7658         // operation; we'll abort this transformation.
7659         return SDValue();
7660       }
7661     }
7662   }
7663
7664   // Make sure that this is a self-contained cluster of operations (which
7665   // is not quite the same thing as saying that everything has only one
7666   // use).
7667   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7668     if (isa<ConstantSDNode>(Inputs[i]))
7669       continue;
7670
7671     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7672                               UE = Inputs[i].getNode()->use_end();
7673          UI != UE; ++UI) {
7674       SDNode *User = *UI;
7675       if (User != N && !Visited.count(User))
7676         return SDValue();
7677
7678       // Make sure that we're not going to promote the non-output-value
7679       // operand(s) or SELECT or SELECT_CC.
7680       // FIXME: Although we could sometimes handle this, and it does occur in
7681       // practice that one of the condition inputs to the select is also one of
7682       // the outputs, we currently can't deal with this.
7683       if (User->getOpcode() == ISD::SELECT) {
7684         if (User->getOperand(0) == Inputs[i])
7685           return SDValue();
7686       } else if (User->getOpcode() == ISD::SELECT_CC) {
7687         if (User->getOperand(0) == Inputs[i] ||
7688             User->getOperand(1) == Inputs[i])
7689           return SDValue();
7690       }
7691     }
7692   }
7693
7694   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7695     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7696                               UE = PromOps[i].getNode()->use_end();
7697          UI != UE; ++UI) {
7698       SDNode *User = *UI;
7699       if (User != N && !Visited.count(User))
7700         return SDValue();
7701
7702       // Make sure that we're not going to promote the non-output-value
7703       // operand(s) or SELECT or SELECT_CC.
7704       // FIXME: Although we could sometimes handle this, and it does occur in
7705       // practice that one of the condition inputs to the select is also one of
7706       // the outputs, we currently can't deal with this.
7707       if (User->getOpcode() == ISD::SELECT) {
7708         if (User->getOperand(0) == PromOps[i])
7709           return SDValue();
7710       } else if (User->getOpcode() == ISD::SELECT_CC) {
7711         if (User->getOperand(0) == PromOps[i] ||
7712             User->getOperand(1) == PromOps[i])
7713           return SDValue();
7714       }
7715     }
7716   }
7717
7718   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7719   bool ReallyNeedsExt = false;
7720   if (N->getOpcode() != ISD::ANY_EXTEND) {
7721     // If all of the inputs are not already sign/zero extended, then
7722     // we'll still need to do that at the end.
7723     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7724       if (isa<ConstantSDNode>(Inputs[i]))
7725         continue;
7726
7727       unsigned OpBits =
7728         Inputs[i].getOperand(0).getValueSizeInBits();
7729       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7730
7731       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7732            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7733                                   APInt::getHighBitsSet(OpBits,
7734                                                         OpBits-PromBits))) ||
7735           (N->getOpcode() == ISD::SIGN_EXTEND &&
7736            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7737              (OpBits-(PromBits-1)))) {
7738         ReallyNeedsExt = true;
7739         break;
7740       }
7741     }
7742   }
7743
7744   // Replace all inputs, either with the truncation operand, or a
7745   // truncation or extension to the final output type.
7746   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7747     // Constant inputs need to be replaced with the to-be-promoted nodes that
7748     // use them because they might have users outside of the cluster of
7749     // promoted nodes.
7750     if (isa<ConstantSDNode>(Inputs[i]))
7751       continue;
7752
7753     SDValue InSrc = Inputs[i].getOperand(0);
7754     if (Inputs[i].getValueType() == N->getValueType(0))
7755       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7756     else if (N->getOpcode() == ISD::SIGN_EXTEND)
7757       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7758         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7759     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7760       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7761         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7762     else
7763       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7764         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7765   }
7766
7767   // Replace all operations (these are all the same, but have a different
7768   // (promoted) return type). DAG.getNode will validate that the types of
7769   // a binary operator match, so go through the list in reverse so that
7770   // we've likely promoted both operands first.
7771   while (!PromOps.empty()) {
7772     SDValue PromOp = PromOps.back();
7773     PromOps.pop_back();
7774
7775     unsigned C;
7776     switch (PromOp.getOpcode()) {
7777     default:             C = 0; break;
7778     case ISD::SELECT:    C = 1; break;
7779     case ISD::SELECT_CC: C = 2; break;
7780     }
7781
7782     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7783          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7784         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7785          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7786       // The to-be-promoted operands of this node have not yet been
7787       // promoted (this should be rare because we're going through the
7788       // list backward, but if one of the operands has several users in
7789       // this cluster of to-be-promoted nodes, it is possible).
7790       PromOps.insert(PromOps.begin(), PromOp);
7791       continue;
7792     }
7793
7794     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7795                                 PromOp.getNode()->op_end());
7796
7797     // If this node has constant inputs, then they'll need to be promoted here.
7798     for (unsigned i = 0; i < 2; ++i) {
7799       if (!isa<ConstantSDNode>(Ops[C+i]))
7800         continue;
7801       if (Ops[C+i].getValueType() == N->getValueType(0))
7802         continue;
7803
7804       if (N->getOpcode() == ISD::SIGN_EXTEND)
7805         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7806       else if (N->getOpcode() == ISD::ZERO_EXTEND)
7807         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7808       else
7809         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7810     }
7811
7812     DAG.ReplaceAllUsesOfValueWith(PromOp,
7813       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
7814   }
7815
7816   // Now we're left with the initial extension itself.
7817   if (!ReallyNeedsExt)
7818     return N->getOperand(0);
7819
7820   // To zero extend, just mask off everything except for the first bit (in the
7821   // i1 case).
7822   if (N->getOpcode() == ISD::ZERO_EXTEND)
7823     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7824                        DAG.getConstant(APInt::getLowBitsSet(
7825                                          N->getValueSizeInBits(0), PromBits),
7826                                        N->getValueType(0)));
7827
7828   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7829          "Invalid extension type");
7830   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7831   SDValue ShiftCst =
7832     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7833   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
7834                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7835                                  N->getOperand(0), ShiftCst), ShiftCst);
7836 }
7837
7838 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7839                                              DAGCombinerInfo &DCI) const {
7840   const TargetMachine &TM = getTargetMachine();
7841   SelectionDAG &DAG = DCI.DAG;
7842   SDLoc dl(N);
7843   switch (N->getOpcode()) {
7844   default: break;
7845   case PPCISD::SHL:
7846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7847       if (C->isNullValue())   // 0 << V -> 0.
7848         return N->getOperand(0);
7849     }
7850     break;
7851   case PPCISD::SRL:
7852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7853       if (C->isNullValue())   // 0 >>u V -> 0.
7854         return N->getOperand(0);
7855     }
7856     break;
7857   case PPCISD::SRA:
7858     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7859       if (C->isNullValue() ||   //  0 >>s V -> 0.
7860           C->isAllOnesValue())    // -1 >>s V -> -1.
7861         return N->getOperand(0);
7862     }
7863     break;
7864   case ISD::SIGN_EXTEND:
7865   case ISD::ZERO_EXTEND:
7866   case ISD::ANY_EXTEND: 
7867     return DAGCombineExtBoolTrunc(N, DCI);
7868   case ISD::TRUNCATE:
7869   case ISD::SETCC:
7870   case ISD::SELECT_CC:
7871     return DAGCombineTruncBoolExt(N, DCI);
7872   case ISD::FDIV: {
7873     assert(TM.Options.UnsafeFPMath &&
7874            "Reciprocal estimates require UnsafeFPMath");
7875
7876     if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7877       SDValue RV =
7878         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7879       if (RV.getNode()) {
7880         DCI.AddToWorklist(RV.getNode());
7881         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7882                            N->getOperand(0), RV);
7883       }
7884     } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7885                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7886       SDValue RV =
7887         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7888                                  DCI);
7889       if (RV.getNode()) {
7890         DCI.AddToWorklist(RV.getNode());
7891         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7892                          N->getValueType(0), RV);
7893         DCI.AddToWorklist(RV.getNode());
7894         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7895                            N->getOperand(0), RV);
7896       }
7897     } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7898                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7899       SDValue RV =
7900         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7901                                  DCI);
7902       if (RV.getNode()) {
7903         DCI.AddToWorklist(RV.getNode());
7904         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7905                          N->getValueType(0), RV,
7906                          N->getOperand(1).getOperand(1));
7907         DCI.AddToWorklist(RV.getNode());
7908         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7909                            N->getOperand(0), RV);
7910       }
7911     }
7912
7913     SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7914     if (RV.getNode()) {
7915       DCI.AddToWorklist(RV.getNode());
7916       return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7917                          N->getOperand(0), RV);
7918     }
7919
7920     }
7921     break;
7922   case ISD::FSQRT: {
7923     assert(TM.Options.UnsafeFPMath &&
7924            "Reciprocal estimates require UnsafeFPMath");
7925
7926     // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7927     // reciprocal sqrt.
7928     SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7929     if (RV.getNode()) {
7930       DCI.AddToWorklist(RV.getNode());
7931       RV = DAGCombineFastRecip(RV, DCI);
7932       if (RV.getNode()) {
7933         // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7934         // this case and force the answer to 0.
7935
7936         EVT VT = RV.getValueType();
7937
7938         SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7939         if (VT.isVector()) {
7940           assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7941           Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7942         }
7943
7944         SDValue ZeroCmp =
7945           DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7946                        N->getOperand(0), Zero, ISD::SETEQ);
7947         DCI.AddToWorklist(ZeroCmp.getNode());
7948         DCI.AddToWorklist(RV.getNode());
7949
7950         RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7951                          ZeroCmp, Zero, RV);
7952         return RV;
7953       }
7954     }
7955
7956     }
7957     break;
7958   case ISD::SINT_TO_FP:
7959     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7960       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7961         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7962         // We allow the src/dst to be either f32/f64, but the intermediate
7963         // type must be i64.
7964         if (N->getOperand(0).getValueType() == MVT::i64 &&
7965             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7966           SDValue Val = N->getOperand(0).getOperand(0);
7967           if (Val.getValueType() == MVT::f32) {
7968             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7969             DCI.AddToWorklist(Val.getNode());
7970           }
7971
7972           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7973           DCI.AddToWorklist(Val.getNode());
7974           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7975           DCI.AddToWorklist(Val.getNode());
7976           if (N->getValueType(0) == MVT::f32) {
7977             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7978                               DAG.getIntPtrConstant(0));
7979             DCI.AddToWorklist(Val.getNode());
7980           }
7981           return Val;
7982         } else if (N->getOperand(0).getValueType() == MVT::i32) {
7983           // If the intermediate type is i32, we can avoid the load/store here
7984           // too.
7985         }
7986       }
7987     }
7988     break;
7989   case ISD::STORE:
7990     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7991     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7992         !cast<StoreSDNode>(N)->isTruncatingStore() &&
7993         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7994         N->getOperand(1).getValueType() == MVT::i32 &&
7995         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7996       SDValue Val = N->getOperand(1).getOperand(0);
7997       if (Val.getValueType() == MVT::f32) {
7998         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7999         DCI.AddToWorklist(Val.getNode());
8000       }
8001       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8002       DCI.AddToWorklist(Val.getNode());
8003
8004       SDValue Ops[] = {
8005         N->getOperand(0), Val, N->getOperand(2),
8006         DAG.getValueType(N->getOperand(1).getValueType())
8007       };
8008
8009       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8010               DAG.getVTList(MVT::Other), Ops,
8011               cast<StoreSDNode>(N)->getMemoryVT(),
8012               cast<StoreSDNode>(N)->getMemOperand());
8013       DCI.AddToWorklist(Val.getNode());
8014       return Val;
8015     }
8016
8017     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8018     if (cast<StoreSDNode>(N)->isUnindexed() &&
8019         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8020         N->getOperand(1).getNode()->hasOneUse() &&
8021         (N->getOperand(1).getValueType() == MVT::i32 ||
8022          N->getOperand(1).getValueType() == MVT::i16 ||
8023          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8024           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8025           N->getOperand(1).getValueType() == MVT::i64))) {
8026       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8027       // Do an any-extend to 32-bits if this is a half-word input.
8028       if (BSwapOp.getValueType() == MVT::i16)
8029         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8030
8031       SDValue Ops[] = {
8032         N->getOperand(0), BSwapOp, N->getOperand(2),
8033         DAG.getValueType(N->getOperand(1).getValueType())
8034       };
8035       return
8036         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8037                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8038                                 cast<StoreSDNode>(N)->getMemOperand());
8039     }
8040     break;
8041   case ISD::LOAD: {
8042     LoadSDNode *LD = cast<LoadSDNode>(N);
8043     EVT VT = LD->getValueType(0);
8044     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8045     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8046     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8047         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8048         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8049          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8050         LD->getAlignment() < ABIAlignment) {
8051       // This is a type-legal unaligned Altivec load.
8052       SDValue Chain = LD->getChain();
8053       SDValue Ptr = LD->getBasePtr();
8054
8055       // This implements the loading of unaligned vectors as described in
8056       // the venerable Apple Velocity Engine overview. Specifically:
8057       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8058       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8059       //
8060       // The general idea is to expand a sequence of one or more unaligned
8061       // loads into a alignment-based permutation-control instruction (lvsl),
8062       // a series of regular vector loads (which always truncate their
8063       // input address to an aligned address), and a series of permutations.
8064       // The results of these permutations are the requested loaded values.
8065       // The trick is that the last "extra" load is not taken from the address
8066       // you might suspect (sizeof(vector) bytes after the last requested
8067       // load), but rather sizeof(vector) - 1 bytes after the last
8068       // requested vector. The point of this is to avoid a page fault if the
8069       // base address happened to be aligned. This works because if the base
8070       // address is aligned, then adding less than a full vector length will
8071       // cause the last vector in the sequence to be (re)loaded. Otherwise,
8072       // the next vector will be fetched as you might suspect was necessary.
8073
8074       // We might be able to reuse the permutation generation from
8075       // a different base address offset from this one by an aligned amount.
8076       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8077       // optimization later.
8078       SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8079                                           DAG, dl, MVT::v16i8);
8080
8081       // Refine the alignment of the original load (a "new" load created here
8082       // which was identical to the first except for the alignment would be
8083       // merged with the existing node regardless).
8084       MachineFunction &MF = DAG.getMachineFunction();
8085       MachineMemOperand *MMO =
8086         MF.getMachineMemOperand(LD->getPointerInfo(),
8087                                 LD->getMemOperand()->getFlags(),
8088                                 LD->getMemoryVT().getStoreSize(),
8089                                 ABIAlignment);
8090       LD->refineAlignment(MMO);
8091       SDValue BaseLoad = SDValue(LD, 0);
8092
8093       // Note that the value of IncOffset (which is provided to the next
8094       // load's pointer info offset value, and thus used to calculate the
8095       // alignment), and the value of IncValue (which is actually used to
8096       // increment the pointer value) are different! This is because we
8097       // require the next load to appear to be aligned, even though it
8098       // is actually offset from the base pointer by a lesser amount.
8099       int IncOffset = VT.getSizeInBits() / 8;
8100       int IncValue = IncOffset;
8101
8102       // Walk (both up and down) the chain looking for another load at the real
8103       // (aligned) offset (the alignment of the other load does not matter in
8104       // this case). If found, then do not use the offset reduction trick, as
8105       // that will prevent the loads from being later combined (as they would
8106       // otherwise be duplicates).
8107       if (!findConsecutiveLoad(LD, DAG))
8108         --IncValue;
8109
8110       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8111       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8112
8113       SDValue ExtraLoad =
8114         DAG.getLoad(VT, dl, Chain, Ptr,
8115                     LD->getPointerInfo().getWithOffset(IncOffset),
8116                     LD->isVolatile(), LD->isNonTemporal(),
8117                     LD->isInvariant(), ABIAlignment);
8118
8119       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8120         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8121
8122       if (BaseLoad.getValueType() != MVT::v4i32)
8123         BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8124
8125       if (ExtraLoad.getValueType() != MVT::v4i32)
8126         ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8127
8128       SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8129                                       BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8130
8131       if (VT != MVT::v4i32)
8132         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8133
8134       // Now we need to be really careful about how we update the users of the
8135       // original load. We cannot just call DCI.CombineTo (or
8136       // DAG.ReplaceAllUsesWith for that matter), because the load still has
8137       // uses created here (the permutation for example) that need to stay.
8138       SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8139       while (UI != UE) {
8140         SDUse &Use = UI.getUse();
8141         SDNode *User = *UI;
8142         // Note: BaseLoad is checked here because it might not be N, but a
8143         // bitcast of N.
8144         if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8145             User == TF.getNode() || Use.getResNo() > 1) {
8146           ++UI;
8147           continue;
8148         }
8149
8150         SDValue To = Use.getResNo() ? TF : Perm;
8151         ++UI;
8152
8153         SmallVector<SDValue, 8> Ops;
8154         for (SDNode::op_iterator O = User->op_begin(),
8155              OE = User->op_end(); O != OE; ++O) {
8156           if (*O == Use)
8157             Ops.push_back(To);
8158           else
8159             Ops.push_back(*O);
8160         }
8161
8162         DAG.UpdateNodeOperands(User, Ops);
8163       }
8164
8165       return SDValue(N, 0);
8166     }
8167     }
8168     break;
8169   case ISD::INTRINSIC_WO_CHAIN:
8170     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8171           Intrinsic::ppc_altivec_lvsl &&
8172         N->getOperand(1)->getOpcode() == ISD::ADD) {
8173       SDValue Add = N->getOperand(1);
8174
8175       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8176             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8177               Add.getValueType().getScalarType().getSizeInBits()))) {
8178         SDNode *BasePtr = Add->getOperand(0).getNode();
8179         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8180              UE = BasePtr->use_end(); UI != UE; ++UI) {
8181           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8182               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8183                 Intrinsic::ppc_altivec_lvsl) {
8184             // We've found another LVSL, and this address if an aligned
8185             // multiple of that one. The results will be the same, so use the
8186             // one we've just found instead.
8187
8188             return SDValue(*UI, 0);
8189           }
8190         }
8191       }
8192     }
8193
8194     break;
8195   case ISD::BSWAP:
8196     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8197     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8198         N->getOperand(0).hasOneUse() &&
8199         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8200          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8201           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8202           N->getValueType(0) == MVT::i64))) {
8203       SDValue Load = N->getOperand(0);
8204       LoadSDNode *LD = cast<LoadSDNode>(Load);
8205       // Create the byte-swapping load.
8206       SDValue Ops[] = {
8207         LD->getChain(),    // Chain
8208         LD->getBasePtr(),  // Ptr
8209         DAG.getValueType(N->getValueType(0)) // VT
8210       };
8211       SDValue BSLoad =
8212         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8213                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8214                                               MVT::i64 : MVT::i32, MVT::Other),
8215                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8216
8217       // If this is an i16 load, insert the truncate.
8218       SDValue ResVal = BSLoad;
8219       if (N->getValueType(0) == MVT::i16)
8220         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8221
8222       // First, combine the bswap away.  This makes the value produced by the
8223       // load dead.
8224       DCI.CombineTo(N, ResVal);
8225
8226       // Next, combine the load away, we give it a bogus result value but a real
8227       // chain result.  The result value is dead because the bswap is dead.
8228       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8229
8230       // Return N so it doesn't get rechecked!
8231       return SDValue(N, 0);
8232     }
8233
8234     break;
8235   case PPCISD::VCMP: {
8236     // If a VCMPo node already exists with exactly the same operands as this
8237     // node, use its result instead of this node (VCMPo computes both a CR6 and
8238     // a normal output).
8239     //
8240     if (!N->getOperand(0).hasOneUse() &&
8241         !N->getOperand(1).hasOneUse() &&
8242         !N->getOperand(2).hasOneUse()) {
8243
8244       // Scan all of the users of the LHS, looking for VCMPo's that match.
8245       SDNode *VCMPoNode = nullptr;
8246
8247       SDNode *LHSN = N->getOperand(0).getNode();
8248       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8249            UI != E; ++UI)
8250         if (UI->getOpcode() == PPCISD::VCMPo &&
8251             UI->getOperand(1) == N->getOperand(1) &&
8252             UI->getOperand(2) == N->getOperand(2) &&
8253             UI->getOperand(0) == N->getOperand(0)) {
8254           VCMPoNode = *UI;
8255           break;
8256         }
8257
8258       // If there is no VCMPo node, or if the flag value has a single use, don't
8259       // transform this.
8260       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8261         break;
8262
8263       // Look at the (necessarily single) use of the flag value.  If it has a
8264       // chain, this transformation is more complex.  Note that multiple things
8265       // could use the value result, which we should ignore.
8266       SDNode *FlagUser = nullptr;
8267       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8268            FlagUser == nullptr; ++UI) {
8269         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8270         SDNode *User = *UI;
8271         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8272           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8273             FlagUser = User;
8274             break;
8275           }
8276         }
8277       }
8278
8279       // If the user is a MFOCRF instruction, we know this is safe.
8280       // Otherwise we give up for right now.
8281       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8282         return SDValue(VCMPoNode, 0);
8283     }
8284     break;
8285   }
8286   case ISD::BRCOND: {
8287     SDValue Cond = N->getOperand(1);
8288     SDValue Target = N->getOperand(2);
8289  
8290     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8291         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8292           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8293
8294       // We now need to make the intrinsic dead (it cannot be instruction
8295       // selected).
8296       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8297       assert(Cond.getNode()->hasOneUse() &&
8298              "Counter decrement has more than one use");
8299
8300       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8301                          N->getOperand(0), Target);
8302     }
8303   }
8304   break;
8305   case ISD::BR_CC: {
8306     // If this is a branch on an altivec predicate comparison, lower this so
8307     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8308     // lowering is done pre-legalize, because the legalizer lowers the predicate
8309     // compare down to code that is difficult to reassemble.
8310     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8311     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8312
8313     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8314     // value. If so, pass-through the AND to get to the intrinsic.
8315     if (LHS.getOpcode() == ISD::AND &&
8316         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8317         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8318           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8319         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8320         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8321           isZero())
8322       LHS = LHS.getOperand(0);
8323
8324     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8325         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8326           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8327         isa<ConstantSDNode>(RHS)) {
8328       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8329              "Counter decrement comparison is not EQ or NE");
8330
8331       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8332       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8333                     (CC == ISD::SETNE && !Val);
8334
8335       // We now need to make the intrinsic dead (it cannot be instruction
8336       // selected).
8337       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8338       assert(LHS.getNode()->hasOneUse() &&
8339              "Counter decrement has more than one use");
8340
8341       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8342                          N->getOperand(0), N->getOperand(4));
8343     }
8344
8345     int CompareOpc;
8346     bool isDot;
8347
8348     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8349         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8350         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8351       assert(isDot && "Can't compare against a vector result!");
8352
8353       // If this is a comparison against something other than 0/1, then we know
8354       // that the condition is never/always true.
8355       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8356       if (Val != 0 && Val != 1) {
8357         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8358           return N->getOperand(0);
8359         // Always !=, turn it into an unconditional branch.
8360         return DAG.getNode(ISD::BR, dl, MVT::Other,
8361                            N->getOperand(0), N->getOperand(4));
8362       }
8363
8364       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8365
8366       // Create the PPCISD altivec 'dot' comparison node.
8367       SDValue Ops[] = {
8368         LHS.getOperand(2),  // LHS of compare
8369         LHS.getOperand(3),  // RHS of compare
8370         DAG.getConstant(CompareOpc, MVT::i32)
8371       };
8372       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8373       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8374
8375       // Unpack the result based on how the target uses it.
8376       PPC::Predicate CompOpc;
8377       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8378       default:  // Can't happen, don't crash on invalid number though.
8379       case 0:   // Branch on the value of the EQ bit of CR6.
8380         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8381         break;
8382       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8383         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8384         break;
8385       case 2:   // Branch on the value of the LT bit of CR6.
8386         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8387         break;
8388       case 3:   // Branch on the inverted value of the LT bit of CR6.
8389         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8390         break;
8391       }
8392
8393       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8394                          DAG.getConstant(CompOpc, MVT::i32),
8395                          DAG.getRegister(PPC::CR6, MVT::i32),
8396                          N->getOperand(4), CompNode.getValue(1));
8397     }
8398     break;
8399   }
8400   }
8401
8402   return SDValue();
8403 }
8404
8405 //===----------------------------------------------------------------------===//
8406 // Inline Assembly Support
8407 //===----------------------------------------------------------------------===//
8408
8409 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8410                                                       APInt &KnownZero,
8411                                                       APInt &KnownOne,
8412                                                       const SelectionDAG &DAG,
8413                                                       unsigned Depth) const {
8414   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8415   switch (Op.getOpcode()) {
8416   default: break;
8417   case PPCISD::LBRX: {
8418     // lhbrx is known to have the top bits cleared out.
8419     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8420       KnownZero = 0xFFFF0000;
8421     break;
8422   }
8423   case ISD::INTRINSIC_WO_CHAIN: {
8424     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8425     default: break;
8426     case Intrinsic::ppc_altivec_vcmpbfp_p:
8427     case Intrinsic::ppc_altivec_vcmpeqfp_p:
8428     case Intrinsic::ppc_altivec_vcmpequb_p:
8429     case Intrinsic::ppc_altivec_vcmpequh_p:
8430     case Intrinsic::ppc_altivec_vcmpequw_p:
8431     case Intrinsic::ppc_altivec_vcmpgefp_p:
8432     case Intrinsic::ppc_altivec_vcmpgtfp_p:
8433     case Intrinsic::ppc_altivec_vcmpgtsb_p:
8434     case Intrinsic::ppc_altivec_vcmpgtsh_p:
8435     case Intrinsic::ppc_altivec_vcmpgtsw_p:
8436     case Intrinsic::ppc_altivec_vcmpgtub_p:
8437     case Intrinsic::ppc_altivec_vcmpgtuh_p:
8438     case Intrinsic::ppc_altivec_vcmpgtuw_p:
8439       KnownZero = ~1U;  // All bits but the low one are known to be zero.
8440       break;
8441     }
8442   }
8443   }
8444 }
8445
8446
8447 /// getConstraintType - Given a constraint, return the type of
8448 /// constraint it is for this target.
8449 PPCTargetLowering::ConstraintType
8450 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8451   if (Constraint.size() == 1) {
8452     switch (Constraint[0]) {
8453     default: break;
8454     case 'b':
8455     case 'r':
8456     case 'f':
8457     case 'v':
8458     case 'y':
8459       return C_RegisterClass;
8460     case 'Z':
8461       // FIXME: While Z does indicate a memory constraint, it specifically
8462       // indicates an r+r address (used in conjunction with the 'y' modifier
8463       // in the replacement string). Currently, we're forcing the base
8464       // register to be r0 in the asm printer (which is interpreted as zero)
8465       // and forming the complete address in the second register. This is
8466       // suboptimal.
8467       return C_Memory;
8468     }
8469   } else if (Constraint == "wc") { // individual CR bits.
8470     return C_RegisterClass;
8471   } else if (Constraint == "wa" || Constraint == "wd" ||
8472              Constraint == "wf" || Constraint == "ws") {
8473     return C_RegisterClass; // VSX registers.
8474   }
8475   return TargetLowering::getConstraintType(Constraint);
8476 }
8477
8478 /// Examine constraint type and operand type and determine a weight value.
8479 /// This object must already have been set up with the operand type
8480 /// and the current alternative constraint selected.
8481 TargetLowering::ConstraintWeight
8482 PPCTargetLowering::getSingleConstraintMatchWeight(
8483     AsmOperandInfo &info, const char *constraint) const {
8484   ConstraintWeight weight = CW_Invalid;
8485   Value *CallOperandVal = info.CallOperandVal;
8486     // If we don't have a value, we can't do a match,
8487     // but allow it at the lowest weight.
8488   if (!CallOperandVal)
8489     return CW_Default;
8490   Type *type = CallOperandVal->getType();
8491
8492   // Look at the constraint type.
8493   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8494     return CW_Register; // an individual CR bit.
8495   else if ((StringRef(constraint) == "wa" ||
8496             StringRef(constraint) == "wd" ||
8497             StringRef(constraint) == "wf") &&
8498            type->isVectorTy())
8499     return CW_Register;
8500   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8501     return CW_Register;
8502
8503   switch (*constraint) {
8504   default:
8505     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8506     break;
8507   case 'b':
8508     if (type->isIntegerTy())
8509       weight = CW_Register;
8510     break;
8511   case 'f':
8512     if (type->isFloatTy())
8513       weight = CW_Register;
8514     break;
8515   case 'd':
8516     if (type->isDoubleTy())
8517       weight = CW_Register;
8518     break;
8519   case 'v':
8520     if (type->isVectorTy())
8521       weight = CW_Register;
8522     break;
8523   case 'y':
8524     weight = CW_Register;
8525     break;
8526   case 'Z':
8527     weight = CW_Memory;
8528     break;
8529   }
8530   return weight;
8531 }
8532
8533 std::pair<unsigned, const TargetRegisterClass*>
8534 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8535                                                 MVT VT) const {
8536   if (Constraint.size() == 1) {
8537     // GCC RS6000 Constraint Letters
8538     switch (Constraint[0]) {
8539     case 'b':   // R1-R31
8540       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8541         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8542       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8543     case 'r':   // R0-R31
8544       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8545         return std::make_pair(0U, &PPC::G8RCRegClass);
8546       return std::make_pair(0U, &PPC::GPRCRegClass);
8547     case 'f':
8548       if (VT == MVT::f32 || VT == MVT::i32)
8549         return std::make_pair(0U, &PPC::F4RCRegClass);
8550       if (VT == MVT::f64 || VT == MVT::i64)
8551         return std::make_pair(0U, &PPC::F8RCRegClass);
8552       break;
8553     case 'v':
8554       return std::make_pair(0U, &PPC::VRRCRegClass);
8555     case 'y':   // crrc
8556       return std::make_pair(0U, &PPC::CRRCRegClass);
8557     }
8558   } else if (Constraint == "wc") { // an individual CR bit.
8559     return std::make_pair(0U, &PPC::CRBITRCRegClass);
8560   } else if (Constraint == "wa" || Constraint == "wd" ||
8561              Constraint == "wf") {
8562     return std::make_pair(0U, &PPC::VSRCRegClass);
8563   } else if (Constraint == "ws") {
8564     return std::make_pair(0U, &PPC::VSFRCRegClass);
8565   }
8566
8567   std::pair<unsigned, const TargetRegisterClass*> R =
8568     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8569
8570   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8571   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8572   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8573   // register.
8574   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8575   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8576   if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8577       PPC::GPRCRegClass.contains(R.first)) {
8578     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8579     return std::make_pair(TRI->getMatchingSuperReg(R.first,
8580                             PPC::sub_32, &PPC::G8RCRegClass),
8581                           &PPC::G8RCRegClass);
8582   }
8583
8584   return R;
8585 }
8586
8587
8588 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8589 /// vector.  If it is invalid, don't add anything to Ops.
8590 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8591                                                      std::string &Constraint,
8592                                                      std::vector<SDValue>&Ops,
8593                                                      SelectionDAG &DAG) const {
8594   SDValue Result;
8595
8596   // Only support length 1 constraints.
8597   if (Constraint.length() > 1) return;
8598
8599   char Letter = Constraint[0];
8600   switch (Letter) {
8601   default: break;
8602   case 'I':
8603   case 'J':
8604   case 'K':
8605   case 'L':
8606   case 'M':
8607   case 'N':
8608   case 'O':
8609   case 'P': {
8610     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8611     if (!CST) return; // Must be an immediate to match.
8612     unsigned Value = CST->getZExtValue();
8613     switch (Letter) {
8614     default: llvm_unreachable("Unknown constraint letter!");
8615     case 'I':  // "I" is a signed 16-bit constant.
8616       if ((short)Value == (int)Value)
8617         Result = DAG.getTargetConstant(Value, Op.getValueType());
8618       break;
8619     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
8620     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
8621       if ((short)Value == 0)
8622         Result = DAG.getTargetConstant(Value, Op.getValueType());
8623       break;
8624     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
8625       if ((Value >> 16) == 0)
8626         Result = DAG.getTargetConstant(Value, Op.getValueType());
8627       break;
8628     case 'M':  // "M" is a constant that is greater than 31.
8629       if (Value > 31)
8630         Result = DAG.getTargetConstant(Value, Op.getValueType());
8631       break;
8632     case 'N':  // "N" is a positive constant that is an exact power of two.
8633       if ((int)Value > 0 && isPowerOf2_32(Value))
8634         Result = DAG.getTargetConstant(Value, Op.getValueType());
8635       break;
8636     case 'O':  // "O" is the constant zero.
8637       if (Value == 0)
8638         Result = DAG.getTargetConstant(Value, Op.getValueType());
8639       break;
8640     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
8641       if ((short)-Value == (int)-Value)
8642         Result = DAG.getTargetConstant(Value, Op.getValueType());
8643       break;
8644     }
8645     break;
8646   }
8647   }
8648
8649   if (Result.getNode()) {
8650     Ops.push_back(Result);
8651     return;
8652   }
8653
8654   // Handle standard constraint letters.
8655   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8656 }
8657
8658 // isLegalAddressingMode - Return true if the addressing mode represented
8659 // by AM is legal for this target, for a load/store of the specified type.
8660 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8661                                               Type *Ty) const {
8662   // FIXME: PPC does not allow r+i addressing modes for vectors!
8663
8664   // PPC allows a sign-extended 16-bit immediate field.
8665   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8666     return false;
8667
8668   // No global is ever allowed as a base.
8669   if (AM.BaseGV)
8670     return false;
8671
8672   // PPC only support r+r,
8673   switch (AM.Scale) {
8674   case 0:  // "r+i" or just "i", depending on HasBaseReg.
8675     break;
8676   case 1:
8677     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
8678       return false;
8679     // Otherwise we have r+r or r+i.
8680     break;
8681   case 2:
8682     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
8683       return false;
8684     // Allow 2*r as r+r.
8685     break;
8686   default:
8687     // No other scales are supported.
8688     return false;
8689   }
8690
8691   return true;
8692 }
8693
8694 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8695                                            SelectionDAG &DAG) const {
8696   MachineFunction &MF = DAG.getMachineFunction();
8697   MachineFrameInfo *MFI = MF.getFrameInfo();
8698   MFI->setReturnAddressIsTaken(true);
8699
8700   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8701     return SDValue();
8702
8703   SDLoc dl(Op);
8704   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8705
8706   // Make sure the function does not optimize away the store of the RA to
8707   // the stack.
8708   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8709   FuncInfo->setLRStoreRequired();
8710   bool isPPC64 = PPCSubTarget.isPPC64();
8711   bool isDarwinABI = PPCSubTarget.isDarwinABI();
8712
8713   if (Depth > 0) {
8714     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8715     SDValue Offset =
8716
8717       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8718                       isPPC64? MVT::i64 : MVT::i32);
8719     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8720                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8721                                    FrameAddr, Offset),
8722                        MachinePointerInfo(), false, false, false, 0);
8723   }
8724
8725   // Just load the return address off the stack.
8726   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8727   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8728                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8729 }
8730
8731 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8732                                           SelectionDAG &DAG) const {
8733   SDLoc dl(Op);
8734   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8735
8736   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8737   bool isPPC64 = PtrVT == MVT::i64;
8738
8739   MachineFunction &MF = DAG.getMachineFunction();
8740   MachineFrameInfo *MFI = MF.getFrameInfo();
8741   MFI->setFrameAddressIsTaken(true);
8742
8743   // Naked functions never have a frame pointer, and so we use r1. For all
8744   // other functions, this decision must be delayed until during PEI.
8745   unsigned FrameReg;
8746   if (MF.getFunction()->getAttributes().hasAttribute(
8747         AttributeSet::FunctionIndex, Attribute::Naked))
8748     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8749   else
8750     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8751
8752   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8753                                          PtrVT);
8754   while (Depth--)
8755     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8756                             FrameAddr, MachinePointerInfo(), false, false,
8757                             false, 0);
8758   return FrameAddr;
8759 }
8760
8761 // FIXME? Maybe this could be a TableGen attribute on some registers and
8762 // this table could be generated automatically from RegInfo.
8763 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
8764                                               EVT VT) const {
8765   bool isPPC64 = PPCSubTarget.isPPC64();
8766   bool isDarwinABI = PPCSubTarget.isDarwinABI();
8767
8768   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
8769       (!isPPC64 && VT != MVT::i32))
8770     report_fatal_error("Invalid register global variable type");
8771
8772   bool is64Bit = isPPC64 && VT == MVT::i64;
8773   unsigned Reg = StringSwitch<unsigned>(RegName)
8774                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
8775                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
8776                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
8777                                   (is64Bit ? PPC::X13 : PPC::R13))
8778                    .Default(0);
8779
8780   if (Reg)
8781     return Reg;
8782   report_fatal_error("Invalid register name global variable");
8783 }
8784
8785 bool
8786 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8787   // The PowerPC target isn't yet aware of offsets.
8788   return false;
8789 }
8790
8791 /// getOptimalMemOpType - Returns the target specific optimal type for load
8792 /// and store operations as a result of memset, memcpy, and memmove
8793 /// lowering. If DstAlign is zero that means it's safe to destination
8794 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8795 /// means there isn't a need to check it against alignment requirement,
8796 /// probably because the source does not need to be loaded. If 'IsMemset' is
8797 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8798 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8799 /// source is constant so it does not need to be loaded.
8800 /// It returns EVT::Other if the type should be determined using generic
8801 /// target-independent logic.
8802 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8803                                            unsigned DstAlign, unsigned SrcAlign,
8804                                            bool IsMemset, bool ZeroMemset,
8805                                            bool MemcpyStrSrc,
8806                                            MachineFunction &MF) const {
8807   if (this->PPCSubTarget.isPPC64()) {
8808     return MVT::i64;
8809   } else {
8810     return MVT::i32;
8811   }
8812 }
8813
8814 /// \brief Returns true if it is beneficial to convert a load of a constant
8815 /// to just the constant itself.
8816 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8817                                                           Type *Ty) const {
8818   assert(Ty->isIntegerTy());
8819
8820   unsigned BitSize = Ty->getPrimitiveSizeInBits();
8821   if (BitSize == 0 || BitSize > 64)
8822     return false;
8823   return true;
8824 }
8825
8826 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8827   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8828     return false;
8829   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8830   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8831   return NumBits1 == 64 && NumBits2 == 32;
8832 }
8833
8834 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8835   if (!VT1.isInteger() || !VT2.isInteger())
8836     return false;
8837   unsigned NumBits1 = VT1.getSizeInBits();
8838   unsigned NumBits2 = VT2.getSizeInBits();
8839   return NumBits1 == 64 && NumBits2 == 32;
8840 }
8841
8842 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8843   return isInt<16>(Imm) || isUInt<16>(Imm);
8844 }
8845
8846 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8847   return isInt<16>(Imm) || isUInt<16>(Imm);
8848 }
8849
8850 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8851                                                       unsigned,
8852                                                       bool *Fast) const {
8853   if (DisablePPCUnaligned)
8854     return false;
8855
8856   // PowerPC supports unaligned memory access for simple non-vector types.
8857   // Although accessing unaligned addresses is not as efficient as accessing
8858   // aligned addresses, it is generally more efficient than manual expansion,
8859   // and generally only traps for software emulation when crossing page
8860   // boundaries.
8861
8862   if (!VT.isSimple())
8863     return false;
8864
8865   if (VT.getSimpleVT().isVector()) {
8866     if (PPCSubTarget.hasVSX()) {
8867       if (VT != MVT::v2f64 && VT != MVT::v2i64)
8868         return false;
8869     } else {
8870       return false;
8871     }
8872   }
8873
8874   if (VT == MVT::ppcf128)
8875     return false;
8876
8877   if (Fast)
8878     *Fast = true;
8879
8880   return true;
8881 }
8882
8883 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8884   VT = VT.getScalarType();
8885
8886   if (!VT.isSimple())
8887     return false;
8888
8889   switch (VT.getSimpleVT().SimpleTy) {
8890   case MVT::f32:
8891   case MVT::f64:
8892     return true;
8893   default:
8894     break;
8895   }
8896
8897   return false;
8898 }
8899
8900 bool
8901 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
8902                      EVT VT , unsigned DefinedValues) const {
8903   if (VT == MVT::v2i64)
8904     return false;
8905
8906   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
8907 }
8908
8909 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8910   if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8911     return TargetLowering::getSchedulingPreference(N);
8912
8913   return Sched::ILP;
8914 }
8915
8916 // Create a fast isel object.
8917 FastISel *
8918 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8919                                   const TargetLibraryInfo *LibInfo) const {
8920   return PPC::createFastISel(FuncInfo, LibInfo);
8921 }