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