]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303291, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCallingConv.h"
17 #include "PPCCCState.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCISelLowering.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/RuntimeLibcalls.h"
52 #include "llvm/CodeGen/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/CallSite.h"
57 #include "llvm/IR/Constant.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalValue.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Module.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/MC/MCExpr.h"
72 #include "llvm/MC/MCRegisterInfo.h"
73 #include "llvm/Support/AtomicOrdering.h"
74 #include "llvm/Support/BranchProbability.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/CodeGen.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/Format.h"
82 #include "llvm/Support/KnownBits.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetInstrInfo.h"
86 #include "llvm/Target/TargetLowering.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include "llvm/Target/TargetRegisterInfo.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97
98 using namespace llvm;
99
100 #define DEBUG_TYPE "ppc-lowering"
101
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumSiblingCalls, "Number of sibling calls");
116
117 // FIXME: Remove this once the bug has been fixed!
118 extern cl::opt<bool> ANDIGlueBug;
119
120 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
121                                      const PPCSubtarget &STI)
122     : TargetLowering(TM), Subtarget(STI) {
123   // Use _setjmp/_longjmp instead of setjmp/longjmp.
124   setUseUnderscoreSetJmp(true);
125   setUseUnderscoreLongJmp(true);
126
127   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
128   // arguments are at least 4/8 bytes aligned.
129   bool isPPC64 = Subtarget.isPPC64();
130   setMinStackArgumentAlignment(isPPC64 ? 8:4);
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
134   if (!useSoftFloat()) {
135     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
136     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
137   }
138
139   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
140   for (MVT VT : MVT::integer_valuetypes()) {
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
143   }
144
145   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
146
147   // PowerPC has pre-inc load and store's.
148   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
149   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
150   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
151   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
152   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
153   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
154   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
155   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
156   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
157   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
158   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
159   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
160   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
161   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
162
163   if (Subtarget.useCRBits()) {
164     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
165
166     if (isPPC64 || Subtarget.hasFPCVT()) {
167       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
168       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
169                          isPPC64 ? MVT::i64 : MVT::i32);
170       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
171       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
172                         isPPC64 ? MVT::i64 : MVT::i32);
173     } else {
174       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
175       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
176     }
177
178     // PowerPC does not support direct load / store of condition registers
179     setOperationAction(ISD::LOAD, MVT::i1, Custom);
180     setOperationAction(ISD::STORE, MVT::i1, Custom);
181
182     // FIXME: Remove this once the ANDI glue bug is fixed:
183     if (ANDIGlueBug)
184       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
185
186     for (MVT VT : MVT::integer_valuetypes()) {
187       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
188       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
189       setTruncStoreAction(VT, MVT::i1, Expand);
190     }
191
192     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
193   }
194
195   // This is used in the ppcf128->int sequence.  Note it has different semantics
196   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
197   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
198
199   // We do not currently implement these libm ops for PowerPC.
200   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
201   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
202   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
203   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
204   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
205   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
206
207   // PowerPC has no SREM/UREM instructions
208   setOperationAction(ISD::SREM, MVT::i32, Expand);
209   setOperationAction(ISD::UREM, MVT::i32, Expand);
210   setOperationAction(ISD::SREM, MVT::i64, Expand);
211   setOperationAction(ISD::UREM, MVT::i64, Expand);
212
213   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
214   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
215   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
216   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
217   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
218   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
219   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
220   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
221   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
222
223   // We don't support sin/cos/sqrt/fmod/pow
224   setOperationAction(ISD::FSIN , MVT::f64, Expand);
225   setOperationAction(ISD::FCOS , MVT::f64, Expand);
226   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
227   setOperationAction(ISD::FREM , MVT::f64, Expand);
228   setOperationAction(ISD::FPOW , MVT::f64, Expand);
229   setOperationAction(ISD::FMA  , MVT::f64, Legal);
230   setOperationAction(ISD::FSIN , MVT::f32, Expand);
231   setOperationAction(ISD::FCOS , MVT::f32, Expand);
232   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
233   setOperationAction(ISD::FREM , MVT::f32, Expand);
234   setOperationAction(ISD::FPOW , MVT::f32, Expand);
235   setOperationAction(ISD::FMA  , MVT::f32, Legal);
236
237   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
238
239   // If we're enabling GP optimizations, use hardware square root
240   if (!Subtarget.hasFSQRT() &&
241       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
242         Subtarget.hasFRE()))
243     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
244
245   if (!Subtarget.hasFSQRT() &&
246       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
247         Subtarget.hasFRES()))
248     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
249
250   if (Subtarget.hasFCPSGN()) {
251     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
252     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
253   } else {
254     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
255     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
256   }
257
258   if (Subtarget.hasFPRND()) {
259     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
260     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
261     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
262     setOperationAction(ISD::FROUND, MVT::f64, Legal);
263
264     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
265     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
266     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
267     setOperationAction(ISD::FROUND, MVT::f32, Legal);
268   }
269
270   // PowerPC does not have BSWAP
271   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
272   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
273   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
274   if (Subtarget.isISA3_0()) {
275     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
276     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
277   } else {
278     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
279     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
280   }
281
282   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
283     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
284     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
285   } else {
286     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
287     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
288   }
289
290   // PowerPC does not have ROTR
291   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
292   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
293
294   if (!Subtarget.useCRBits()) {
295     // PowerPC does not have Select
296     setOperationAction(ISD::SELECT, MVT::i32, Expand);
297     setOperationAction(ISD::SELECT, MVT::i64, Expand);
298     setOperationAction(ISD::SELECT, MVT::f32, Expand);
299     setOperationAction(ISD::SELECT, MVT::f64, Expand);
300   }
301
302   // PowerPC wants to turn select_cc of FP into fsel when possible.
303   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
304   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
305
306   // PowerPC wants to optimize integer setcc a bit
307   if (!Subtarget.useCRBits())
308     setOperationAction(ISD::SETCC, MVT::i32, Custom);
309
310   // PowerPC does not have BRCOND which requires SetCC
311   if (!Subtarget.useCRBits())
312     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
313
314   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
315
316   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
317   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
318
319   // PowerPC does not have [U|S]INT_TO_FP
320   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
321   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
322
323   if (Subtarget.hasDirectMove() && isPPC64) {
324     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
325     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
326     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
327     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
328   } else {
329     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
330     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
331     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
332     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
333   }
334
335   // We cannot sextinreg(i1).  Expand to shifts.
336   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
337
338   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
339   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
340   // support continuation, user-level threading, and etc.. As a result, no
341   // other SjLj exception interfaces are implemented and please don't build
342   // your own exception handling based on them.
343   // LLVM/Clang supports zero-cost DWARF exception handling.
344   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
345   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
346
347   // We want to legalize GlobalAddress and ConstantPool nodes into the
348   // appropriate instructions to materialize the address.
349   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
350   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
351   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
352   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
353   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
354   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
355   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
356   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
357   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
358   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
359
360   // TRAP is legal.
361   setOperationAction(ISD::TRAP, MVT::Other, Legal);
362
363   // TRAMPOLINE is custom lowered.
364   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
365   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
366
367   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
368   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
369
370   if (Subtarget.isSVR4ABI()) {
371     if (isPPC64) {
372       // VAARG always uses double-word chunks, so promote anything smaller.
373       setOperationAction(ISD::VAARG, MVT::i1, Promote);
374       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
375       setOperationAction(ISD::VAARG, MVT::i8, Promote);
376       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
377       setOperationAction(ISD::VAARG, MVT::i16, Promote);
378       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
379       setOperationAction(ISD::VAARG, MVT::i32, Promote);
380       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
381       setOperationAction(ISD::VAARG, MVT::Other, Expand);
382     } else {
383       // VAARG is custom lowered with the 32-bit SVR4 ABI.
384       setOperationAction(ISD::VAARG, MVT::Other, Custom);
385       setOperationAction(ISD::VAARG, MVT::i64, Custom);
386     }
387   } else
388     setOperationAction(ISD::VAARG, MVT::Other, Expand);
389
390   if (Subtarget.isSVR4ABI() && !isPPC64)
391     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
392     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
393   else
394     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
395
396   // Use the default implementation.
397   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
398   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
399   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
400   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
401   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
402   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
403   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
404   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
405   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
406
407   // We want to custom lower some of our intrinsics.
408   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
409
410   // To handle counter-based loop conditions.
411   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
412
413   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
414   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
415   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
416   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
417
418   // Comparisons that require checking two conditions.
419   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
420   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
421   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
422   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
423   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
424   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
425   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
426   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
427   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
428   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
429   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
430   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
431
432   if (Subtarget.has64BitSupport()) {
433     // They also have instructions for converting between i64 and fp.
434     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
435     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
436     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
437     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
438     // This is just the low 32 bits of a (signed) fp->i64 conversion.
439     // We cannot do this with Promote because i64 is not a legal type.
440     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
441
442     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
443       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
444   } else {
445     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
446     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
447   }
448
449   // With the instructions enabled under FPCVT, we can do everything.
450   if (Subtarget.hasFPCVT()) {
451     if (Subtarget.has64BitSupport()) {
452       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
453       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
454       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
455       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
456     }
457
458     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
459     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
460     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
461     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
462   }
463
464   if (Subtarget.use64BitRegs()) {
465     // 64-bit PowerPC implementations can support i64 types directly
466     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
467     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
468     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
469     // 64-bit PowerPC wants to expand i128 shifts itself.
470     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
471     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
472     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
473   } else {
474     // 32-bit PowerPC wants to expand i64 shifts itself.
475     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
476     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
477     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
478   }
479
480   if (Subtarget.hasAltivec()) {
481     // First set operation action for all vector types to expand. Then we
482     // will selectively turn on ones that can be effectively codegen'd.
483     for (MVT VT : MVT::vector_valuetypes()) {
484       // add/sub are legal for all supported vector VT's.
485       setOperationAction(ISD::ADD, VT, Legal);
486       setOperationAction(ISD::SUB, VT, Legal);
487
488       // Vector instructions introduced in P8
489       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
490         setOperationAction(ISD::CTPOP, VT, Legal);
491         setOperationAction(ISD::CTLZ, VT, Legal);
492       }
493       else {
494         setOperationAction(ISD::CTPOP, VT, Expand);
495         setOperationAction(ISD::CTLZ, VT, Expand);
496       }
497
498       // Vector instructions introduced in P9
499       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
500         setOperationAction(ISD::CTTZ, VT, Legal);
501       else
502         setOperationAction(ISD::CTTZ, VT, Expand);
503
504       // We promote all shuffles to v16i8.
505       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
506       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
507
508       // We promote all non-typed operations to v4i32.
509       setOperationAction(ISD::AND   , VT, Promote);
510       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
511       setOperationAction(ISD::OR    , VT, Promote);
512       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
513       setOperationAction(ISD::XOR   , VT, Promote);
514       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
515       setOperationAction(ISD::LOAD  , VT, Promote);
516       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
517       setOperationAction(ISD::SELECT, VT, Promote);
518       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
519       setOperationAction(ISD::SELECT_CC, VT, Promote);
520       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
521       setOperationAction(ISD::STORE, VT, Promote);
522       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
523
524       // No other operations are legal.
525       setOperationAction(ISD::MUL , VT, Expand);
526       setOperationAction(ISD::SDIV, VT, Expand);
527       setOperationAction(ISD::SREM, VT, Expand);
528       setOperationAction(ISD::UDIV, VT, Expand);
529       setOperationAction(ISD::UREM, VT, Expand);
530       setOperationAction(ISD::FDIV, VT, Expand);
531       setOperationAction(ISD::FREM, VT, Expand);
532       setOperationAction(ISD::FNEG, VT, Expand);
533       setOperationAction(ISD::FSQRT, VT, Expand);
534       setOperationAction(ISD::FLOG, VT, Expand);
535       setOperationAction(ISD::FLOG10, VT, Expand);
536       setOperationAction(ISD::FLOG2, VT, Expand);
537       setOperationAction(ISD::FEXP, VT, Expand);
538       setOperationAction(ISD::FEXP2, VT, Expand);
539       setOperationAction(ISD::FSIN, VT, Expand);
540       setOperationAction(ISD::FCOS, VT, Expand);
541       setOperationAction(ISD::FABS, VT, Expand);
542       setOperationAction(ISD::FPOWI, VT, Expand);
543       setOperationAction(ISD::FFLOOR, VT, Expand);
544       setOperationAction(ISD::FCEIL,  VT, Expand);
545       setOperationAction(ISD::FTRUNC, VT, Expand);
546       setOperationAction(ISD::FRINT,  VT, Expand);
547       setOperationAction(ISD::FNEARBYINT, VT, Expand);
548       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
549       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
550       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
551       setOperationAction(ISD::MULHU, VT, Expand);
552       setOperationAction(ISD::MULHS, VT, Expand);
553       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
554       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
555       setOperationAction(ISD::UDIVREM, VT, Expand);
556       setOperationAction(ISD::SDIVREM, VT, Expand);
557       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
558       setOperationAction(ISD::FPOW, VT, Expand);
559       setOperationAction(ISD::BSWAP, VT, Expand);
560       setOperationAction(ISD::VSELECT, VT, Expand);
561       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
562       setOperationAction(ISD::ROTL, VT, Expand);
563       setOperationAction(ISD::ROTR, VT, Expand);
564
565       for (MVT InnerVT : MVT::vector_valuetypes()) {
566         setTruncStoreAction(VT, InnerVT, Expand);
567         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
568         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
569         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
570       }
571     }
572
573     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
574     // with merges, splats, etc.
575     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
576
577     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
578     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
579     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
580     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
581     setOperationAction(ISD::SELECT, MVT::v4i32,
582                        Subtarget.useCRBits() ? Legal : Expand);
583     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
584     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
585     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
586     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
587     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
588     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
589     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
590     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
591     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
592
593     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
594     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
595     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
596     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
597
598     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
599     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
600
601     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
602       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
603       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
604     }
605
606     if (Subtarget.hasP8Altivec())
607       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
608     else
609       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
610
611     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
612     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
613
614     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
615     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
616
617     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
618     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
619     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
620     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
621
622     // Altivec does not contain unordered floating-point compare instructions
623     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
624     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
625     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
626     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
627
628     if (Subtarget.hasVSX()) {
629       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
630       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
631       if (Subtarget.hasP8Vector()) {
632         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
633         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
634       }
635       if (Subtarget.hasDirectMove() && isPPC64) {
636         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
637         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
638         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
639         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
640         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
641         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
642         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
643         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
644       }
645       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
646
647       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
648       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
649       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
650       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
651       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
652
653       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
654
655       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
656       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
657
658       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
659       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
660
661       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
662       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
663       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
664       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
665       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
666
667       // Share the Altivec comparison restrictions.
668       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
669       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
670       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
671       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
672
673       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
674       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
675
676       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
677
678       if (Subtarget.hasP8Vector())
679         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
680
681       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
682
683       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
684       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
685       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
686
687       if (Subtarget.hasP8Altivec()) {
688         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
689         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
690         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
691
692         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
693       }
694       else {
695         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
696         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
697         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
698
699         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
700
701         // VSX v2i64 only supports non-arithmetic operations.
702         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
703         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
704       }
705
706       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
707       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
708       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
709       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
710
711       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
712
713       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
714       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
715       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
716       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
717
718       // Vector operation legalization checks the result type of
719       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
720       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
721       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
722       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
723       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
724
725       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
726       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
727       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
728       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
729
730       if (Subtarget.hasDirectMove())
731         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
732       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
733
734       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
735     }
736
737     if (Subtarget.hasP8Altivec()) {
738       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
739       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
740     }
741
742     if (Subtarget.hasP9Vector()) {
743       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
744       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
745     }
746   }
747
748   if (Subtarget.hasQPX()) {
749     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
750     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
751     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
752     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
753
754     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
755     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
756
757     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
758     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
759
760     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
761     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
762
763     if (!Subtarget.useCRBits())
764       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
765     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
766
767     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
768     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
769     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
770     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
771     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
772     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
773     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
774
775     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
776     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
777
778     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
779     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
780     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
781
782     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
783     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
784     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
785     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
786     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
787     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
788     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
789     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
790     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
791     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
792     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
793
794     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
795     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
796
797     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
798     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
799
800     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
801
802     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
803     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
804     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
805     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
806
807     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
808     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
809
810     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
811     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
812
813     if (!Subtarget.useCRBits())
814       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
815     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
816
817     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
818     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
819     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
820     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
821     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
822     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
823     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
824
825     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
826     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
827
828     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
829     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
830     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
831     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
832     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
833     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
834     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
835     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
836     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
837     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
838     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
839
840     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
841     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
842
843     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
844     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
845
846     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
847
848     setOperationAction(ISD::AND , MVT::v4i1, Legal);
849     setOperationAction(ISD::OR , MVT::v4i1, Legal);
850     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
851
852     if (!Subtarget.useCRBits())
853       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
854     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
855
856     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
857     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
858
859     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
861     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
862     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
863     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
864     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
865     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
866
867     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
868     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
869
870     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
871
872     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
873     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
874     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
875     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
876
877     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
878     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
879     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
880     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
881
882     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
883     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
884
885     // These need to set FE_INEXACT, and so cannot be vectorized here.
886     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
887     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
888
889     if (TM.Options.UnsafeFPMath) {
890       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
891       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
892
893       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
894       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
895     } else {
896       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
897       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
898
899       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
900       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
901     }
902   }
903
904   if (Subtarget.has64BitSupport())
905     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
906
907   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
908
909   if (!isPPC64) {
910     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
911     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
912   }
913
914   setBooleanContents(ZeroOrOneBooleanContent);
915
916   if (Subtarget.hasAltivec()) {
917     // Altivec instructions set fields to all zeros or all ones.
918     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
919   }
920
921   if (!isPPC64) {
922     // These libcalls are not available in 32-bit.
923     setLibcallName(RTLIB::SHL_I128, nullptr);
924     setLibcallName(RTLIB::SRL_I128, nullptr);
925     setLibcallName(RTLIB::SRA_I128, nullptr);
926   }
927
928   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
929
930   // We have target-specific dag combine patterns for the following nodes:
931   setTargetDAGCombine(ISD::SHL);
932   setTargetDAGCombine(ISD::SRA);
933   setTargetDAGCombine(ISD::SRL);
934   setTargetDAGCombine(ISD::SINT_TO_FP);
935   setTargetDAGCombine(ISD::BUILD_VECTOR);
936   if (Subtarget.hasFPCVT())
937     setTargetDAGCombine(ISD::UINT_TO_FP);
938   setTargetDAGCombine(ISD::LOAD);
939   setTargetDAGCombine(ISD::STORE);
940   setTargetDAGCombine(ISD::BR_CC);
941   if (Subtarget.useCRBits())
942     setTargetDAGCombine(ISD::BRCOND);
943   setTargetDAGCombine(ISD::BSWAP);
944   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
945   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
946   setTargetDAGCombine(ISD::INTRINSIC_VOID);
947
948   setTargetDAGCombine(ISD::SIGN_EXTEND);
949   setTargetDAGCombine(ISD::ZERO_EXTEND);
950   setTargetDAGCombine(ISD::ANY_EXTEND);
951
952   if (Subtarget.useCRBits()) {
953     setTargetDAGCombine(ISD::TRUNCATE);
954     setTargetDAGCombine(ISD::SETCC);
955     setTargetDAGCombine(ISD::SELECT_CC);
956   }
957
958   // Use reciprocal estimates.
959   if (TM.Options.UnsafeFPMath) {
960     setTargetDAGCombine(ISD::FDIV);
961     setTargetDAGCombine(ISD::FSQRT);
962   }
963
964   // Darwin long double math library functions have $LDBL128 appended.
965   if (Subtarget.isDarwin()) {
966     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
967     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
968     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
969     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
970     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
971     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
972     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
973     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
974     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
975     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
976   }
977
978   // With 32 condition bits, we don't need to sink (and duplicate) compares
979   // aggressively in CodeGenPrep.
980   if (Subtarget.useCRBits()) {
981     setHasMultipleConditionRegisters();
982     setJumpIsExpensive();
983   }
984
985   setMinFunctionAlignment(2);
986   if (Subtarget.isDarwin())
987     setPrefFunctionAlignment(4);
988
989   switch (Subtarget.getDarwinDirective()) {
990   default: break;
991   case PPC::DIR_970:
992   case PPC::DIR_A2:
993   case PPC::DIR_E500mc:
994   case PPC::DIR_E5500:
995   case PPC::DIR_PWR4:
996   case PPC::DIR_PWR5:
997   case PPC::DIR_PWR5X:
998   case PPC::DIR_PWR6:
999   case PPC::DIR_PWR6X:
1000   case PPC::DIR_PWR7:
1001   case PPC::DIR_PWR8:
1002   case PPC::DIR_PWR9:
1003     setPrefFunctionAlignment(4);
1004     setPrefLoopAlignment(4);
1005     break;
1006   }
1007
1008   if (Subtarget.enableMachineScheduler())
1009     setSchedulingPreference(Sched::Source);
1010   else
1011     setSchedulingPreference(Sched::Hybrid);
1012
1013   computeRegisterProperties(STI.getRegisterInfo());
1014
1015   // The Freescale cores do better with aggressive inlining of memcpy and
1016   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1017   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1018       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1019     MaxStoresPerMemset = 32;
1020     MaxStoresPerMemsetOptSize = 16;
1021     MaxStoresPerMemcpy = 32;
1022     MaxStoresPerMemcpyOptSize = 8;
1023     MaxStoresPerMemmove = 32;
1024     MaxStoresPerMemmoveOptSize = 8;
1025   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1026     // The A2 also benefits from (very) aggressive inlining of memcpy and
1027     // friends. The overhead of a the function call, even when warm, can be
1028     // over one hundred cycles.
1029     MaxStoresPerMemset = 128;
1030     MaxStoresPerMemcpy = 128;
1031     MaxStoresPerMemmove = 128;
1032   }
1033 }
1034
1035 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1036 /// the desired ByVal argument alignment.
1037 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1038                              unsigned MaxMaxAlign) {
1039   if (MaxAlign == MaxMaxAlign)
1040     return;
1041   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1042     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1043       MaxAlign = 32;
1044     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1045       MaxAlign = 16;
1046   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1047     unsigned EltAlign = 0;
1048     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1049     if (EltAlign > MaxAlign)
1050       MaxAlign = EltAlign;
1051   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1052     for (auto *EltTy : STy->elements()) {
1053       unsigned EltAlign = 0;
1054       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1055       if (EltAlign > MaxAlign)
1056         MaxAlign = EltAlign;
1057       if (MaxAlign == MaxMaxAlign)
1058         break;
1059     }
1060   }
1061 }
1062
1063 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1064 /// function arguments in the caller parameter area.
1065 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1066                                                   const DataLayout &DL) const {
1067   // Darwin passes everything on 4 byte boundary.
1068   if (Subtarget.isDarwin())
1069     return 4;
1070
1071   // 16byte and wider vectors are passed on 16byte boundary.
1072   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1073   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1074   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1075     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1076   return Align;
1077 }
1078
1079 bool PPCTargetLowering::useSoftFloat() const {
1080   return Subtarget.useSoftFloat();
1081 }
1082
1083 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1084   switch ((PPCISD::NodeType)Opcode) {
1085   case PPCISD::FIRST_NUMBER:    break;
1086   case PPCISD::FSEL:            return "PPCISD::FSEL";
1087   case PPCISD::FCFID:           return "PPCISD::FCFID";
1088   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1089   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1090   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1091   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1092   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1093   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1094   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1095   case PPCISD::FRE:             return "PPCISD::FRE";
1096   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1097   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1098   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1099   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1100   case PPCISD::VPERM:           return "PPCISD::VPERM";
1101   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1102   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1103   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1104   case PPCISD::CMPB:            return "PPCISD::CMPB";
1105   case PPCISD::Hi:              return "PPCISD::Hi";
1106   case PPCISD::Lo:              return "PPCISD::Lo";
1107   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1108   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1109   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1110   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1111   case PPCISD::SRL:             return "PPCISD::SRL";
1112   case PPCISD::SRA:             return "PPCISD::SRA";
1113   case PPCISD::SHL:             return "PPCISD::SHL";
1114   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1115   case PPCISD::CALL:            return "PPCISD::CALL";
1116   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1117   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1118   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1119   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1120   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1121   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1122   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1123   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1124   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1125   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1126   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1127   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1128   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1129   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1130   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1131   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1132   case PPCISD::VCMP:            return "PPCISD::VCMP";
1133   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1134   case PPCISD::LBRX:            return "PPCISD::LBRX";
1135   case PPCISD::STBRX:           return "PPCISD::STBRX";
1136   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1137   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1138   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1139   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1140   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1141   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1142   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1143   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1144   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1145   case PPCISD::BDZ:             return "PPCISD::BDZ";
1146   case PPCISD::MFFS:            return "PPCISD::MFFS";
1147   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1148   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1149   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1150   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1151   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1152   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1153   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1154   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1155   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1156   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1157   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1158   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1159   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1160   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1161   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1162   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1163   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1164   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1165   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1166   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1167   case PPCISD::SC:              return "PPCISD::SC";
1168   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1169   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1170   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1171   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1172   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1173   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1174   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1175   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1176   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1177   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1178   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1179   }
1180   return nullptr;
1181 }
1182
1183 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1184                                           EVT VT) const {
1185   if (!VT.isVector())
1186     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1187
1188   if (Subtarget.hasQPX())
1189     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1190
1191   return VT.changeVectorElementTypeToInteger();
1192 }
1193
1194 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1195   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1196   return true;
1197 }
1198
1199 //===----------------------------------------------------------------------===//
1200 // Node matching predicates, for use by the tblgen matching code.
1201 //===----------------------------------------------------------------------===//
1202
1203 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1204 static bool isFloatingPointZero(SDValue Op) {
1205   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1206     return CFP->getValueAPF().isZero();
1207   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1208     // Maybe this has already been legalized into the constant pool?
1209     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1210       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1211         return CFP->getValueAPF().isZero();
1212   }
1213   return false;
1214 }
1215
1216 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1217 /// true if Op is undef or if it matches the specified value.
1218 static bool isConstantOrUndef(int Op, int Val) {
1219   return Op < 0 || Op == Val;
1220 }
1221
1222 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1223 /// VPKUHUM instruction.
1224 /// The ShuffleKind distinguishes between big-endian operations with
1225 /// two different inputs (0), either-endian operations with two identical
1226 /// inputs (1), and little-endian operations with two different inputs (2).
1227 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1228 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1229                                SelectionDAG &DAG) {
1230   bool IsLE = DAG.getDataLayout().isLittleEndian();
1231   if (ShuffleKind == 0) {
1232     if (IsLE)
1233       return false;
1234     for (unsigned i = 0; i != 16; ++i)
1235       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1236         return false;
1237   } else if (ShuffleKind == 2) {
1238     if (!IsLE)
1239       return false;
1240     for (unsigned i = 0; i != 16; ++i)
1241       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1242         return false;
1243   } else if (ShuffleKind == 1) {
1244     unsigned j = IsLE ? 0 : 1;
1245     for (unsigned i = 0; i != 8; ++i)
1246       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1247           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1248         return false;
1249   }
1250   return true;
1251 }
1252
1253 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1254 /// VPKUWUM instruction.
1255 /// The ShuffleKind distinguishes between big-endian operations with
1256 /// two different inputs (0), either-endian operations with two identical
1257 /// inputs (1), and little-endian operations with two different inputs (2).
1258 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1259 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1260                                SelectionDAG &DAG) {
1261   bool IsLE = DAG.getDataLayout().isLittleEndian();
1262   if (ShuffleKind == 0) {
1263     if (IsLE)
1264       return false;
1265     for (unsigned i = 0; i != 16; i += 2)
1266       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1267           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1268         return false;
1269   } else if (ShuffleKind == 2) {
1270     if (!IsLE)
1271       return false;
1272     for (unsigned i = 0; i != 16; i += 2)
1273       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1274           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1275         return false;
1276   } else if (ShuffleKind == 1) {
1277     unsigned j = IsLE ? 0 : 2;
1278     for (unsigned i = 0; i != 8; i += 2)
1279       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1280           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1281           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1282           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1283         return false;
1284   }
1285   return true;
1286 }
1287
1288 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1289 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1290 /// current subtarget.
1291 ///
1292 /// The ShuffleKind distinguishes between big-endian operations with
1293 /// two different inputs (0), either-endian operations with two identical
1294 /// inputs (1), and little-endian operations with two different inputs (2).
1295 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1296 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1297                                SelectionDAG &DAG) {
1298   const PPCSubtarget& Subtarget =
1299     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1300   if (!Subtarget.hasP8Vector())
1301     return false;
1302
1303   bool IsLE = DAG.getDataLayout().isLittleEndian();
1304   if (ShuffleKind == 0) {
1305     if (IsLE)
1306       return false;
1307     for (unsigned i = 0; i != 16; i += 4)
1308       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1309           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1310           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1311           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1312         return false;
1313   } else if (ShuffleKind == 2) {
1314     if (!IsLE)
1315       return false;
1316     for (unsigned i = 0; i != 16; i += 4)
1317       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1318           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1319           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1320           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1321         return false;
1322   } else if (ShuffleKind == 1) {
1323     unsigned j = IsLE ? 0 : 4;
1324     for (unsigned i = 0; i != 8; i += 4)
1325       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1326           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1327           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1328           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1329           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1330           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1331           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1332           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1333         return false;
1334   }
1335   return true;
1336 }
1337
1338 /// isVMerge - Common function, used to match vmrg* shuffles.
1339 ///
1340 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1341                      unsigned LHSStart, unsigned RHSStart) {
1342   if (N->getValueType(0) != MVT::v16i8)
1343     return false;
1344   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1345          "Unsupported merge size!");
1346
1347   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1348     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1349       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1350                              LHSStart+j+i*UnitSize) ||
1351           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1352                              RHSStart+j+i*UnitSize))
1353         return false;
1354     }
1355   return true;
1356 }
1357
1358 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1359 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1360 /// The ShuffleKind distinguishes between big-endian merges with two
1361 /// different inputs (0), either-endian merges with two identical inputs (1),
1362 /// and little-endian merges with two different inputs (2).  For the latter,
1363 /// the input operands are swapped (see PPCInstrAltivec.td).
1364 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1365                              unsigned ShuffleKind, SelectionDAG &DAG) {
1366   if (DAG.getDataLayout().isLittleEndian()) {
1367     if (ShuffleKind == 1) // unary
1368       return isVMerge(N, UnitSize, 0, 0);
1369     else if (ShuffleKind == 2) // swapped
1370       return isVMerge(N, UnitSize, 0, 16);
1371     else
1372       return false;
1373   } else {
1374     if (ShuffleKind == 1) // unary
1375       return isVMerge(N, UnitSize, 8, 8);
1376     else if (ShuffleKind == 0) // normal
1377       return isVMerge(N, UnitSize, 8, 24);
1378     else
1379       return false;
1380   }
1381 }
1382
1383 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1384 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1385 /// The ShuffleKind distinguishes between big-endian merges with two
1386 /// different inputs (0), either-endian merges with two identical inputs (1),
1387 /// and little-endian merges with two different inputs (2).  For the latter,
1388 /// the input operands are swapped (see PPCInstrAltivec.td).
1389 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1390                              unsigned ShuffleKind, SelectionDAG &DAG) {
1391   if (DAG.getDataLayout().isLittleEndian()) {
1392     if (ShuffleKind == 1) // unary
1393       return isVMerge(N, UnitSize, 8, 8);
1394     else if (ShuffleKind == 2) // swapped
1395       return isVMerge(N, UnitSize, 8, 24);
1396     else
1397       return false;
1398   } else {
1399     if (ShuffleKind == 1) // unary
1400       return isVMerge(N, UnitSize, 0, 0);
1401     else if (ShuffleKind == 0) // normal
1402       return isVMerge(N, UnitSize, 0, 16);
1403     else
1404       return false;
1405   }
1406 }
1407
1408 /**
1409  * \brief Common function used to match vmrgew and vmrgow shuffles
1410  *
1411  * The indexOffset determines whether to look for even or odd words in
1412  * the shuffle mask. This is based on the of the endianness of the target
1413  * machine.
1414  *   - Little Endian:
1415  *     - Use offset of 0 to check for odd elements
1416  *     - Use offset of 4 to check for even elements
1417  *   - Big Endian:
1418  *     - Use offset of 0 to check for even elements
1419  *     - Use offset of 4 to check for odd elements
1420  * A detailed description of the vector element ordering for little endian and
1421  * big endian can be found at
1422  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1423  * Targeting your applications - what little endian and big endian IBM XL C/C++
1424  * compiler differences mean to you
1425  *
1426  * The mask to the shuffle vector instruction specifies the indices of the
1427  * elements from the two input vectors to place in the result. The elements are
1428  * numbered in array-access order, starting with the first vector. These vectors
1429  * are always of type v16i8, thus each vector will contain 16 elements of size
1430  * 8. More info on the shuffle vector can be found in the
1431  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1432  * Language Reference.
1433  *
1434  * The RHSStartValue indicates whether the same input vectors are used (unary)
1435  * or two different input vectors are used, based on the following:
1436  *   - If the instruction uses the same vector for both inputs, the range of the
1437  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1438  *     be 0.
1439  *   - If the instruction has two different vectors then the range of the
1440  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1441  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1442  *     to 31 specify elements in the second vector).
1443  *
1444  * \param[in] N The shuffle vector SD Node to analyze
1445  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1446  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1447  * vector to the shuffle_vector instruction
1448  * \return true iff this shuffle vector represents an even or odd word merge
1449  */
1450 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1451                      unsigned RHSStartValue) {
1452   if (N->getValueType(0) != MVT::v16i8)
1453     return false;
1454
1455   for (unsigned i = 0; i < 2; ++i)
1456     for (unsigned j = 0; j < 4; ++j)
1457       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1458                              i*RHSStartValue+j+IndexOffset) ||
1459           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1460                              i*RHSStartValue+j+IndexOffset+8))
1461         return false;
1462   return true;
1463 }
1464
1465 /**
1466  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1467  * vmrgow instructions.
1468  *
1469  * \param[in] N The shuffle vector SD Node to analyze
1470  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1471  * \param[in] ShuffleKind Identify the type of merge:
1472  *   - 0 = big-endian merge with two different inputs;
1473  *   - 1 = either-endian merge with two identical inputs;
1474  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1475  *     little-endian merges).
1476  * \param[in] DAG The current SelectionDAG
1477  * \return true iff this shuffle mask
1478  */
1479 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1480                               unsigned ShuffleKind, SelectionDAG &DAG) {
1481   if (DAG.getDataLayout().isLittleEndian()) {
1482     unsigned indexOffset = CheckEven ? 4 : 0;
1483     if (ShuffleKind == 1) // Unary
1484       return isVMerge(N, indexOffset, 0);
1485     else if (ShuffleKind == 2) // swapped
1486       return isVMerge(N, indexOffset, 16);
1487     else
1488       return false;
1489   }
1490   else {
1491     unsigned indexOffset = CheckEven ? 0 : 4;
1492     if (ShuffleKind == 1) // Unary
1493       return isVMerge(N, indexOffset, 0);
1494     else if (ShuffleKind == 0) // Normal
1495       return isVMerge(N, indexOffset, 16);
1496     else
1497       return false;
1498   }
1499   return false;
1500 }
1501
1502 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1503 /// amount, otherwise return -1.
1504 /// The ShuffleKind distinguishes between big-endian operations with two
1505 /// different inputs (0), either-endian operations with two identical inputs
1506 /// (1), and little-endian operations with two different inputs (2).  For the
1507 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1508 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1509                              SelectionDAG &DAG) {
1510   if (N->getValueType(0) != MVT::v16i8)
1511     return -1;
1512
1513   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1514
1515   // Find the first non-undef value in the shuffle mask.
1516   unsigned i;
1517   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1518     /*search*/;
1519
1520   if (i == 16) return -1;  // all undef.
1521
1522   // Otherwise, check to see if the rest of the elements are consecutively
1523   // numbered from this value.
1524   unsigned ShiftAmt = SVOp->getMaskElt(i);
1525   if (ShiftAmt < i) return -1;
1526
1527   ShiftAmt -= i;
1528   bool isLE = DAG.getDataLayout().isLittleEndian();
1529
1530   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1531     // Check the rest of the elements to see if they are consecutive.
1532     for (++i; i != 16; ++i)
1533       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1534         return -1;
1535   } else if (ShuffleKind == 1) {
1536     // Check the rest of the elements to see if they are consecutive.
1537     for (++i; i != 16; ++i)
1538       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1539         return -1;
1540   } else
1541     return -1;
1542
1543   if (isLE)
1544     ShiftAmt = 16 - ShiftAmt;
1545
1546   return ShiftAmt;
1547 }
1548
1549 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1550 /// specifies a splat of a single element that is suitable for input to
1551 /// VSPLTB/VSPLTH/VSPLTW.
1552 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1553   assert(N->getValueType(0) == MVT::v16i8 &&
1554          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1555
1556   // The consecutive indices need to specify an element, not part of two
1557   // different elements.  So abandon ship early if this isn't the case.
1558   if (N->getMaskElt(0) % EltSize != 0)
1559     return false;
1560
1561   // This is a splat operation if each element of the permute is the same, and
1562   // if the value doesn't reference the second vector.
1563   unsigned ElementBase = N->getMaskElt(0);
1564
1565   // FIXME: Handle UNDEF elements too!
1566   if (ElementBase >= 16)
1567     return false;
1568
1569   // Check that the indices are consecutive, in the case of a multi-byte element
1570   // splatted with a v16i8 mask.
1571   for (unsigned i = 1; i != EltSize; ++i)
1572     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1573       return false;
1574
1575   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1576     if (N->getMaskElt(i) < 0) continue;
1577     for (unsigned j = 0; j != EltSize; ++j)
1578       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1579         return false;
1580   }
1581   return true;
1582 }
1583
1584 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1585                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1586   // Check that the mask is shuffling words
1587   for (unsigned i = 0; i < 4; ++i) {
1588     unsigned B0 = N->getMaskElt(i*4);
1589     unsigned B1 = N->getMaskElt(i*4+1);
1590     unsigned B2 = N->getMaskElt(i*4+2);
1591     unsigned B3 = N->getMaskElt(i*4+3);
1592     if (B0 % 4)
1593       return false;
1594     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1595       return false;
1596   }
1597
1598   // Now we look at mask elements 0,4,8,12
1599   unsigned M0 = N->getMaskElt(0) / 4;
1600   unsigned M1 = N->getMaskElt(4) / 4;
1601   unsigned M2 = N->getMaskElt(8) / 4;
1602   unsigned M3 = N->getMaskElt(12) / 4;
1603   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1604   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1605
1606   // Below, let H and L be arbitrary elements of the shuffle mask
1607   // where H is in the range [4,7] and L is in the range [0,3].
1608   // H, 1, 2, 3 or L, 5, 6, 7
1609   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1610       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1611     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1612     InsertAtByte = IsLE ? 12 : 0;
1613     Swap = M0 < 4;
1614     return true;
1615   }
1616   // 0, H, 2, 3 or 4, L, 6, 7
1617   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1618       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1619     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1620     InsertAtByte = IsLE ? 8 : 4;
1621     Swap = M1 < 4;
1622     return true;
1623   }
1624   // 0, 1, H, 3 or 4, 5, L, 7
1625   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1626       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1627     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1628     InsertAtByte = IsLE ? 4 : 8;
1629     Swap = M2 < 4;
1630     return true;
1631   }
1632   // 0, 1, 2, H or 4, 5, 6, L
1633   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1634       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1635     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1636     InsertAtByte = IsLE ? 0 : 12;
1637     Swap = M3 < 4;
1638     return true;
1639   }
1640
1641   // If both vector operands for the shuffle are the same vector, the mask will
1642   // contain only elements from the first one and the second one will be undef.
1643   if (N->getOperand(1).isUndef()) {
1644     ShiftElts = 0;
1645     Swap = true;
1646     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1647     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1648       InsertAtByte = IsLE ? 12 : 0;
1649       return true;
1650     }
1651     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1652       InsertAtByte = IsLE ? 8 : 4;
1653       return true;
1654     }
1655     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1656       InsertAtByte = IsLE ? 4 : 8;
1657       return true;
1658     }
1659     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1660       InsertAtByte = IsLE ? 0 : 12;
1661       return true;
1662     }
1663   }
1664
1665   return false;
1666 }
1667
1668 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1669 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1670 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1671                                 SelectionDAG &DAG) {
1672   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1673   assert(isSplatShuffleMask(SVOp, EltSize));
1674   if (DAG.getDataLayout().isLittleEndian())
1675     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1676   else
1677     return SVOp->getMaskElt(0) / EltSize;
1678 }
1679
1680 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1681 /// by using a vspltis[bhw] instruction of the specified element size, return
1682 /// the constant being splatted.  The ByteSize field indicates the number of
1683 /// bytes of each element [124] -> [bhw].
1684 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1685   SDValue OpVal(nullptr, 0);
1686
1687   // If ByteSize of the splat is bigger than the element size of the
1688   // build_vector, then we have a case where we are checking for a splat where
1689   // multiple elements of the buildvector are folded together into a single
1690   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1691   unsigned EltSize = 16/N->getNumOperands();
1692   if (EltSize < ByteSize) {
1693     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1694     SDValue UniquedVals[4];
1695     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1696
1697     // See if all of the elements in the buildvector agree across.
1698     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1699       if (N->getOperand(i).isUndef()) continue;
1700       // If the element isn't a constant, bail fully out.
1701       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1702
1703       if (!UniquedVals[i&(Multiple-1)].getNode())
1704         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1705       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1706         return SDValue();  // no match.
1707     }
1708
1709     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1710     // either constant or undef values that are identical for each chunk.  See
1711     // if these chunks can form into a larger vspltis*.
1712
1713     // Check to see if all of the leading entries are either 0 or -1.  If
1714     // neither, then this won't fit into the immediate field.
1715     bool LeadingZero = true;
1716     bool LeadingOnes = true;
1717     for (unsigned i = 0; i != Multiple-1; ++i) {
1718       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1719
1720       LeadingZero &= isNullConstant(UniquedVals[i]);
1721       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1722     }
1723     // Finally, check the least significant entry.
1724     if (LeadingZero) {
1725       if (!UniquedVals[Multiple-1].getNode())
1726         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1727       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1728       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1729         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1730     }
1731     if (LeadingOnes) {
1732       if (!UniquedVals[Multiple-1].getNode())
1733         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1734       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1735       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1736         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1737     }
1738
1739     return SDValue();
1740   }
1741
1742   // Check to see if this buildvec has a single non-undef value in its elements.
1743   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1744     if (N->getOperand(i).isUndef()) continue;
1745     if (!OpVal.getNode())
1746       OpVal = N->getOperand(i);
1747     else if (OpVal != N->getOperand(i))
1748       return SDValue();
1749   }
1750
1751   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1752
1753   unsigned ValSizeInBytes = EltSize;
1754   uint64_t Value = 0;
1755   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1756     Value = CN->getZExtValue();
1757   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1758     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1759     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1760   }
1761
1762   // If the splat value is larger than the element value, then we can never do
1763   // this splat.  The only case that we could fit the replicated bits into our
1764   // immediate field for would be zero, and we prefer to use vxor for it.
1765   if (ValSizeInBytes < ByteSize) return SDValue();
1766
1767   // If the element value is larger than the splat value, check if it consists
1768   // of a repeated bit pattern of size ByteSize.
1769   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1770     return SDValue();
1771
1772   // Properly sign extend the value.
1773   int MaskVal = SignExtend32(Value, ByteSize * 8);
1774
1775   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1776   if (MaskVal == 0) return SDValue();
1777
1778   // Finally, if this value fits in a 5 bit sext field, return it
1779   if (SignExtend32<5>(MaskVal) == MaskVal)
1780     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1781   return SDValue();
1782 }
1783
1784 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1785 /// amount, otherwise return -1.
1786 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1787   EVT VT = N->getValueType(0);
1788   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1789     return -1;
1790
1791   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1792
1793   // Find the first non-undef value in the shuffle mask.
1794   unsigned i;
1795   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1796     /*search*/;
1797
1798   if (i == 4) return -1;  // all undef.
1799
1800   // Otherwise, check to see if the rest of the elements are consecutively
1801   // numbered from this value.
1802   unsigned ShiftAmt = SVOp->getMaskElt(i);
1803   if (ShiftAmt < i) return -1;
1804   ShiftAmt -= i;
1805
1806   // Check the rest of the elements to see if they are consecutive.
1807   for (++i; i != 4; ++i)
1808     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1809       return -1;
1810
1811   return ShiftAmt;
1812 }
1813
1814 //===----------------------------------------------------------------------===//
1815 //  Addressing Mode Selection
1816 //===----------------------------------------------------------------------===//
1817
1818 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1819 /// or 64-bit immediate, and if the value can be accurately represented as a
1820 /// sign extension from a 16-bit value.  If so, this returns true and the
1821 /// immediate.
1822 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1823   if (!isa<ConstantSDNode>(N))
1824     return false;
1825
1826   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1827   if (N->getValueType(0) == MVT::i32)
1828     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1829   else
1830     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1831 }
1832 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1833   return isIntS16Immediate(Op.getNode(), Imm);
1834 }
1835
1836 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1837 /// can be represented as an indexed [r+r] operation.  Returns false if it
1838 /// can be more efficiently represented with [r+imm].
1839 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1840                                             SDValue &Index,
1841                                             SelectionDAG &DAG) const {
1842   short imm = 0;
1843   if (N.getOpcode() == ISD::ADD) {
1844     if (isIntS16Immediate(N.getOperand(1), imm))
1845       return false;    // r+i
1846     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1847       return false;    // r+i
1848
1849     Base = N.getOperand(0);
1850     Index = N.getOperand(1);
1851     return true;
1852   } else if (N.getOpcode() == ISD::OR) {
1853     if (isIntS16Immediate(N.getOperand(1), imm))
1854       return false;    // r+i can fold it if we can.
1855
1856     // If this is an or of disjoint bitfields, we can codegen this as an add
1857     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1858     // disjoint.
1859     KnownBits LHSKnown, RHSKnown;
1860     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1861
1862     if (LHSKnown.Zero.getBoolValue()) {
1863       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
1864       // If all of the bits are known zero on the LHS or RHS, the add won't
1865       // carry.
1866       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
1867         Base = N.getOperand(0);
1868         Index = N.getOperand(1);
1869         return true;
1870       }
1871     }
1872   }
1873
1874   return false;
1875 }
1876
1877 // If we happen to be doing an i64 load or store into a stack slot that has
1878 // less than a 4-byte alignment, then the frame-index elimination may need to
1879 // use an indexed load or store instruction (because the offset may not be a
1880 // multiple of 4). The extra register needed to hold the offset comes from the
1881 // register scavenger, and it is possible that the scavenger will need to use
1882 // an emergency spill slot. As a result, we need to make sure that a spill slot
1883 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1884 // stack slot.
1885 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1886   // FIXME: This does not handle the LWA case.
1887   if (VT != MVT::i64)
1888     return;
1889
1890   // NOTE: We'll exclude negative FIs here, which come from argument
1891   // lowering, because there are no known test cases triggering this problem
1892   // using packed structures (or similar). We can remove this exclusion if
1893   // we find such a test case. The reason why this is so test-case driven is
1894   // because this entire 'fixup' is only to prevent crashes (from the
1895   // register scavenger) on not-really-valid inputs. For example, if we have:
1896   //   %a = alloca i1
1897   //   %b = bitcast i1* %a to i64*
1898   //   store i64* a, i64 b
1899   // then the store should really be marked as 'align 1', but is not. If it
1900   // were marked as 'align 1' then the indexed form would have been
1901   // instruction-selected initially, and the problem this 'fixup' is preventing
1902   // won't happen regardless.
1903   if (FrameIdx < 0)
1904     return;
1905
1906   MachineFunction &MF = DAG.getMachineFunction();
1907   MachineFrameInfo &MFI = MF.getFrameInfo();
1908
1909   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1910   if (Align >= 4)
1911     return;
1912
1913   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1914   FuncInfo->setHasNonRISpills();
1915 }
1916
1917 /// Returns true if the address N can be represented by a base register plus
1918 /// a signed 16-bit displacement [r+imm], and if it is not better
1919 /// represented as reg+reg.  If Aligned is true, only accept displacements
1920 /// suitable for STD and friends, i.e. multiples of 4.
1921 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1922                                             SDValue &Base,
1923                                             SelectionDAG &DAG,
1924                                             bool Aligned) const {
1925   // FIXME dl should come from parent load or store, not from address
1926   SDLoc dl(N);
1927   // If this can be more profitably realized as r+r, fail.
1928   if (SelectAddressRegReg(N, Disp, Base, DAG))
1929     return false;
1930
1931   if (N.getOpcode() == ISD::ADD) {
1932     short imm = 0;
1933     if (isIntS16Immediate(N.getOperand(1), imm) &&
1934         (!Aligned || (imm & 3) == 0)) {
1935       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1936       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1937         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1938         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1939       } else {
1940         Base = N.getOperand(0);
1941       }
1942       return true; // [r+i]
1943     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1944       // Match LOAD (ADD (X, Lo(G))).
1945       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1946              && "Cannot handle constant offsets yet!");
1947       Disp = N.getOperand(1).getOperand(0);  // The global address.
1948       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1949              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1950              Disp.getOpcode() == ISD::TargetConstantPool ||
1951              Disp.getOpcode() == ISD::TargetJumpTable);
1952       Base = N.getOperand(0);
1953       return true;  // [&g+r]
1954     }
1955   } else if (N.getOpcode() == ISD::OR) {
1956     short imm = 0;
1957     if (isIntS16Immediate(N.getOperand(1), imm) &&
1958         (!Aligned || (imm & 3) == 0)) {
1959       // If this is an or of disjoint bitfields, we can codegen this as an add
1960       // (for better address arithmetic) if the LHS and RHS of the OR are
1961       // provably disjoint.
1962       KnownBits LHSKnown;
1963       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1964
1965       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1966         // If all of the bits are known zero on the LHS or RHS, the add won't
1967         // carry.
1968         if (FrameIndexSDNode *FI =
1969               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1970           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1971           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1972         } else {
1973           Base = N.getOperand(0);
1974         }
1975         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1976         return true;
1977       }
1978     }
1979   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1980     // Loading from a constant address.
1981
1982     // If this address fits entirely in a 16-bit sext immediate field, codegen
1983     // this as "d, 0"
1984     short Imm;
1985     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1986       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1987       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1988                              CN->getValueType(0));
1989       return true;
1990     }
1991
1992     // Handle 32-bit sext immediates with LIS + addr mode.
1993     if ((CN->getValueType(0) == MVT::i32 ||
1994          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1995         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1996       int Addr = (int)CN->getZExtValue();
1997
1998       // Otherwise, break this down into an LIS + disp.
1999       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2000
2001       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2002                                    MVT::i32);
2003       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2004       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2005       return true;
2006     }
2007   }
2008
2009   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2010   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2011     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2012     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2013   } else
2014     Base = N;
2015   return true;      // [r+0]
2016 }
2017
2018 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2019 /// represented as an indexed [r+r] operation.
2020 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2021                                                 SDValue &Index,
2022                                                 SelectionDAG &DAG) const {
2023   // Check to see if we can easily represent this as an [r+r] address.  This
2024   // will fail if it thinks that the address is more profitably represented as
2025   // reg+imm, e.g. where imm = 0.
2026   if (SelectAddressRegReg(N, Base, Index, DAG))
2027     return true;
2028
2029   // If the operand is an addition, always emit this as [r+r], since this is
2030   // better (for code size, and execution, as the memop does the add for free)
2031   // than emitting an explicit add.
2032   if (N.getOpcode() == ISD::ADD) {
2033     Base = N.getOperand(0);
2034     Index = N.getOperand(1);
2035     return true;
2036   }
2037
2038   // Otherwise, do it the hard way, using R0 as the base register.
2039   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2040                          N.getValueType());
2041   Index = N;
2042   return true;
2043 }
2044
2045 /// getPreIndexedAddressParts - returns true by value, base pointer and
2046 /// offset pointer and addressing mode by reference if the node's address
2047 /// can be legally represented as pre-indexed load / store address.
2048 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2049                                                   SDValue &Offset,
2050                                                   ISD::MemIndexedMode &AM,
2051                                                   SelectionDAG &DAG) const {
2052   if (DisablePPCPreinc) return false;
2053
2054   bool isLoad = true;
2055   SDValue Ptr;
2056   EVT VT;
2057   unsigned Alignment;
2058   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2059     Ptr = LD->getBasePtr();
2060     VT = LD->getMemoryVT();
2061     Alignment = LD->getAlignment();
2062   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2063     Ptr = ST->getBasePtr();
2064     VT  = ST->getMemoryVT();
2065     Alignment = ST->getAlignment();
2066     isLoad = false;
2067   } else
2068     return false;
2069
2070   // PowerPC doesn't have preinc load/store instructions for vectors (except
2071   // for QPX, which does have preinc r+r forms).
2072   if (VT.isVector()) {
2073     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2074       return false;
2075     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2076       AM = ISD::PRE_INC;
2077       return true;
2078     }
2079   }
2080
2081   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2082     // Common code will reject creating a pre-inc form if the base pointer
2083     // is a frame index, or if N is a store and the base pointer is either
2084     // the same as or a predecessor of the value being stored.  Check for
2085     // those situations here, and try with swapped Base/Offset instead.
2086     bool Swap = false;
2087
2088     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2089       Swap = true;
2090     else if (!isLoad) {
2091       SDValue Val = cast<StoreSDNode>(N)->getValue();
2092       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2093         Swap = true;
2094     }
2095
2096     if (Swap)
2097       std::swap(Base, Offset);
2098
2099     AM = ISD::PRE_INC;
2100     return true;
2101   }
2102
2103   // LDU/STU can only handle immediates that are a multiple of 4.
2104   if (VT != MVT::i64) {
2105     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2106       return false;
2107   } else {
2108     // LDU/STU need an address with at least 4-byte alignment.
2109     if (Alignment < 4)
2110       return false;
2111
2112     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2113       return false;
2114   }
2115
2116   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2117     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2118     // sext i32 to i64 when addr mode is r+i.
2119     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2120         LD->getExtensionType() == ISD::SEXTLOAD &&
2121         isa<ConstantSDNode>(Offset))
2122       return false;
2123   }
2124
2125   AM = ISD::PRE_INC;
2126   return true;
2127 }
2128
2129 //===----------------------------------------------------------------------===//
2130 //  LowerOperation implementation
2131 //===----------------------------------------------------------------------===//
2132
2133 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2134 /// and LoOpFlags to the target MO flags.
2135 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2136                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2137                                const GlobalValue *GV = nullptr) {
2138   HiOpFlags = PPCII::MO_HA;
2139   LoOpFlags = PPCII::MO_LO;
2140
2141   // Don't use the pic base if not in PIC relocation model.
2142   if (IsPIC) {
2143     HiOpFlags |= PPCII::MO_PIC_FLAG;
2144     LoOpFlags |= PPCII::MO_PIC_FLAG;
2145   }
2146
2147   // If this is a reference to a global value that requires a non-lazy-ptr, make
2148   // sure that instruction lowering adds it.
2149   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2150     HiOpFlags |= PPCII::MO_NLP_FLAG;
2151     LoOpFlags |= PPCII::MO_NLP_FLAG;
2152
2153     if (GV->hasHiddenVisibility()) {
2154       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2155       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2156     }
2157   }
2158 }
2159
2160 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2161                              SelectionDAG &DAG) {
2162   SDLoc DL(HiPart);
2163   EVT PtrVT = HiPart.getValueType();
2164   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2165
2166   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2167   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2168
2169   // With PIC, the first instruction is actually "GR+hi(&G)".
2170   if (isPIC)
2171     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2172                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2173
2174   // Generate non-pic code that has direct accesses to the constant pool.
2175   // The address of the global is just (hi(&g)+lo(&g)).
2176   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2177 }
2178
2179 static void setUsesTOCBasePtr(MachineFunction &MF) {
2180   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2181   FuncInfo->setUsesTOCBasePtr();
2182 }
2183
2184 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2185   setUsesTOCBasePtr(DAG.getMachineFunction());
2186 }
2187
2188 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2189                            SDValue GA) {
2190   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2191   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2192                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2193
2194   SDValue Ops[] = { GA, Reg };
2195   return DAG.getMemIntrinsicNode(
2196       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2197       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2198       false, 0);
2199 }
2200
2201 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2202                                              SelectionDAG &DAG) const {
2203   EVT PtrVT = Op.getValueType();
2204   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2205   const Constant *C = CP->getConstVal();
2206
2207   // 64-bit SVR4 ABI code is always position-independent.
2208   // The actual address of the GlobalValue is stored in the TOC.
2209   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2210     setUsesTOCBasePtr(DAG);
2211     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2212     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2213   }
2214
2215   unsigned MOHiFlag, MOLoFlag;
2216   bool IsPIC = isPositionIndependent();
2217   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2218
2219   if (IsPIC && Subtarget.isSVR4ABI()) {
2220     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2221                                            PPCII::MO_PIC_FLAG);
2222     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2223   }
2224
2225   SDValue CPIHi =
2226     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2227   SDValue CPILo =
2228     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2229   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2230 }
2231
2232 // For 64-bit PowerPC, prefer the more compact relative encodings.
2233 // This trades 32 bits per jump table entry for one or two instructions
2234 // on the jump site.
2235 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2236   if (isJumpTableRelative())
2237     return MachineJumpTableInfo::EK_LabelDifference32;
2238
2239   return TargetLowering::getJumpTableEncoding();
2240 }
2241
2242 bool PPCTargetLowering::isJumpTableRelative() const {
2243   if (Subtarget.isPPC64())
2244     return true;
2245   return TargetLowering::isJumpTableRelative();
2246 }
2247
2248 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2249                                                     SelectionDAG &DAG) const {
2250   if (!Subtarget.isPPC64())
2251     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2252
2253   switch (getTargetMachine().getCodeModel()) {
2254   case CodeModel::Default:
2255   case CodeModel::Small:
2256   case CodeModel::Medium:
2257     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2258   default:
2259     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2260                        getPointerTy(DAG.getDataLayout()));
2261   }
2262 }
2263
2264 const MCExpr *
2265 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2266                                                 unsigned JTI,
2267                                                 MCContext &Ctx) const {
2268   if (!Subtarget.isPPC64())
2269     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2270
2271   switch (getTargetMachine().getCodeModel()) {
2272   case CodeModel::Default:
2273   case CodeModel::Small:
2274   case CodeModel::Medium:
2275     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2276   default:
2277     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2278   }
2279 }
2280
2281 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2282   EVT PtrVT = Op.getValueType();
2283   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2284
2285   // 64-bit SVR4 ABI code is always position-independent.
2286   // The actual address of the GlobalValue is stored in the TOC.
2287   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2288     setUsesTOCBasePtr(DAG);
2289     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2290     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2291   }
2292
2293   unsigned MOHiFlag, MOLoFlag;
2294   bool IsPIC = isPositionIndependent();
2295   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2296
2297   if (IsPIC && Subtarget.isSVR4ABI()) {
2298     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2299                                         PPCII::MO_PIC_FLAG);
2300     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2301   }
2302
2303   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2304   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2305   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2306 }
2307
2308 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2309                                              SelectionDAG &DAG) const {
2310   EVT PtrVT = Op.getValueType();
2311   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2312   const BlockAddress *BA = BASDN->getBlockAddress();
2313
2314   // 64-bit SVR4 ABI code is always position-independent.
2315   // The actual BlockAddress is stored in the TOC.
2316   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2317     setUsesTOCBasePtr(DAG);
2318     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2319     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2320   }
2321
2322   unsigned MOHiFlag, MOLoFlag;
2323   bool IsPIC = isPositionIndependent();
2324   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2325   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2326   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2327   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2328 }
2329
2330 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2331                                               SelectionDAG &DAG) const {
2332   // FIXME: TLS addresses currently use medium model code sequences,
2333   // which is the most useful form.  Eventually support for small and
2334   // large models could be added if users need it, at the cost of
2335   // additional complexity.
2336   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2337   if (DAG.getTarget().Options.EmulatedTLS)
2338     return LowerToTLSEmulatedModel(GA, DAG);
2339
2340   SDLoc dl(GA);
2341   const GlobalValue *GV = GA->getGlobal();
2342   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2343   bool is64bit = Subtarget.isPPC64();
2344   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2345   PICLevel::Level picLevel = M->getPICLevel();
2346
2347   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2348
2349   if (Model == TLSModel::LocalExec) {
2350     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2351                                                PPCII::MO_TPREL_HA);
2352     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2353                                                PPCII::MO_TPREL_LO);
2354     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2355                                      is64bit ? MVT::i64 : MVT::i32);
2356     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2357     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2358   }
2359
2360   if (Model == TLSModel::InitialExec) {
2361     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2362     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2363                                                 PPCII::MO_TLS);
2364     SDValue GOTPtr;
2365     if (is64bit) {
2366       setUsesTOCBasePtr(DAG);
2367       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2368       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2369                            PtrVT, GOTReg, TGA);
2370     } else
2371       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2372     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2373                                    PtrVT, TGA, GOTPtr);
2374     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2375   }
2376
2377   if (Model == TLSModel::GeneralDynamic) {
2378     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2379     SDValue GOTPtr;
2380     if (is64bit) {
2381       setUsesTOCBasePtr(DAG);
2382       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2383       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2384                                    GOTReg, TGA);
2385     } else {
2386       if (picLevel == PICLevel::SmallPIC)
2387         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2388       else
2389         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2390     }
2391     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2392                        GOTPtr, TGA, TGA);
2393   }
2394
2395   if (Model == TLSModel::LocalDynamic) {
2396     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2397     SDValue GOTPtr;
2398     if (is64bit) {
2399       setUsesTOCBasePtr(DAG);
2400       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2401       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2402                            GOTReg, TGA);
2403     } else {
2404       if (picLevel == PICLevel::SmallPIC)
2405         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2406       else
2407         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2408     }
2409     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2410                                   PtrVT, GOTPtr, TGA, TGA);
2411     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2412                                       PtrVT, TLSAddr, TGA);
2413     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2414   }
2415
2416   llvm_unreachable("Unknown TLS model!");
2417 }
2418
2419 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2420                                               SelectionDAG &DAG) const {
2421   EVT PtrVT = Op.getValueType();
2422   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2423   SDLoc DL(GSDN);
2424   const GlobalValue *GV = GSDN->getGlobal();
2425
2426   // 64-bit SVR4 ABI code is always position-independent.
2427   // The actual address of the GlobalValue is stored in the TOC.
2428   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2429     setUsesTOCBasePtr(DAG);
2430     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2431     return getTOCEntry(DAG, DL, true, GA);
2432   }
2433
2434   unsigned MOHiFlag, MOLoFlag;
2435   bool IsPIC = isPositionIndependent();
2436   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2437
2438   if (IsPIC && Subtarget.isSVR4ABI()) {
2439     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2440                                             GSDN->getOffset(),
2441                                             PPCII::MO_PIC_FLAG);
2442     return getTOCEntry(DAG, DL, false, GA);
2443   }
2444
2445   SDValue GAHi =
2446     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2447   SDValue GALo =
2448     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2449
2450   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2451
2452   // If the global reference is actually to a non-lazy-pointer, we have to do an
2453   // extra load to get the address of the global.
2454   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2455     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2456   return Ptr;
2457 }
2458
2459 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2460   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2461   SDLoc dl(Op);
2462
2463   if (Op.getValueType() == MVT::v2i64) {
2464     // When the operands themselves are v2i64 values, we need to do something
2465     // special because VSX has no underlying comparison operations for these.
2466     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2467       // Equality can be handled by casting to the legal type for Altivec
2468       // comparisons, everything else needs to be expanded.
2469       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2470         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2471                  DAG.getSetCC(dl, MVT::v4i32,
2472                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2473                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2474                    CC));
2475       }
2476
2477       return SDValue();
2478     }
2479
2480     // We handle most of these in the usual way.
2481     return Op;
2482   }
2483
2484   // If we're comparing for equality to zero, expose the fact that this is
2485   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2486   // fold the new nodes.
2487   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2488     return V;
2489
2490   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2491     // Leave comparisons against 0 and -1 alone for now, since they're usually
2492     // optimized.  FIXME: revisit this when we can custom lower all setcc
2493     // optimizations.
2494     if (C->isAllOnesValue() || C->isNullValue())
2495       return SDValue();
2496   }
2497
2498   // If we have an integer seteq/setne, turn it into a compare against zero
2499   // by xor'ing the rhs with the lhs, which is faster than setting a
2500   // condition register, reading it back out, and masking the correct bit.  The
2501   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2502   // the result to other bit-twiddling opportunities.
2503   EVT LHSVT = Op.getOperand(0).getValueType();
2504   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2505     EVT VT = Op.getValueType();
2506     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2507                                 Op.getOperand(1));
2508     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2509   }
2510   return SDValue();
2511 }
2512
2513 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2514   SDNode *Node = Op.getNode();
2515   EVT VT = Node->getValueType(0);
2516   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2517   SDValue InChain = Node->getOperand(0);
2518   SDValue VAListPtr = Node->getOperand(1);
2519   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2520   SDLoc dl(Node);
2521
2522   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2523
2524   // gpr_index
2525   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2526                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2527   InChain = GprIndex.getValue(1);
2528
2529   if (VT == MVT::i64) {
2530     // Check if GprIndex is even
2531     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2532                                  DAG.getConstant(1, dl, MVT::i32));
2533     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2534                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2535     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2536                                           DAG.getConstant(1, dl, MVT::i32));
2537     // Align GprIndex to be even if it isn't
2538     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2539                            GprIndex);
2540   }
2541
2542   // fpr index is 1 byte after gpr
2543   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2544                                DAG.getConstant(1, dl, MVT::i32));
2545
2546   // fpr
2547   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2548                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2549   InChain = FprIndex.getValue(1);
2550
2551   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2552                                        DAG.getConstant(8, dl, MVT::i32));
2553
2554   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2555                                         DAG.getConstant(4, dl, MVT::i32));
2556
2557   // areas
2558   SDValue OverflowArea =
2559       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2560   InChain = OverflowArea.getValue(1);
2561
2562   SDValue RegSaveArea =
2563       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2564   InChain = RegSaveArea.getValue(1);
2565
2566   // select overflow_area if index > 8
2567   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2568                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2569
2570   // adjustment constant gpr_index * 4/8
2571   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2572                                     VT.isInteger() ? GprIndex : FprIndex,
2573                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2574                                                     MVT::i32));
2575
2576   // OurReg = RegSaveArea + RegConstant
2577   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2578                                RegConstant);
2579
2580   // Floating types are 32 bytes into RegSaveArea
2581   if (VT.isFloatingPoint())
2582     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2583                          DAG.getConstant(32, dl, MVT::i32));
2584
2585   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2586   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2587                                    VT.isInteger() ? GprIndex : FprIndex,
2588                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2589                                                    MVT::i32));
2590
2591   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2592                               VT.isInteger() ? VAListPtr : FprPtr,
2593                               MachinePointerInfo(SV), MVT::i8);
2594
2595   // determine if we should load from reg_save_area or overflow_area
2596   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2597
2598   // increase overflow_area by 4/8 if gpr/fpr > 8
2599   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2600                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2601                                           dl, MVT::i32));
2602
2603   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2604                              OverflowAreaPlusN);
2605
2606   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2607                               MachinePointerInfo(), MVT::i32);
2608
2609   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2610 }
2611
2612 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2613   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2614
2615   // We have to copy the entire va_list struct:
2616   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2617   return DAG.getMemcpy(Op.getOperand(0), Op,
2618                        Op.getOperand(1), Op.getOperand(2),
2619                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2620                        false, MachinePointerInfo(), MachinePointerInfo());
2621 }
2622
2623 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2624                                                   SelectionDAG &DAG) const {
2625   return Op.getOperand(0);
2626 }
2627
2628 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2629                                                 SelectionDAG &DAG) const {
2630   SDValue Chain = Op.getOperand(0);
2631   SDValue Trmp = Op.getOperand(1); // trampoline
2632   SDValue FPtr = Op.getOperand(2); // nested function
2633   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2634   SDLoc dl(Op);
2635
2636   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2637   bool isPPC64 = (PtrVT == MVT::i64);
2638   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2639
2640   TargetLowering::ArgListTy Args;
2641   TargetLowering::ArgListEntry Entry;
2642
2643   Entry.Ty = IntPtrTy;
2644   Entry.Node = Trmp; Args.push_back(Entry);
2645
2646   // TrampSize == (isPPC64 ? 48 : 40);
2647   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2648                                isPPC64 ? MVT::i64 : MVT::i32);
2649   Args.push_back(Entry);
2650
2651   Entry.Node = FPtr; Args.push_back(Entry);
2652   Entry.Node = Nest; Args.push_back(Entry);
2653
2654   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2655   TargetLowering::CallLoweringInfo CLI(DAG);
2656   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2657       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2658       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2659
2660   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2661   return CallResult.second;
2662 }
2663
2664 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2665   MachineFunction &MF = DAG.getMachineFunction();
2666   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2667   EVT PtrVT = getPointerTy(MF.getDataLayout());
2668
2669   SDLoc dl(Op);
2670
2671   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2672     // vastart just stores the address of the VarArgsFrameIndex slot into the
2673     // memory location argument.
2674     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2675     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2676     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2677                         MachinePointerInfo(SV));
2678   }
2679
2680   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2681   // We suppose the given va_list is already allocated.
2682   //
2683   // typedef struct {
2684   //  char gpr;     /* index into the array of 8 GPRs
2685   //                 * stored in the register save area
2686   //                 * gpr=0 corresponds to r3,
2687   //                 * gpr=1 to r4, etc.
2688   //                 */
2689   //  char fpr;     /* index into the array of 8 FPRs
2690   //                 * stored in the register save area
2691   //                 * fpr=0 corresponds to f1,
2692   //                 * fpr=1 to f2, etc.
2693   //                 */
2694   //  char *overflow_arg_area;
2695   //                /* location on stack that holds
2696   //                 * the next overflow argument
2697   //                 */
2698   //  char *reg_save_area;
2699   //               /* where r3:r10 and f1:f8 (if saved)
2700   //                * are stored
2701   //                */
2702   // } va_list[1];
2703
2704   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2705   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2706   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2707                                             PtrVT);
2708   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2709                                  PtrVT);
2710
2711   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2712   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2713
2714   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2715   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2716
2717   uint64_t FPROffset = 1;
2718   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2719
2720   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2721
2722   // Store first byte : number of int regs
2723   SDValue firstStore =
2724       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2725                         MachinePointerInfo(SV), MVT::i8);
2726   uint64_t nextOffset = FPROffset;
2727   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2728                                   ConstFPROffset);
2729
2730   // Store second byte : number of float regs
2731   SDValue secondStore =
2732       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2733                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2734   nextOffset += StackOffset;
2735   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2736
2737   // Store second word : arguments given on stack
2738   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2739                                     MachinePointerInfo(SV, nextOffset));
2740   nextOffset += FrameOffset;
2741   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2742
2743   // Store third word : arguments given in registers
2744   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2745                       MachinePointerInfo(SV, nextOffset));
2746 }
2747
2748 #include "PPCGenCallingConv.inc"
2749
2750 // Function whose sole purpose is to kill compiler warnings
2751 // stemming from unused functions included from PPCGenCallingConv.inc.
2752 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2753   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2754 }
2755
2756 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2757                                       CCValAssign::LocInfo &LocInfo,
2758                                       ISD::ArgFlagsTy &ArgFlags,
2759                                       CCState &State) {
2760   return true;
2761 }
2762
2763 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2764                                              MVT &LocVT,
2765                                              CCValAssign::LocInfo &LocInfo,
2766                                              ISD::ArgFlagsTy &ArgFlags,
2767                                              CCState &State) {
2768   static const MCPhysReg ArgRegs[] = {
2769     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2770     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2771   };
2772   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2773
2774   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2775
2776   // Skip one register if the first unallocated register has an even register
2777   // number and there are still argument registers available which have not been
2778   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2779   // need to skip a register if RegNum is odd.
2780   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2781     State.AllocateReg(ArgRegs[RegNum]);
2782   }
2783
2784   // Always return false here, as this function only makes sure that the first
2785   // unallocated register has an odd register number and does not actually
2786   // allocate a register for the current argument.
2787   return false;
2788 }
2789
2790 bool
2791 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2792                                                   MVT &LocVT,
2793                                                   CCValAssign::LocInfo &LocInfo,
2794                                                   ISD::ArgFlagsTy &ArgFlags,
2795                                                   CCState &State) {
2796   static const MCPhysReg ArgRegs[] = {
2797     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2798     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2799   };
2800   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2801
2802   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2803   int RegsLeft = NumArgRegs - RegNum;
2804
2805   // Skip if there is not enough registers left for long double type (4 gpr regs
2806   // in soft float mode) and put long double argument on the stack.
2807   if (RegNum != NumArgRegs && RegsLeft < 4) {
2808     for (int i = 0; i < RegsLeft; i++) {
2809       State.AllocateReg(ArgRegs[RegNum + i]);
2810     }
2811   }
2812
2813   return false;
2814 }
2815
2816 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2817                                                MVT &LocVT,
2818                                                CCValAssign::LocInfo &LocInfo,
2819                                                ISD::ArgFlagsTy &ArgFlags,
2820                                                CCState &State) {
2821   static const MCPhysReg ArgRegs[] = {
2822     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2823     PPC::F8
2824   };
2825
2826   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2827
2828   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2829
2830   // If there is only one Floating-point register left we need to put both f64
2831   // values of a split ppc_fp128 value on the stack.
2832   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2833     State.AllocateReg(ArgRegs[RegNum]);
2834   }
2835
2836   // Always return false here, as this function only makes sure that the two f64
2837   // values a ppc_fp128 value is split into are both passed in registers or both
2838   // passed on the stack and does not actually allocate a register for the
2839   // current argument.
2840   return false;
2841 }
2842
2843 /// FPR - The set of FP registers that should be allocated for arguments,
2844 /// on Darwin.
2845 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2846                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2847                                 PPC::F11, PPC::F12, PPC::F13};
2848
2849 /// QFPR - The set of QPX registers that should be allocated for arguments.
2850 static const MCPhysReg QFPR[] = {
2851     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2852     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2853
2854 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2855 /// the stack.
2856 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2857                                        unsigned PtrByteSize) {
2858   unsigned ArgSize = ArgVT.getStoreSize();
2859   if (Flags.isByVal())
2860     ArgSize = Flags.getByValSize();
2861
2862   // Round up to multiples of the pointer size, except for array members,
2863   // which are always packed.
2864   if (!Flags.isInConsecutiveRegs())
2865     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2866
2867   return ArgSize;
2868 }
2869
2870 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2871 /// on the stack.
2872 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2873                                             ISD::ArgFlagsTy Flags,
2874                                             unsigned PtrByteSize) {
2875   unsigned Align = PtrByteSize;
2876
2877   // Altivec parameters are padded to a 16 byte boundary.
2878   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2879       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2880       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2881       ArgVT == MVT::v1i128)
2882     Align = 16;
2883   // QPX vector types stored in double-precision are padded to a 32 byte
2884   // boundary.
2885   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2886     Align = 32;
2887
2888   // ByVal parameters are aligned as requested.
2889   if (Flags.isByVal()) {
2890     unsigned BVAlign = Flags.getByValAlign();
2891     if (BVAlign > PtrByteSize) {
2892       if (BVAlign % PtrByteSize != 0)
2893           llvm_unreachable(
2894             "ByVal alignment is not a multiple of the pointer size");
2895
2896       Align = BVAlign;
2897     }
2898   }
2899
2900   // Array members are always packed to their original alignment.
2901   if (Flags.isInConsecutiveRegs()) {
2902     // If the array member was split into multiple registers, the first
2903     // needs to be aligned to the size of the full type.  (Except for
2904     // ppcf128, which is only aligned as its f64 components.)
2905     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2906       Align = OrigVT.getStoreSize();
2907     else
2908       Align = ArgVT.getStoreSize();
2909   }
2910
2911   return Align;
2912 }
2913
2914 /// CalculateStackSlotUsed - Return whether this argument will use its
2915 /// stack slot (instead of being passed in registers).  ArgOffset,
2916 /// AvailableFPRs, and AvailableVRs must hold the current argument
2917 /// position, and will be updated to account for this argument.
2918 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2919                                    ISD::ArgFlagsTy Flags,
2920                                    unsigned PtrByteSize,
2921                                    unsigned LinkageSize,
2922                                    unsigned ParamAreaSize,
2923                                    unsigned &ArgOffset,
2924                                    unsigned &AvailableFPRs,
2925                                    unsigned &AvailableVRs, bool HasQPX) {
2926   bool UseMemory = false;
2927
2928   // Respect alignment of argument on the stack.
2929   unsigned Align =
2930     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2931   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2932   // If there's no space left in the argument save area, we must
2933   // use memory (this check also catches zero-sized arguments).
2934   if (ArgOffset >= LinkageSize + ParamAreaSize)
2935     UseMemory = true;
2936
2937   // Allocate argument on the stack.
2938   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2939   if (Flags.isInConsecutiveRegsLast())
2940     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2941   // If we overran the argument save area, we must use memory
2942   // (this check catches arguments passed partially in memory)
2943   if (ArgOffset > LinkageSize + ParamAreaSize)
2944     UseMemory = true;
2945
2946   // However, if the argument is actually passed in an FPR or a VR,
2947   // we don't use memory after all.
2948   if (!Flags.isByVal()) {
2949     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2950         // QPX registers overlap with the scalar FP registers.
2951         (HasQPX && (ArgVT == MVT::v4f32 ||
2952                     ArgVT == MVT::v4f64 ||
2953                     ArgVT == MVT::v4i1)))
2954       if (AvailableFPRs > 0) {
2955         --AvailableFPRs;
2956         return false;
2957       }
2958     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2959         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2960         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2961         ArgVT == MVT::v1i128)
2962       if (AvailableVRs > 0) {
2963         --AvailableVRs;
2964         return false;
2965       }
2966   }
2967
2968   return UseMemory;
2969 }
2970
2971 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2972 /// ensure minimum alignment required for target.
2973 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2974                                      unsigned NumBytes) {
2975   unsigned TargetAlign = Lowering->getStackAlignment();
2976   unsigned AlignMask = TargetAlign - 1;
2977   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2978   return NumBytes;
2979 }
2980
2981 SDValue PPCTargetLowering::LowerFormalArguments(
2982     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2983     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2984     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2985   if (Subtarget.isSVR4ABI()) {
2986     if (Subtarget.isPPC64())
2987       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2988                                          dl, DAG, InVals);
2989     else
2990       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2991                                          dl, DAG, InVals);
2992   } else {
2993     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2994                                        dl, DAG, InVals);
2995   }
2996 }
2997
2998 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2999     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3000     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3001     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3002
3003   // 32-bit SVR4 ABI Stack Frame Layout:
3004   //              +-----------------------------------+
3005   //        +-->  |            Back chain             |
3006   //        |     +-----------------------------------+
3007   //        |     | Floating-point register save area |
3008   //        |     +-----------------------------------+
3009   //        |     |    General register save area     |
3010   //        |     +-----------------------------------+
3011   //        |     |          CR save word             |
3012   //        |     +-----------------------------------+
3013   //        |     |         VRSAVE save word          |
3014   //        |     +-----------------------------------+
3015   //        |     |         Alignment padding         |
3016   //        |     +-----------------------------------+
3017   //        |     |     Vector register save area     |
3018   //        |     +-----------------------------------+
3019   //        |     |       Local variable space        |
3020   //        |     +-----------------------------------+
3021   //        |     |        Parameter list area        |
3022   //        |     +-----------------------------------+
3023   //        |     |           LR save word            |
3024   //        |     +-----------------------------------+
3025   // SP-->  +---  |            Back chain             |
3026   //              +-----------------------------------+
3027   //
3028   // Specifications:
3029   //   System V Application Binary Interface PowerPC Processor Supplement
3030   //   AltiVec Technology Programming Interface Manual
3031
3032   MachineFunction &MF = DAG.getMachineFunction();
3033   MachineFrameInfo &MFI = MF.getFrameInfo();
3034   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3035
3036   EVT PtrVT = getPointerTy(MF.getDataLayout());
3037   // Potential tail calls could cause overwriting of argument stack slots.
3038   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3039                        (CallConv == CallingConv::Fast));
3040   unsigned PtrByteSize = 4;
3041
3042   // Assign locations to all of the incoming arguments.
3043   SmallVector<CCValAssign, 16> ArgLocs;
3044   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3045                  *DAG.getContext());
3046
3047   // Reserve space for the linkage area on the stack.
3048   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3049   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3050   if (useSoftFloat())
3051     CCInfo.PreAnalyzeFormalArguments(Ins);
3052
3053   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3054   CCInfo.clearWasPPCF128();
3055
3056   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3057     CCValAssign &VA = ArgLocs[i];
3058
3059     // Arguments stored in registers.
3060     if (VA.isRegLoc()) {
3061       const TargetRegisterClass *RC;
3062       EVT ValVT = VA.getValVT();
3063
3064       switch (ValVT.getSimpleVT().SimpleTy) {
3065         default:
3066           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3067         case MVT::i1:
3068         case MVT::i32:
3069           RC = &PPC::GPRCRegClass;
3070           break;
3071         case MVT::f32:
3072           if (Subtarget.hasP8Vector())
3073             RC = &PPC::VSSRCRegClass;
3074           else
3075             RC = &PPC::F4RCRegClass;
3076           break;
3077         case MVT::f64:
3078           if (Subtarget.hasVSX())
3079             RC = &PPC::VSFRCRegClass;
3080           else
3081             RC = &PPC::F8RCRegClass;
3082           break;
3083         case MVT::v16i8:
3084         case MVT::v8i16:
3085         case MVT::v4i32:
3086           RC = &PPC::VRRCRegClass;
3087           break;
3088         case MVT::v4f32:
3089           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3090           break;
3091         case MVT::v2f64:
3092         case MVT::v2i64:
3093           RC = &PPC::VRRCRegClass;
3094           break;
3095         case MVT::v4f64:
3096           RC = &PPC::QFRCRegClass;
3097           break;
3098         case MVT::v4i1:
3099           RC = &PPC::QBRCRegClass;
3100           break;
3101       }
3102
3103       // Transform the arguments stored in physical registers into virtual ones.
3104       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3105       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3106                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3107
3108       if (ValVT == MVT::i1)
3109         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3110
3111       InVals.push_back(ArgValue);
3112     } else {
3113       // Argument stored in memory.
3114       assert(VA.isMemLoc());
3115
3116       unsigned ArgSize = VA.getLocVT().getStoreSize();
3117       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3118                                      isImmutable);
3119
3120       // Create load nodes to retrieve arguments from the stack.
3121       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3122       InVals.push_back(
3123           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3124     }
3125   }
3126
3127   // Assign locations to all of the incoming aggregate by value arguments.
3128   // Aggregates passed by value are stored in the local variable space of the
3129   // caller's stack frame, right above the parameter list area.
3130   SmallVector<CCValAssign, 16> ByValArgLocs;
3131   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3132                       ByValArgLocs, *DAG.getContext());
3133
3134   // Reserve stack space for the allocations in CCInfo.
3135   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3136
3137   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3138
3139   // Area that is at least reserved in the caller of this function.
3140   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3141   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3142
3143   // Set the size that is at least reserved in caller of this function.  Tail
3144   // call optimized function's reserved stack space needs to be aligned so that
3145   // taking the difference between two stack areas will result in an aligned
3146   // stack.
3147   MinReservedArea =
3148       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3149   FuncInfo->setMinReservedArea(MinReservedArea);
3150
3151   SmallVector<SDValue, 8> MemOps;
3152
3153   // If the function takes variable number of arguments, make a frame index for
3154   // the start of the first vararg value... for expansion of llvm.va_start.
3155   if (isVarArg) {
3156     static const MCPhysReg GPArgRegs[] = {
3157       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3158       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3159     };
3160     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3161
3162     static const MCPhysReg FPArgRegs[] = {
3163       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3164       PPC::F8
3165     };
3166     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3167
3168     if (useSoftFloat())
3169        NumFPArgRegs = 0;
3170
3171     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3172     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3173
3174     // Make room for NumGPArgRegs and NumFPArgRegs.
3175     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3176                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3177
3178     FuncInfo->setVarArgsStackOffset(
3179       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3180                             CCInfo.getNextStackOffset(), true));
3181
3182     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3183     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3184
3185     // The fixed integer arguments of a variadic function are stored to the
3186     // VarArgsFrameIndex on the stack so that they may be loaded by
3187     // dereferencing the result of va_next.
3188     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3189       // Get an existing live-in vreg, or add a new one.
3190       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3191       if (!VReg)
3192         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3193
3194       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3195       SDValue Store =
3196           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3197       MemOps.push_back(Store);
3198       // Increment the address by four for the next argument to store
3199       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3200       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3201     }
3202
3203     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3204     // is set.
3205     // The double arguments are stored to the VarArgsFrameIndex
3206     // on the stack.
3207     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3208       // Get an existing live-in vreg, or add a new one.
3209       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3210       if (!VReg)
3211         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3212
3213       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3214       SDValue Store =
3215           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3216       MemOps.push_back(Store);
3217       // Increment the address by eight for the next argument to store
3218       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3219                                          PtrVT);
3220       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3221     }
3222   }
3223
3224   if (!MemOps.empty())
3225     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3226
3227   return Chain;
3228 }
3229
3230 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3231 // value to MVT::i64 and then truncate to the correct register size.
3232 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3233                                              EVT ObjectVT, SelectionDAG &DAG,
3234                                              SDValue ArgVal,
3235                                              const SDLoc &dl) const {
3236   if (Flags.isSExt())
3237     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3238                          DAG.getValueType(ObjectVT));
3239   else if (Flags.isZExt())
3240     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3241                          DAG.getValueType(ObjectVT));
3242
3243   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3244 }
3245
3246 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3247     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3248     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3249     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3250   // TODO: add description of PPC stack frame format, or at least some docs.
3251   //
3252   bool isELFv2ABI = Subtarget.isELFv2ABI();
3253   bool isLittleEndian = Subtarget.isLittleEndian();
3254   MachineFunction &MF = DAG.getMachineFunction();
3255   MachineFrameInfo &MFI = MF.getFrameInfo();
3256   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3257
3258   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3259          "fastcc not supported on varargs functions");
3260
3261   EVT PtrVT = getPointerTy(MF.getDataLayout());
3262   // Potential tail calls could cause overwriting of argument stack slots.
3263   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3264                        (CallConv == CallingConv::Fast));
3265   unsigned PtrByteSize = 8;
3266   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3267
3268   static const MCPhysReg GPR[] = {
3269     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3270     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3271   };
3272   static const MCPhysReg VR[] = {
3273     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3274     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3275   };
3276
3277   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3278   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3279   const unsigned Num_VR_Regs  = array_lengthof(VR);
3280   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3281
3282   // Do a first pass over the arguments to determine whether the ABI
3283   // guarantees that our caller has allocated the parameter save area
3284   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3285   // in the ELFv2 ABI, it is true if this is a vararg function or if
3286   // any parameter is located in a stack slot.
3287
3288   bool HasParameterArea = !isELFv2ABI || isVarArg;
3289   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3290   unsigned NumBytes = LinkageSize;
3291   unsigned AvailableFPRs = Num_FPR_Regs;
3292   unsigned AvailableVRs = Num_VR_Regs;
3293   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3294     if (Ins[i].Flags.isNest())
3295       continue;
3296
3297     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3298                                PtrByteSize, LinkageSize, ParamAreaSize,
3299                                NumBytes, AvailableFPRs, AvailableVRs,
3300                                Subtarget.hasQPX()))
3301       HasParameterArea = true;
3302   }
3303
3304   // Add DAG nodes to load the arguments or copy them out of registers.  On
3305   // entry to a function on PPC, the arguments start after the linkage area,
3306   // although the first ones are often in registers.
3307
3308   unsigned ArgOffset = LinkageSize;
3309   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3310   unsigned &QFPR_idx = FPR_idx;
3311   SmallVector<SDValue, 8> MemOps;
3312   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3313   unsigned CurArgIdx = 0;
3314   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3315     SDValue ArgVal;
3316     bool needsLoad = false;
3317     EVT ObjectVT = Ins[ArgNo].VT;
3318     EVT OrigVT = Ins[ArgNo].ArgVT;
3319     unsigned ObjSize = ObjectVT.getStoreSize();
3320     unsigned ArgSize = ObjSize;
3321     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3322     if (Ins[ArgNo].isOrigArg()) {
3323       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3324       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3325     }
3326     // We re-align the argument offset for each argument, except when using the
3327     // fast calling convention, when we need to make sure we do that only when
3328     // we'll actually use a stack slot.
3329     unsigned CurArgOffset, Align;
3330     auto ComputeArgOffset = [&]() {
3331       /* Respect alignment of argument on the stack.  */
3332       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3333       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3334       CurArgOffset = ArgOffset;
3335     };
3336
3337     if (CallConv != CallingConv::Fast) {
3338       ComputeArgOffset();
3339
3340       /* Compute GPR index associated with argument offset.  */
3341       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3342       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3343     }
3344
3345     // FIXME the codegen can be much improved in some cases.
3346     // We do not have to keep everything in memory.
3347     if (Flags.isByVal()) {
3348       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3349
3350       if (CallConv == CallingConv::Fast)
3351         ComputeArgOffset();
3352
3353       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3354       ObjSize = Flags.getByValSize();
3355       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3356       // Empty aggregate parameters do not take up registers.  Examples:
3357       //   struct { } a;
3358       //   union  { } b;
3359       //   int c[0];
3360       // etc.  However, we have to provide a place-holder in InVals, so
3361       // pretend we have an 8-byte item at the current address for that
3362       // purpose.
3363       if (!ObjSize) {
3364         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3365         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3366         InVals.push_back(FIN);
3367         continue;
3368       }
3369
3370       // Create a stack object covering all stack doublewords occupied
3371       // by the argument.  If the argument is (fully or partially) on
3372       // the stack, or if the argument is fully in registers but the
3373       // caller has allocated the parameter save anyway, we can refer
3374       // directly to the caller's stack frame.  Otherwise, create a
3375       // local copy in our own frame.
3376       int FI;
3377       if (HasParameterArea ||
3378           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3379         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3380       else
3381         FI = MFI.CreateStackObject(ArgSize, Align, false);
3382       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3383
3384       // Handle aggregates smaller than 8 bytes.
3385       if (ObjSize < PtrByteSize) {
3386         // The value of the object is its address, which differs from the
3387         // address of the enclosing doubleword on big-endian systems.
3388         SDValue Arg = FIN;
3389         if (!isLittleEndian) {
3390           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3391           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3392         }
3393         InVals.push_back(Arg);
3394
3395         if (GPR_idx != Num_GPR_Regs) {
3396           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3397           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3398           SDValue Store;
3399
3400           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3401             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3402                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3403             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3404                                       MachinePointerInfo(&*FuncArg), ObjType);
3405           } else {
3406             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3407             // store the whole register as-is to the parameter save area
3408             // slot.
3409             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3410                                  MachinePointerInfo(&*FuncArg));
3411           }
3412
3413           MemOps.push_back(Store);
3414         }
3415         // Whether we copied from a register or not, advance the offset
3416         // into the parameter save area by a full doubleword.
3417         ArgOffset += PtrByteSize;
3418         continue;
3419       }
3420
3421       // The value of the object is its address, which is the address of
3422       // its first stack doubleword.
3423       InVals.push_back(FIN);
3424
3425       // Store whatever pieces of the object are in registers to memory.
3426       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3427         if (GPR_idx == Num_GPR_Regs)
3428           break;
3429
3430         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3431         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3432         SDValue Addr = FIN;
3433         if (j) {
3434           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3435           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3436         }
3437         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3438                                      MachinePointerInfo(&*FuncArg, j));
3439         MemOps.push_back(Store);
3440         ++GPR_idx;
3441       }
3442       ArgOffset += ArgSize;
3443       continue;
3444     }
3445
3446     switch (ObjectVT.getSimpleVT().SimpleTy) {
3447     default: llvm_unreachable("Unhandled argument type!");
3448     case MVT::i1:
3449     case MVT::i32:
3450     case MVT::i64:
3451       if (Flags.isNest()) {
3452         // The 'nest' parameter, if any, is passed in R11.
3453         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3454         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3455
3456         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3457           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3458
3459         break;
3460       }
3461
3462       // These can be scalar arguments or elements of an integer array type
3463       // passed directly.  Clang may use those instead of "byval" aggregate
3464       // types to avoid forcing arguments to memory unnecessarily.
3465       if (GPR_idx != Num_GPR_Regs) {
3466         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3467         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3468
3469         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3470           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3471           // value to MVT::i64 and then truncate to the correct register size.
3472           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3473       } else {
3474         if (CallConv == CallingConv::Fast)
3475           ComputeArgOffset();
3476
3477         needsLoad = true;
3478         ArgSize = PtrByteSize;
3479       }
3480       if (CallConv != CallingConv::Fast || needsLoad)
3481         ArgOffset += 8;
3482       break;
3483
3484     case MVT::f32:
3485     case MVT::f64:
3486       // These can be scalar arguments or elements of a float array type
3487       // passed directly.  The latter are used to implement ELFv2 homogenous
3488       // float aggregates.
3489       if (FPR_idx != Num_FPR_Regs) {
3490         unsigned VReg;
3491
3492         if (ObjectVT == MVT::f32)
3493           VReg = MF.addLiveIn(FPR[FPR_idx],
3494                               Subtarget.hasP8Vector()
3495                                   ? &PPC::VSSRCRegClass
3496                                   : &PPC::F4RCRegClass);
3497         else
3498           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3499                                                 ? &PPC::VSFRCRegClass
3500                                                 : &PPC::F8RCRegClass);
3501
3502         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3503         ++FPR_idx;
3504       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3505         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3506         // once we support fp <-> gpr moves.
3507
3508         // This can only ever happen in the presence of f32 array types,
3509         // since otherwise we never run out of FPRs before running out
3510         // of GPRs.
3511         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3512         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3513
3514         if (ObjectVT == MVT::f32) {
3515           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3516             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3517                                  DAG.getConstant(32, dl, MVT::i32));
3518           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3519         }
3520
3521         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3522       } else {
3523         if (CallConv == CallingConv::Fast)
3524           ComputeArgOffset();
3525
3526         needsLoad = true;
3527       }
3528
3529       // When passing an array of floats, the array occupies consecutive
3530       // space in the argument area; only round up to the next doubleword
3531       // at the end of the array.  Otherwise, each float takes 8 bytes.
3532       if (CallConv != CallingConv::Fast || needsLoad) {
3533         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3534         ArgOffset += ArgSize;
3535         if (Flags.isInConsecutiveRegsLast())
3536           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3537       }
3538       break;
3539     case MVT::v4f32:
3540     case MVT::v4i32:
3541     case MVT::v8i16:
3542     case MVT::v16i8:
3543     case MVT::v2f64:
3544     case MVT::v2i64:
3545     case MVT::v1i128:
3546       if (!Subtarget.hasQPX()) {
3547       // These can be scalar arguments or elements of a vector array type
3548       // passed directly.  The latter are used to implement ELFv2 homogenous
3549       // vector aggregates.
3550       if (VR_idx != Num_VR_Regs) {
3551         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3552         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3553         ++VR_idx;
3554       } else {
3555         if (CallConv == CallingConv::Fast)
3556           ComputeArgOffset();
3557
3558         needsLoad = true;
3559       }
3560       if (CallConv != CallingConv::Fast || needsLoad)
3561         ArgOffset += 16;
3562       break;
3563       } // not QPX
3564
3565       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3566              "Invalid QPX parameter type");
3567       /* fall through */
3568
3569     case MVT::v4f64:
3570     case MVT::v4i1:
3571       // QPX vectors are treated like their scalar floating-point subregisters
3572       // (except that they're larger).
3573       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3574       if (QFPR_idx != Num_QFPR_Regs) {
3575         const TargetRegisterClass *RC;
3576         switch (ObjectVT.getSimpleVT().SimpleTy) {
3577         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3578         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3579         default:         RC = &PPC::QBRCRegClass; break;
3580         }
3581
3582         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3583         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3584         ++QFPR_idx;
3585       } else {
3586         if (CallConv == CallingConv::Fast)
3587           ComputeArgOffset();
3588         needsLoad = true;
3589       }
3590       if (CallConv != CallingConv::Fast || needsLoad)
3591         ArgOffset += Sz;
3592       break;
3593     }
3594
3595     // We need to load the argument to a virtual register if we determined
3596     // above that we ran out of physical registers of the appropriate type.
3597     if (needsLoad) {
3598       if (ObjSize < ArgSize && !isLittleEndian)
3599         CurArgOffset += ArgSize - ObjSize;
3600       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3601       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3602       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3603     }
3604
3605     InVals.push_back(ArgVal);
3606   }
3607
3608   // Area that is at least reserved in the caller of this function.
3609   unsigned MinReservedArea;
3610   if (HasParameterArea)
3611     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3612   else
3613     MinReservedArea = LinkageSize;
3614
3615   // Set the size that is at least reserved in caller of this function.  Tail
3616   // call optimized functions' reserved stack space needs to be aligned so that
3617   // taking the difference between two stack areas will result in an aligned
3618   // stack.
3619   MinReservedArea =
3620       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3621   FuncInfo->setMinReservedArea(MinReservedArea);
3622
3623   // If the function takes variable number of arguments, make a frame index for
3624   // the start of the first vararg value... for expansion of llvm.va_start.
3625   if (isVarArg) {
3626     int Depth = ArgOffset;
3627
3628     FuncInfo->setVarArgsFrameIndex(
3629       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3630     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3631
3632     // If this function is vararg, store any remaining integer argument regs
3633     // to their spots on the stack so that they may be loaded by dereferencing
3634     // the result of va_next.
3635     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3636          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3637       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3638       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3639       SDValue Store =
3640           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3641       MemOps.push_back(Store);
3642       // Increment the address by four for the next argument to store
3643       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3644       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3645     }
3646   }
3647
3648   if (!MemOps.empty())
3649     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3650
3651   return Chain;
3652 }
3653
3654 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3655     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3656     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3657     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3658   // TODO: add description of PPC stack frame format, or at least some docs.
3659   //
3660   MachineFunction &MF = DAG.getMachineFunction();
3661   MachineFrameInfo &MFI = MF.getFrameInfo();
3662   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3663
3664   EVT PtrVT = getPointerTy(MF.getDataLayout());
3665   bool isPPC64 = PtrVT == MVT::i64;
3666   // Potential tail calls could cause overwriting of argument stack slots.
3667   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3668                        (CallConv == CallingConv::Fast));
3669   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3670   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3671   unsigned ArgOffset = LinkageSize;
3672   // Area that is at least reserved in caller of this function.
3673   unsigned MinReservedArea = ArgOffset;
3674
3675   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3676     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3677     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3678   };
3679   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3680     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3681     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3682   };
3683   static const MCPhysReg VR[] = {
3684     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3685     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3686   };
3687
3688   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3689   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3690   const unsigned Num_VR_Regs  = array_lengthof( VR);
3691
3692   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3693
3694   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3695
3696   // In 32-bit non-varargs functions, the stack space for vectors is after the
3697   // stack space for non-vectors.  We do not use this space unless we have
3698   // too many vectors to fit in registers, something that only occurs in
3699   // constructed examples:), but we have to walk the arglist to figure
3700   // that out...for the pathological case, compute VecArgOffset as the
3701   // start of the vector parameter area.  Computing VecArgOffset is the
3702   // entire point of the following loop.
3703   unsigned VecArgOffset = ArgOffset;
3704   if (!isVarArg && !isPPC64) {
3705     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3706          ++ArgNo) {
3707       EVT ObjectVT = Ins[ArgNo].VT;
3708       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3709
3710       if (Flags.isByVal()) {
3711         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3712         unsigned ObjSize = Flags.getByValSize();
3713         unsigned ArgSize =
3714                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3715         VecArgOffset += ArgSize;
3716         continue;
3717       }
3718
3719       switch(ObjectVT.getSimpleVT().SimpleTy) {
3720       default: llvm_unreachable("Unhandled argument type!");
3721       case MVT::i1:
3722       case MVT::i32:
3723       case MVT::f32:
3724         VecArgOffset += 4;
3725         break;
3726       case MVT::i64:  // PPC64
3727       case MVT::f64:
3728         // FIXME: We are guaranteed to be !isPPC64 at this point.
3729         // Does MVT::i64 apply?
3730         VecArgOffset += 8;
3731         break;
3732       case MVT::v4f32:
3733       case MVT::v4i32:
3734       case MVT::v8i16:
3735       case MVT::v16i8:
3736         // Nothing to do, we're only looking at Nonvector args here.
3737         break;
3738       }
3739     }
3740   }
3741   // We've found where the vector parameter area in memory is.  Skip the
3742   // first 12 parameters; these don't use that memory.
3743   VecArgOffset = ((VecArgOffset+15)/16)*16;
3744   VecArgOffset += 12*16;
3745
3746   // Add DAG nodes to load the arguments or copy them out of registers.  On
3747   // entry to a function on PPC, the arguments start after the linkage area,
3748   // although the first ones are often in registers.
3749
3750   SmallVector<SDValue, 8> MemOps;
3751   unsigned nAltivecParamsAtEnd = 0;
3752   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3753   unsigned CurArgIdx = 0;
3754   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3755     SDValue ArgVal;
3756     bool needsLoad = false;
3757     EVT ObjectVT = Ins[ArgNo].VT;
3758     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3759     unsigned ArgSize = ObjSize;
3760     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3761     if (Ins[ArgNo].isOrigArg()) {
3762       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3763       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3764     }
3765     unsigned CurArgOffset = ArgOffset;
3766
3767     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3768     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3769         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3770       if (isVarArg || isPPC64) {
3771         MinReservedArea = ((MinReservedArea+15)/16)*16;
3772         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3773                                                   Flags,
3774                                                   PtrByteSize);
3775       } else  nAltivecParamsAtEnd++;
3776     } else
3777       // Calculate min reserved area.
3778       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3779                                                 Flags,
3780                                                 PtrByteSize);
3781
3782     // FIXME the codegen can be much improved in some cases.
3783     // We do not have to keep everything in memory.
3784     if (Flags.isByVal()) {
3785       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3786
3787       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3788       ObjSize = Flags.getByValSize();
3789       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3790       // Objects of size 1 and 2 are right justified, everything else is
3791       // left justified.  This means the memory address is adjusted forwards.
3792       if (ObjSize==1 || ObjSize==2) {
3793         CurArgOffset = CurArgOffset + (4 - ObjSize);
3794       }
3795       // The value of the object is its address.
3796       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3797       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3798       InVals.push_back(FIN);
3799       if (ObjSize==1 || ObjSize==2) {
3800         if (GPR_idx != Num_GPR_Regs) {
3801           unsigned VReg;
3802           if (isPPC64)
3803             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3804           else
3805             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3806           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3807           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3808           SDValue Store =
3809               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3810                                 MachinePointerInfo(&*FuncArg), ObjType);
3811           MemOps.push_back(Store);
3812           ++GPR_idx;
3813         }
3814
3815         ArgOffset += PtrByteSize;
3816
3817         continue;
3818       }
3819       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3820         // Store whatever pieces of the object are in registers
3821         // to memory.  ArgOffset will be the address of the beginning
3822         // of the object.
3823         if (GPR_idx != Num_GPR_Regs) {
3824           unsigned VReg;
3825           if (isPPC64)
3826             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3827           else
3828             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3829           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3830           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3831           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3832           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3833                                        MachinePointerInfo(&*FuncArg, j));
3834           MemOps.push_back(Store);
3835           ++GPR_idx;
3836           ArgOffset += PtrByteSize;
3837         } else {
3838           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3839           break;
3840         }
3841       }
3842       continue;
3843     }
3844
3845     switch (ObjectVT.getSimpleVT().SimpleTy) {
3846     default: llvm_unreachable("Unhandled argument type!");
3847     case MVT::i1:
3848     case MVT::i32:
3849       if (!isPPC64) {
3850         if (GPR_idx != Num_GPR_Regs) {
3851           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3852           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3853
3854           if (ObjectVT == MVT::i1)
3855             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3856
3857           ++GPR_idx;
3858         } else {
3859           needsLoad = true;
3860           ArgSize = PtrByteSize;
3861         }
3862         // All int arguments reserve stack space in the Darwin ABI.
3863         ArgOffset += PtrByteSize;
3864         break;
3865       }
3866       LLVM_FALLTHROUGH;
3867     case MVT::i64:  // PPC64
3868       if (GPR_idx != Num_GPR_Regs) {
3869         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3870         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3871
3872         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3873           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3874           // value to MVT::i64 and then truncate to the correct register size.
3875           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3876
3877         ++GPR_idx;
3878       } else {
3879         needsLoad = true;
3880         ArgSize = PtrByteSize;
3881       }
3882       // All int arguments reserve stack space in the Darwin ABI.
3883       ArgOffset += 8;
3884       break;
3885
3886     case MVT::f32:
3887     case MVT::f64:
3888       // Every 4 bytes of argument space consumes one of the GPRs available for
3889       // argument passing.
3890       if (GPR_idx != Num_GPR_Regs) {
3891         ++GPR_idx;
3892         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3893           ++GPR_idx;
3894       }
3895       if (FPR_idx != Num_FPR_Regs) {
3896         unsigned VReg;
3897
3898         if (ObjectVT == MVT::f32)
3899           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3900         else
3901           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3902
3903         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3904         ++FPR_idx;
3905       } else {
3906         needsLoad = true;
3907       }
3908
3909       // All FP arguments reserve stack space in the Darwin ABI.
3910       ArgOffset += isPPC64 ? 8 : ObjSize;
3911       break;
3912     case MVT::v4f32:
3913     case MVT::v4i32:
3914     case MVT::v8i16:
3915     case MVT::v16i8:
3916       // Note that vector arguments in registers don't reserve stack space,
3917       // except in varargs functions.
3918       if (VR_idx != Num_VR_Regs) {
3919         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3920         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3921         if (isVarArg) {
3922           while ((ArgOffset % 16) != 0) {
3923             ArgOffset += PtrByteSize;
3924             if (GPR_idx != Num_GPR_Regs)
3925               GPR_idx++;
3926           }
3927           ArgOffset += 16;
3928           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3929         }
3930         ++VR_idx;
3931       } else {
3932         if (!isVarArg && !isPPC64) {
3933           // Vectors go after all the nonvectors.
3934           CurArgOffset = VecArgOffset;
3935           VecArgOffset += 16;
3936         } else {
3937           // Vectors are aligned.
3938           ArgOffset = ((ArgOffset+15)/16)*16;
3939           CurArgOffset = ArgOffset;
3940           ArgOffset += 16;
3941         }
3942         needsLoad = true;
3943       }
3944       break;
3945     }
3946
3947     // We need to load the argument to a virtual register if we determined above
3948     // that we ran out of physical registers of the appropriate type.
3949     if (needsLoad) {
3950       int FI = MFI.CreateFixedObject(ObjSize,
3951                                      CurArgOffset + (ArgSize - ObjSize),
3952                                      isImmutable);
3953       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3954       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3955     }
3956
3957     InVals.push_back(ArgVal);
3958   }
3959
3960   // Allow for Altivec parameters at the end, if needed.
3961   if (nAltivecParamsAtEnd) {
3962     MinReservedArea = ((MinReservedArea+15)/16)*16;
3963     MinReservedArea += 16*nAltivecParamsAtEnd;
3964   }
3965
3966   // Area that is at least reserved in the caller of this function.
3967   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3968
3969   // Set the size that is at least reserved in caller of this function.  Tail
3970   // call optimized functions' reserved stack space needs to be aligned so that
3971   // taking the difference between two stack areas will result in an aligned
3972   // stack.
3973   MinReservedArea =
3974       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3975   FuncInfo->setMinReservedArea(MinReservedArea);
3976
3977   // If the function takes variable number of arguments, make a frame index for
3978   // the start of the first vararg value... for expansion of llvm.va_start.
3979   if (isVarArg) {
3980     int Depth = ArgOffset;
3981
3982     FuncInfo->setVarArgsFrameIndex(
3983       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3984                             Depth, true));
3985     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3986
3987     // If this function is vararg, store any remaining integer argument regs
3988     // to their spots on the stack so that they may be loaded by dereferencing
3989     // the result of va_next.
3990     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3991       unsigned VReg;
3992
3993       if (isPPC64)
3994         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3995       else
3996         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3997
3998       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3999       SDValue Store =
4000           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4001       MemOps.push_back(Store);
4002       // Increment the address by four for the next argument to store
4003       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4004       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4005     }
4006   }
4007
4008   if (!MemOps.empty())
4009     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4010
4011   return Chain;
4012 }
4013
4014 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4015 /// adjusted to accommodate the arguments for the tailcall.
4016 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4017                                    unsigned ParamSize) {
4018
4019   if (!isTailCall) return 0;
4020
4021   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4022   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4023   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4024   // Remember only if the new adjustement is bigger.
4025   if (SPDiff < FI->getTailCallSPDelta())
4026     FI->setTailCallSPDelta(SPDiff);
4027
4028   return SPDiff;
4029 }
4030
4031 static bool isFunctionGlobalAddress(SDValue Callee);
4032
4033 static bool
4034 resideInSameSection(const Function *Caller, SDValue Callee,
4035                     const TargetMachine &TM) {
4036   // If !G, Callee can be an external symbol.
4037   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4038   if (!G)
4039     return false;
4040
4041   const GlobalValue *GV = G->getGlobal();
4042   if (!GV->isStrongDefinitionForLinker())
4043     return false;
4044
4045   // Any explicitly-specified sections and section prefixes must also match.
4046   // Also, if we're using -ffunction-sections, then each function is always in
4047   // a different section (the same is true for COMDAT functions).
4048   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4049       GV->getSection() != Caller->getSection())
4050     return false;
4051   if (const auto *F = dyn_cast<Function>(GV)) {
4052     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4053       return false;
4054   }
4055
4056   // If the callee might be interposed, then we can't assume the ultimate call
4057   // target will be in the same section. Even in cases where we can assume that
4058   // interposition won't happen, in any case where the linker might insert a
4059   // stub to allow for interposition, we must generate code as though
4060   // interposition might occur. To understand why this matters, consider a
4061   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4062   // in the same section, but a is in a different module (i.e. has a different
4063   // TOC base pointer). If the linker allows for interposition between b and c,
4064   // then it will generate a stub for the call edge between b and c which will
4065   // save the TOC pointer into the designated stack slot allocated by b. If we
4066   // return true here, and therefore allow a tail call between b and c, that
4067   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4068   // pointer into the stack slot allocated by a (where the a -> b stub saved
4069   // a's TOC base pointer). If we're not considering a tail call, but rather,
4070   // whether a nop is needed after the call instruction in b, because the linker
4071   // will insert a stub, it might complain about a missing nop if we omit it
4072   // (although many don't complain in this case).
4073   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4074     return false;
4075
4076   return true;
4077 }
4078
4079 static bool
4080 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4081                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4082   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4083
4084   const unsigned PtrByteSize = 8;
4085   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4086
4087   static const MCPhysReg GPR[] = {
4088     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4089     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4090   };
4091   static const MCPhysReg VR[] = {
4092     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4093     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4094   };
4095
4096   const unsigned NumGPRs = array_lengthof(GPR);
4097   const unsigned NumFPRs = 13;
4098   const unsigned NumVRs = array_lengthof(VR);
4099   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4100
4101   unsigned NumBytes = LinkageSize;
4102   unsigned AvailableFPRs = NumFPRs;
4103   unsigned AvailableVRs = NumVRs;
4104
4105   for (const ISD::OutputArg& Param : Outs) {
4106     if (Param.Flags.isNest()) continue;
4107
4108     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4109                                PtrByteSize, LinkageSize, ParamAreaSize,
4110                                NumBytes, AvailableFPRs, AvailableVRs,
4111                                Subtarget.hasQPX()))
4112       return true;
4113   }
4114   return false;
4115 }
4116
4117 static bool
4118 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4119   if (CS->arg_size() != CallerFn->arg_size())
4120     return false;
4121
4122   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4123   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4124   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4125
4126   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4127     const Value* CalleeArg = *CalleeArgIter;
4128     const Value* CallerArg = &(*CallerArgIter);
4129     if (CalleeArg == CallerArg)
4130       continue;
4131
4132     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4133     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4134     //      }
4135     // 1st argument of callee is undef and has the same type as caller.
4136     if (CalleeArg->getType() == CallerArg->getType() &&
4137         isa<UndefValue>(CalleeArg))
4138       continue;
4139
4140     return false;
4141   }
4142
4143   return true;
4144 }
4145
4146 bool
4147 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4148                                     SDValue Callee,
4149                                     CallingConv::ID CalleeCC,
4150                                     ImmutableCallSite *CS,
4151                                     bool isVarArg,
4152                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4153                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4154                                     SelectionDAG& DAG) const {
4155   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4156
4157   if (DisableSCO && !TailCallOpt) return false;
4158
4159   // Variadic argument functions are not supported.
4160   if (isVarArg) return false;
4161
4162   MachineFunction &MF = DAG.getMachineFunction();
4163   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4164
4165   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4166   // the same calling convention
4167   if (CallerCC != CalleeCC) return false;
4168
4169   // SCO support C calling convention
4170   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4171     return false;
4172
4173   // Caller contains any byval parameter is not supported.
4174   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4175     return false;
4176
4177   // Callee contains any byval parameter is not supported, too.
4178   // Note: This is a quick work around, because in some cases, e.g.
4179   // caller's stack size > callee's stack size, we are still able to apply
4180   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4181   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4182     return false;
4183
4184   // No TCO/SCO on indirect call because Caller have to restore its TOC
4185   if (!isFunctionGlobalAddress(Callee) &&
4186       !isa<ExternalSymbolSDNode>(Callee))
4187     return false;
4188
4189   // Check if Callee resides in the same section, because for now, PPC64 SVR4
4190   // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4191   // section.
4192   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4193   if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4194     return false;
4195
4196   // TCO allows altering callee ABI, so we don't have to check further.
4197   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4198     return true;
4199
4200   if (DisableSCO) return false;
4201
4202   // If callee use the same argument list that caller is using, then we can
4203   // apply SCO on this case. If it is not, then we need to check if callee needs
4204   // stack for passing arguments.
4205   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4206       needStackSlotPassParameters(Subtarget, Outs)) {
4207     return false;
4208   }
4209
4210   return true;
4211 }
4212
4213 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4214 /// for tail call optimization. Targets which want to do tail call
4215 /// optimization should implement this function.
4216 bool
4217 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4218                                                      CallingConv::ID CalleeCC,
4219                                                      bool isVarArg,
4220                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4221                                                      SelectionDAG& DAG) const {
4222   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4223     return false;
4224
4225   // Variable argument functions are not supported.
4226   if (isVarArg)
4227     return false;
4228
4229   MachineFunction &MF = DAG.getMachineFunction();
4230   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4231   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4232     // Functions containing by val parameters are not supported.
4233     for (unsigned i = 0; i != Ins.size(); i++) {
4234        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4235        if (Flags.isByVal()) return false;
4236     }
4237
4238     // Non-PIC/GOT tail calls are supported.
4239     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4240       return true;
4241
4242     // At the moment we can only do local tail calls (in same module, hidden
4243     // or protected) if we are generating PIC.
4244     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4245       return G->getGlobal()->hasHiddenVisibility()
4246           || G->getGlobal()->hasProtectedVisibility();
4247   }
4248
4249   return false;
4250 }
4251
4252 /// isCallCompatibleAddress - Return the immediate to use if the specified
4253 /// 32-bit value is representable in the immediate field of a BxA instruction.
4254 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4255   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4256   if (!C) return nullptr;
4257
4258   int Addr = C->getZExtValue();
4259   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4260       SignExtend32<26>(Addr) != Addr)
4261     return nullptr;  // Top 6 bits have to be sext of immediate.
4262
4263   return DAG
4264       .getConstant(
4265           (int)C->getZExtValue() >> 2, SDLoc(Op),
4266           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4267       .getNode();
4268 }
4269
4270 namespace {
4271
4272 struct TailCallArgumentInfo {
4273   SDValue Arg;
4274   SDValue FrameIdxOp;
4275   int FrameIdx = 0;
4276
4277   TailCallArgumentInfo() = default;
4278 };
4279
4280 } // end anonymous namespace
4281
4282 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4283 static void StoreTailCallArgumentsToStackSlot(
4284     SelectionDAG &DAG, SDValue Chain,
4285     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4286     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4287   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4288     SDValue Arg = TailCallArgs[i].Arg;
4289     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4290     int FI = TailCallArgs[i].FrameIdx;
4291     // Store relative to framepointer.
4292     MemOpChains.push_back(DAG.getStore(
4293         Chain, dl, Arg, FIN,
4294         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4295   }
4296 }
4297
4298 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4299 /// the appropriate stack slot for the tail call optimized function call.
4300 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4301                                              SDValue OldRetAddr, SDValue OldFP,
4302                                              int SPDiff, const SDLoc &dl) {
4303   if (SPDiff) {
4304     // Calculate the new stack slot for the return address.
4305     MachineFunction &MF = DAG.getMachineFunction();
4306     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4307     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4308     bool isPPC64 = Subtarget.isPPC64();
4309     int SlotSize = isPPC64 ? 8 : 4;
4310     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4311     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4312                                                          NewRetAddrLoc, true);
4313     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4314     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4315     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4316                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4317
4318     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4319     // slot as the FP is never overwritten.
4320     if (Subtarget.isDarwinABI()) {
4321       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4322       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4323                                                          true);
4324       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4325       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4326                            MachinePointerInfo::getFixedStack(
4327                                DAG.getMachineFunction(), NewFPIdx));
4328     }
4329   }
4330   return Chain;
4331 }
4332
4333 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4334 /// the position of the argument.
4335 static void
4336 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4337                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4338                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4339   int Offset = ArgOffset + SPDiff;
4340   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4341   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4342   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4343   SDValue FIN = DAG.getFrameIndex(FI, VT);
4344   TailCallArgumentInfo Info;
4345   Info.Arg = Arg;
4346   Info.FrameIdxOp = FIN;
4347   Info.FrameIdx = FI;
4348   TailCallArguments.push_back(Info);
4349 }
4350
4351 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4352 /// stack slot. Returns the chain as result and the loaded frame pointers in
4353 /// LROpOut/FPOpout. Used when tail calling.
4354 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4355     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4356     SDValue &FPOpOut, const SDLoc &dl) const {
4357   if (SPDiff) {
4358     // Load the LR and FP stack slot for later adjusting.
4359     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4360     LROpOut = getReturnAddrFrameIndex(DAG);
4361     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4362     Chain = SDValue(LROpOut.getNode(), 1);
4363
4364     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4365     // slot as the FP is never overwritten.
4366     if (Subtarget.isDarwinABI()) {
4367       FPOpOut = getFramePointerFrameIndex(DAG);
4368       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4369       Chain = SDValue(FPOpOut.getNode(), 1);
4370     }
4371   }
4372   return Chain;
4373 }
4374
4375 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4376 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4377 /// specified by the specific parameter attribute. The copy will be passed as
4378 /// a byval function parameter.
4379 /// Sometimes what we are copying is the end of a larger object, the part that
4380 /// does not fit in registers.
4381 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4382                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4383                                          SelectionDAG &DAG, const SDLoc &dl) {
4384   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4385   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4386                        false, false, false, MachinePointerInfo(),
4387                        MachinePointerInfo());
4388 }
4389
4390 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4391 /// tail calls.
4392 static void LowerMemOpCallTo(
4393     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4394     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4395     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4396     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4397   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4398   if (!isTailCall) {
4399     if (isVector) {
4400       SDValue StackPtr;
4401       if (isPPC64)
4402         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4403       else
4404         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4405       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4406                            DAG.getConstant(ArgOffset, dl, PtrVT));
4407     }
4408     MemOpChains.push_back(
4409         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4410     // Calculate and remember argument location.
4411   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4412                                   TailCallArguments);
4413 }
4414
4415 static void
4416 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4417                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4418                 SDValue FPOp,
4419                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4420   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4421   // might overwrite each other in case of tail call optimization.
4422   SmallVector<SDValue, 8> MemOpChains2;
4423   // Do not flag preceding copytoreg stuff together with the following stuff.
4424   InFlag = SDValue();
4425   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4426                                     MemOpChains2, dl);
4427   if (!MemOpChains2.empty())
4428     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4429
4430   // Store the return address to the appropriate stack slot.
4431   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4432
4433   // Emit callseq_end just before tailcall node.
4434   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4435                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4436   InFlag = Chain.getValue(1);
4437 }
4438
4439 // Is this global address that of a function that can be called by name? (as
4440 // opposed to something that must hold a descriptor for an indirect call).
4441 static bool isFunctionGlobalAddress(SDValue Callee) {
4442   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4443     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4444         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4445       return false;
4446
4447     return G->getGlobal()->getValueType()->isFunctionTy();
4448   }
4449
4450   return false;
4451 }
4452
4453 static unsigned
4454 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4455             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4456             bool isPatchPoint, bool hasNest,
4457             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4458             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4459             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4460   bool isPPC64 = Subtarget.isPPC64();
4461   bool isSVR4ABI = Subtarget.isSVR4ABI();
4462   bool isELFv2ABI = Subtarget.isELFv2ABI();
4463
4464   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4465   NodeTys.push_back(MVT::Other);   // Returns a chain
4466   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4467
4468   unsigned CallOpc = PPCISD::CALL;
4469
4470   bool needIndirectCall = true;
4471   if (!isSVR4ABI || !isPPC64)
4472     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4473       // If this is an absolute destination address, use the munged value.
4474       Callee = SDValue(Dest, 0);
4475       needIndirectCall = false;
4476     }
4477
4478   // PC-relative references to external symbols should go through $stub, unless
4479   // we're building with the leopard linker or later, which automatically
4480   // synthesizes these stubs.
4481   const TargetMachine &TM = DAG.getTarget();
4482   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4483   const GlobalValue *GV = nullptr;
4484   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4485     GV = G->getGlobal();
4486   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4487   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4488
4489   if (isFunctionGlobalAddress(Callee)) {
4490     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4491     // A call to a TLS address is actually an indirect call to a
4492     // thread-specific pointer.
4493     unsigned OpFlags = 0;
4494     if (UsePlt)
4495       OpFlags = PPCII::MO_PLT;
4496
4497     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4498     // every direct call is) turn it into a TargetGlobalAddress /
4499     // TargetExternalSymbol node so that legalize doesn't hack it.
4500     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4501                                         Callee.getValueType(), 0, OpFlags);
4502     needIndirectCall = false;
4503   }
4504
4505   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4506     unsigned char OpFlags = 0;
4507
4508     if (UsePlt)
4509       OpFlags = PPCII::MO_PLT;
4510
4511     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4512                                          OpFlags);
4513     needIndirectCall = false;
4514   }
4515
4516   if (isPatchPoint) {
4517     // We'll form an invalid direct call when lowering a patchpoint; the full
4518     // sequence for an indirect call is complicated, and many of the
4519     // instructions introduced might have side effects (and, thus, can't be
4520     // removed later). The call itself will be removed as soon as the
4521     // argument/return lowering is complete, so the fact that it has the wrong
4522     // kind of operands should not really matter.
4523     needIndirectCall = false;
4524   }
4525
4526   if (needIndirectCall) {
4527     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4528     // to do the call, we can't use PPCISD::CALL.
4529     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4530
4531     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4532       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4533       // entry point, but to the function descriptor (the function entry point
4534       // address is part of the function descriptor though).
4535       // The function descriptor is a three doubleword structure with the
4536       // following fields: function entry point, TOC base address and
4537       // environment pointer.
4538       // Thus for a call through a function pointer, the following actions need
4539       // to be performed:
4540       //   1. Save the TOC of the caller in the TOC save area of its stack
4541       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4542       //   2. Load the address of the function entry point from the function
4543       //      descriptor.
4544       //   3. Load the TOC of the callee from the function descriptor into r2.
4545       //   4. Load the environment pointer from the function descriptor into
4546       //      r11.
4547       //   5. Branch to the function entry point address.
4548       //   6. On return of the callee, the TOC of the caller needs to be
4549       //      restored (this is done in FinishCall()).
4550       //
4551       // The loads are scheduled at the beginning of the call sequence, and the
4552       // register copies are flagged together to ensure that no other
4553       // operations can be scheduled in between. E.g. without flagging the
4554       // copies together, a TOC access in the caller could be scheduled between
4555       // the assignment of the callee TOC and the branch to the callee, which
4556       // results in the TOC access going through the TOC of the callee instead
4557       // of going through the TOC of the caller, which leads to incorrect code.
4558
4559       // Load the address of the function entry point from the function
4560       // descriptor.
4561       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4562       if (LDChain.getValueType() == MVT::Glue)
4563         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4564
4565       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4566                           ? (MachineMemOperand::MODereferenceable |
4567                              MachineMemOperand::MOInvariant)
4568                           : MachineMemOperand::MONone;
4569
4570       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4571       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4572                                         /* Alignment = */ 8, MMOFlags);
4573
4574       // Load environment pointer into r11.
4575       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4576       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4577       SDValue LoadEnvPtr =
4578           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4579                       /* Alignment = */ 8, MMOFlags);
4580
4581       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4582       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4583       SDValue TOCPtr =
4584           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4585                       /* Alignment = */ 8, MMOFlags);
4586
4587       setUsesTOCBasePtr(DAG);
4588       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4589                                         InFlag);
4590       Chain = TOCVal.getValue(0);
4591       InFlag = TOCVal.getValue(1);
4592
4593       // If the function call has an explicit 'nest' parameter, it takes the
4594       // place of the environment pointer.
4595       if (!hasNest) {
4596         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4597                                           InFlag);
4598
4599         Chain = EnvVal.getValue(0);
4600         InFlag = EnvVal.getValue(1);
4601       }
4602
4603       MTCTROps[0] = Chain;
4604       MTCTROps[1] = LoadFuncPtr;
4605       MTCTROps[2] = InFlag;
4606     }
4607
4608     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4609                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4610     InFlag = Chain.getValue(1);
4611
4612     NodeTys.clear();
4613     NodeTys.push_back(MVT::Other);
4614     NodeTys.push_back(MVT::Glue);
4615     Ops.push_back(Chain);
4616     CallOpc = PPCISD::BCTRL;
4617     Callee.setNode(nullptr);
4618     // Add use of X11 (holding environment pointer)
4619     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4620       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4621     // Add CTR register as callee so a bctr can be emitted later.
4622     if (isTailCall)
4623       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4624   }
4625
4626   // If this is a direct call, pass the chain and the callee.
4627   if (Callee.getNode()) {
4628     Ops.push_back(Chain);
4629     Ops.push_back(Callee);
4630   }
4631   // If this is a tail call add stack pointer delta.
4632   if (isTailCall)
4633     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4634
4635   // Add argument registers to the end of the list so that they are known live
4636   // into the call.
4637   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4638     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4639                                   RegsToPass[i].second.getValueType()));
4640
4641   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4642   // into the call.
4643   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4644     setUsesTOCBasePtr(DAG);
4645     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4646   }
4647
4648   return CallOpc;
4649 }
4650
4651 SDValue PPCTargetLowering::LowerCallResult(
4652     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4653     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4654     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4655   SmallVector<CCValAssign, 16> RVLocs;
4656   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4657                     *DAG.getContext());
4658   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4659
4660   // Copy all of the result registers out of their specified physreg.
4661   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4662     CCValAssign &VA = RVLocs[i];
4663     assert(VA.isRegLoc() && "Can only return in registers!");
4664
4665     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4666                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4667     Chain = Val.getValue(1);
4668     InFlag = Val.getValue(2);
4669
4670     switch (VA.getLocInfo()) {
4671     default: llvm_unreachable("Unknown loc info!");
4672     case CCValAssign::Full: break;
4673     case CCValAssign::AExt:
4674       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4675       break;
4676     case CCValAssign::ZExt:
4677       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4678                         DAG.getValueType(VA.getValVT()));
4679       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4680       break;
4681     case CCValAssign::SExt:
4682       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4683                         DAG.getValueType(VA.getValVT()));
4684       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4685       break;
4686     }
4687
4688     InVals.push_back(Val);
4689   }
4690
4691   return Chain;
4692 }
4693
4694 SDValue PPCTargetLowering::FinishCall(
4695     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4696     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4697     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4698     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4699     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4700     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4701   std::vector<EVT> NodeTys;
4702   SmallVector<SDValue, 8> Ops;
4703   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4704                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4705                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4706
4707   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4708   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4709     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4710
4711   // When performing tail call optimization the callee pops its arguments off
4712   // the stack. Account for this here so these bytes can be pushed back on in
4713   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4714   int BytesCalleePops =
4715     (CallConv == CallingConv::Fast &&
4716      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4717
4718   // Add a register mask operand representing the call-preserved registers.
4719   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4720   const uint32_t *Mask =
4721       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4722   assert(Mask && "Missing call preserved mask for calling convention");
4723   Ops.push_back(DAG.getRegisterMask(Mask));
4724
4725   if (InFlag.getNode())
4726     Ops.push_back(InFlag);
4727
4728   // Emit tail call.
4729   if (isTailCall) {
4730     assert(((Callee.getOpcode() == ISD::Register &&
4731              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4732             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4733             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4734             isa<ConstantSDNode>(Callee)) &&
4735     "Expecting an global address, external symbol, absolute value or register");
4736
4737     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4738     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4739   }
4740
4741   // Add a NOP immediately after the branch instruction when using the 64-bit
4742   // SVR4 ABI. At link time, if caller and callee are in a different module and
4743   // thus have a different TOC, the call will be replaced with a call to a stub
4744   // function which saves the current TOC, loads the TOC of the callee and
4745   // branches to the callee. The NOP will be replaced with a load instruction
4746   // which restores the TOC of the caller from the TOC save slot of the current
4747   // stack frame. If caller and callee belong to the same module (and have the
4748   // same TOC), the NOP will remain unchanged.
4749
4750   MachineFunction &MF = DAG.getMachineFunction();
4751   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4752       !isPatchPoint) {
4753     if (CallOpc == PPCISD::BCTRL) {
4754       // This is a call through a function pointer.
4755       // Restore the caller TOC from the save area into R2.
4756       // See PrepareCall() for more information about calls through function
4757       // pointers in the 64-bit SVR4 ABI.
4758       // We are using a target-specific load with r2 hard coded, because the
4759       // result of a target-independent load would never go directly into r2,
4760       // since r2 is a reserved register (which prevents the register allocator
4761       // from allocating it), resulting in an additional register being
4762       // allocated and an unnecessary move instruction being generated.
4763       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4764
4765       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4766       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4767       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4768       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4769       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4770
4771       // The address needs to go after the chain input but before the flag (or
4772       // any other variadic arguments).
4773       Ops.insert(std::next(Ops.begin()), AddTOC);
4774     } else if (CallOpc == PPCISD::CALL &&
4775       !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4776       // Otherwise insert NOP for non-local calls.
4777       CallOpc = PPCISD::CALL_NOP;
4778     }
4779   }
4780
4781   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4782   InFlag = Chain.getValue(1);
4783
4784   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4785                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4786                              InFlag, dl);
4787   if (!Ins.empty())
4788     InFlag = Chain.getValue(1);
4789
4790   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4791                          Ins, dl, DAG, InVals);
4792 }
4793
4794 SDValue
4795 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4796                              SmallVectorImpl<SDValue> &InVals) const {
4797   SelectionDAG &DAG                     = CLI.DAG;
4798   SDLoc &dl                             = CLI.DL;
4799   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4800   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4801   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4802   SDValue Chain                         = CLI.Chain;
4803   SDValue Callee                        = CLI.Callee;
4804   bool &isTailCall                      = CLI.IsTailCall;
4805   CallingConv::ID CallConv              = CLI.CallConv;
4806   bool isVarArg                         = CLI.IsVarArg;
4807   bool isPatchPoint                     = CLI.IsPatchPoint;
4808   ImmutableCallSite *CS                 = CLI.CS;
4809
4810   if (isTailCall) {
4811     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4812       isTailCall = false;
4813     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4814       isTailCall =
4815         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4816                                                  isVarArg, Outs, Ins, DAG);
4817     else
4818       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4819                                                      Ins, DAG);
4820     if (isTailCall) {
4821       ++NumTailCalls;
4822       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4823         ++NumSiblingCalls;
4824
4825       assert(isa<GlobalAddressSDNode>(Callee) &&
4826              "Callee should be an llvm::Function object.");
4827       DEBUG(
4828         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4829         const unsigned Width = 80 - strlen("TCO caller: ")
4830                                   - strlen(", callee linkage: 0, 0");
4831         dbgs() << "TCO caller: "
4832                << left_justify(DAG.getMachineFunction().getName(), Width)
4833                << ", callee linkage: "
4834                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4835       );
4836     }
4837   }
4838
4839   if (!isTailCall && CS && CS->isMustTailCall())
4840     report_fatal_error("failed to perform tail call elimination on a call "
4841                        "site marked musttail");
4842
4843   // When long calls (i.e. indirect calls) are always used, calls are always
4844   // made via function pointer. If we have a function name, first translate it
4845   // into a pointer.
4846   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4847       !isTailCall)
4848     Callee = LowerGlobalAddress(Callee, DAG);
4849
4850   if (Subtarget.isSVR4ABI()) {
4851     if (Subtarget.isPPC64())
4852       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4853                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4854                               dl, DAG, InVals, CS);
4855     else
4856       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4857                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4858                               dl, DAG, InVals, CS);
4859   }
4860
4861   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4862                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4863                           dl, DAG, InVals, CS);
4864 }
4865
4866 SDValue PPCTargetLowering::LowerCall_32SVR4(
4867     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4868     bool isTailCall, bool isPatchPoint,
4869     const SmallVectorImpl<ISD::OutputArg> &Outs,
4870     const SmallVectorImpl<SDValue> &OutVals,
4871     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4872     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4873     ImmutableCallSite *CS) const {
4874   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4875   // of the 32-bit SVR4 ABI stack frame layout.
4876
4877   assert((CallConv == CallingConv::C ||
4878           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4879
4880   unsigned PtrByteSize = 4;
4881
4882   MachineFunction &MF = DAG.getMachineFunction();
4883
4884   // Mark this function as potentially containing a function that contains a
4885   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4886   // and restoring the callers stack pointer in this functions epilog. This is
4887   // done because by tail calling the called function might overwrite the value
4888   // in this function's (MF) stack pointer stack slot 0(SP).
4889   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4890       CallConv == CallingConv::Fast)
4891     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4892
4893   // Count how many bytes are to be pushed on the stack, including the linkage
4894   // area, parameter list area and the part of the local variable space which
4895   // contains copies of aggregates which are passed by value.
4896
4897   // Assign locations to all of the outgoing arguments.
4898   SmallVector<CCValAssign, 16> ArgLocs;
4899   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4900
4901   // Reserve space for the linkage area on the stack.
4902   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4903                        PtrByteSize);
4904   if (useSoftFloat())
4905     CCInfo.PreAnalyzeCallOperands(Outs);
4906
4907   if (isVarArg) {
4908     // Handle fixed and variable vector arguments differently.
4909     // Fixed vector arguments go into registers as long as registers are
4910     // available. Variable vector arguments always go into memory.
4911     unsigned NumArgs = Outs.size();
4912
4913     for (unsigned i = 0; i != NumArgs; ++i) {
4914       MVT ArgVT = Outs[i].VT;
4915       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4916       bool Result;
4917
4918       if (Outs[i].IsFixed) {
4919         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4920                                CCInfo);
4921       } else {
4922         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4923                                       ArgFlags, CCInfo);
4924       }
4925
4926       if (Result) {
4927 #ifndef NDEBUG
4928         errs() << "Call operand #" << i << " has unhandled type "
4929              << EVT(ArgVT).getEVTString() << "\n";
4930 #endif
4931         llvm_unreachable(nullptr);
4932       }
4933     }
4934   } else {
4935     // All arguments are treated the same.
4936     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4937   }
4938   CCInfo.clearWasPPCF128();
4939
4940   // Assign locations to all of the outgoing aggregate by value arguments.
4941   SmallVector<CCValAssign, 16> ByValArgLocs;
4942   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4943
4944   // Reserve stack space for the allocations in CCInfo.
4945   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4946
4947   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4948
4949   // Size of the linkage area, parameter list area and the part of the local
4950   // space variable where copies of aggregates which are passed by value are
4951   // stored.
4952   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4953
4954   // Calculate by how many bytes the stack has to be adjusted in case of tail
4955   // call optimization.
4956   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4957
4958   // Adjust the stack pointer for the new arguments...
4959   // These operations are automatically eliminated by the prolog/epilog pass
4960   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
4961   SDValue CallSeqStart = Chain;
4962
4963   // Load the return address and frame pointer so it can be moved somewhere else
4964   // later.
4965   SDValue LROp, FPOp;
4966   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4967
4968   // Set up a copy of the stack pointer for use loading and storing any
4969   // arguments that may not fit in the registers available for argument
4970   // passing.
4971   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4972
4973   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4974   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4975   SmallVector<SDValue, 8> MemOpChains;
4976
4977   bool seenFloatArg = false;
4978   // Walk the register/memloc assignments, inserting copies/loads.
4979   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4980        i != e;
4981        ++i) {
4982     CCValAssign &VA = ArgLocs[i];
4983     SDValue Arg = OutVals[i];
4984     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4985
4986     if (Flags.isByVal()) {
4987       // Argument is an aggregate which is passed by value, thus we need to
4988       // create a copy of it in the local variable space of the current stack
4989       // frame (which is the stack frame of the caller) and pass the address of
4990       // this copy to the callee.
4991       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4992       CCValAssign &ByValVA = ByValArgLocs[j++];
4993       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4994
4995       // Memory reserved in the local variable space of the callers stack frame.
4996       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4997
4998       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4999       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5000                            StackPtr, PtrOff);
5001
5002       // Create a copy of the argument in the local area of the current
5003       // stack frame.
5004       SDValue MemcpyCall =
5005         CreateCopyOfByValArgument(Arg, PtrOff,
5006                                   CallSeqStart.getNode()->getOperand(0),
5007                                   Flags, DAG, dl);
5008
5009       // This must go outside the CALLSEQ_START..END.
5010       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5011                                                      SDLoc(MemcpyCall));
5012       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5013                              NewCallSeqStart.getNode());
5014       Chain = CallSeqStart = NewCallSeqStart;
5015
5016       // Pass the address of the aggregate copy on the stack either in a
5017       // physical register or in the parameter list area of the current stack
5018       // frame to the callee.
5019       Arg = PtrOff;
5020     }
5021
5022     if (VA.isRegLoc()) {
5023       if (Arg.getValueType() == MVT::i1)
5024         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5025
5026       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5027       // Put argument in a physical register.
5028       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5029     } else {
5030       // Put argument in the parameter list area of the current stack frame.
5031       assert(VA.isMemLoc());
5032       unsigned LocMemOffset = VA.getLocMemOffset();
5033
5034       if (!isTailCall) {
5035         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5036         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5037                              StackPtr, PtrOff);
5038
5039         MemOpChains.push_back(
5040             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5041       } else {
5042         // Calculate and remember argument location.
5043         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5044                                  TailCallArguments);
5045       }
5046     }
5047   }
5048
5049   if (!MemOpChains.empty())
5050     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5051
5052   // Build a sequence of copy-to-reg nodes chained together with token chain
5053   // and flag operands which copy the outgoing args into the appropriate regs.
5054   SDValue InFlag;
5055   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5056     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5057                              RegsToPass[i].second, InFlag);
5058     InFlag = Chain.getValue(1);
5059   }
5060
5061   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5062   // registers.
5063   if (isVarArg) {
5064     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5065     SDValue Ops[] = { Chain, InFlag };
5066
5067     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5068                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5069
5070     InFlag = Chain.getValue(1);
5071   }
5072
5073   if (isTailCall)
5074     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5075                     TailCallArguments);
5076
5077   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5078                     /* unused except on PPC64 ELFv1 */ false, DAG,
5079                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5080                     NumBytes, Ins, InVals, CS);
5081 }
5082
5083 // Copy an argument into memory, being careful to do this outside the
5084 // call sequence for the call to which the argument belongs.
5085 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5086     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5087     SelectionDAG &DAG, const SDLoc &dl) const {
5088   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5089                         CallSeqStart.getNode()->getOperand(0),
5090                         Flags, DAG, dl);
5091   // The MEMCPY must go outside the CALLSEQ_START..END.
5092   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5093   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5094                                                  SDLoc(MemcpyCall));
5095   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5096                          NewCallSeqStart.getNode());
5097   return NewCallSeqStart;
5098 }
5099
5100 SDValue PPCTargetLowering::LowerCall_64SVR4(
5101     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5102     bool isTailCall, bool isPatchPoint,
5103     const SmallVectorImpl<ISD::OutputArg> &Outs,
5104     const SmallVectorImpl<SDValue> &OutVals,
5105     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5106     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5107     ImmutableCallSite *CS) const {
5108   bool isELFv2ABI = Subtarget.isELFv2ABI();
5109   bool isLittleEndian = Subtarget.isLittleEndian();
5110   unsigned NumOps = Outs.size();
5111   bool hasNest = false;
5112   bool IsSibCall = false;
5113
5114   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5115   unsigned PtrByteSize = 8;
5116
5117   MachineFunction &MF = DAG.getMachineFunction();
5118
5119   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5120     IsSibCall = true;
5121
5122   // Mark this function as potentially containing a function that contains a
5123   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5124   // and restoring the callers stack pointer in this functions epilog. This is
5125   // done because by tail calling the called function might overwrite the value
5126   // in this function's (MF) stack pointer stack slot 0(SP).
5127   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5128       CallConv == CallingConv::Fast)
5129     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5130
5131   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5132          "fastcc not supported on varargs functions");
5133
5134   // Count how many bytes are to be pushed on the stack, including the linkage
5135   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5136   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5137   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5138   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5139   unsigned NumBytes = LinkageSize;
5140   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5141   unsigned &QFPR_idx = FPR_idx;
5142
5143   static const MCPhysReg GPR[] = {
5144     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5145     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5146   };
5147   static const MCPhysReg VR[] = {
5148     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5149     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5150   };
5151
5152   const unsigned NumGPRs = array_lengthof(GPR);
5153   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5154   const unsigned NumVRs  = array_lengthof(VR);
5155   const unsigned NumQFPRs = NumFPRs;
5156
5157   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5158   // can be passed to the callee in registers.
5159   // For the fast calling convention, there is another check below.
5160   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5161   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5162   if (!HasParameterArea) {
5163     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5164     unsigned AvailableFPRs = NumFPRs;
5165     unsigned AvailableVRs = NumVRs;
5166     unsigned NumBytesTmp = NumBytes;
5167     for (unsigned i = 0; i != NumOps; ++i) {
5168       if (Outs[i].Flags.isNest()) continue;
5169       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5170                                 PtrByteSize, LinkageSize, ParamAreaSize,
5171                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5172                                 Subtarget.hasQPX()))
5173         HasParameterArea = true;
5174     }
5175   }
5176
5177   // When using the fast calling convention, we don't provide backing for
5178   // arguments that will be in registers.
5179   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5180
5181   // Add up all the space actually used.
5182   for (unsigned i = 0; i != NumOps; ++i) {
5183     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5184     EVT ArgVT = Outs[i].VT;
5185     EVT OrigVT = Outs[i].ArgVT;
5186
5187     if (Flags.isNest())
5188       continue;
5189
5190     if (CallConv == CallingConv::Fast) {
5191       if (Flags.isByVal())
5192         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5193       else
5194         switch (ArgVT.getSimpleVT().SimpleTy) {
5195         default: llvm_unreachable("Unexpected ValueType for argument!");
5196         case MVT::i1:
5197         case MVT::i32:
5198         case MVT::i64:
5199           if (++NumGPRsUsed <= NumGPRs)
5200             continue;
5201           break;
5202         case MVT::v4i32:
5203         case MVT::v8i16:
5204         case MVT::v16i8:
5205         case MVT::v2f64:
5206         case MVT::v2i64:
5207         case MVT::v1i128:
5208           if (++NumVRsUsed <= NumVRs)
5209             continue;
5210           break;
5211         case MVT::v4f32:
5212           // When using QPX, this is handled like a FP register, otherwise, it
5213           // is an Altivec register.
5214           if (Subtarget.hasQPX()) {
5215             if (++NumFPRsUsed <= NumFPRs)
5216               continue;
5217           } else {
5218             if (++NumVRsUsed <= NumVRs)
5219               continue;
5220           }
5221           break;
5222         case MVT::f32:
5223         case MVT::f64:
5224         case MVT::v4f64: // QPX
5225         case MVT::v4i1:  // QPX
5226           if (++NumFPRsUsed <= NumFPRs)
5227             continue;
5228           break;
5229         }
5230     }
5231
5232     /* Respect alignment of argument on the stack.  */
5233     unsigned Align =
5234       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5235     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5236
5237     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5238     if (Flags.isInConsecutiveRegsLast())
5239       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5240   }
5241
5242   unsigned NumBytesActuallyUsed = NumBytes;
5243
5244   // In the old ELFv1 ABI,
5245   // the prolog code of the callee may store up to 8 GPR argument registers to
5246   // the stack, allowing va_start to index over them in memory if its varargs.
5247   // Because we cannot tell if this is needed on the caller side, we have to
5248   // conservatively assume that it is needed.  As such, make sure we have at
5249   // least enough stack space for the caller to store the 8 GPRs.
5250   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5251   // really requires memory operands, e.g. a vararg function.
5252   if (HasParameterArea)
5253     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5254   else
5255     NumBytes = LinkageSize;
5256
5257   // Tail call needs the stack to be aligned.
5258   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5259       CallConv == CallingConv::Fast)
5260     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5261
5262   int SPDiff = 0;
5263
5264   // Calculate by how many bytes the stack has to be adjusted in case of tail
5265   // call optimization.
5266   if (!IsSibCall)
5267     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5268
5269   // To protect arguments on the stack from being clobbered in a tail call,
5270   // force all the loads to happen before doing any other lowering.
5271   if (isTailCall)
5272     Chain = DAG.getStackArgumentTokenFactor(Chain);
5273
5274   // Adjust the stack pointer for the new arguments...
5275   // These operations are automatically eliminated by the prolog/epilog pass
5276   if (!IsSibCall)
5277     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5278   SDValue CallSeqStart = Chain;
5279
5280   // Load the return address and frame pointer so it can be move somewhere else
5281   // later.
5282   SDValue LROp, FPOp;
5283   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5284
5285   // Set up a copy of the stack pointer for use loading and storing any
5286   // arguments that may not fit in the registers available for argument
5287   // passing.
5288   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5289
5290   // Figure out which arguments are going to go in registers, and which in
5291   // memory.  Also, if this is a vararg function, floating point operations
5292   // must be stored to our stack, and loaded into integer regs as well, if
5293   // any integer regs are available for argument passing.
5294   unsigned ArgOffset = LinkageSize;
5295
5296   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5297   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5298
5299   SmallVector<SDValue, 8> MemOpChains;
5300   for (unsigned i = 0; i != NumOps; ++i) {
5301     SDValue Arg = OutVals[i];
5302     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5303     EVT ArgVT = Outs[i].VT;
5304     EVT OrigVT = Outs[i].ArgVT;
5305
5306     // PtrOff will be used to store the current argument to the stack if a
5307     // register cannot be found for it.
5308     SDValue PtrOff;
5309
5310     // We re-align the argument offset for each argument, except when using the
5311     // fast calling convention, when we need to make sure we do that only when
5312     // we'll actually use a stack slot.
5313     auto ComputePtrOff = [&]() {
5314       /* Respect alignment of argument on the stack.  */
5315       unsigned Align =
5316         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5317       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5318
5319       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5320
5321       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5322     };
5323
5324     if (CallConv != CallingConv::Fast) {
5325       ComputePtrOff();
5326
5327       /* Compute GPR index associated with argument offset.  */
5328       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5329       GPR_idx = std::min(GPR_idx, NumGPRs);
5330     }
5331
5332     // Promote integers to 64-bit values.
5333     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5334       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5335       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5336       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5337     }
5338
5339     // FIXME memcpy is used way more than necessary.  Correctness first.
5340     // Note: "by value" is code for passing a structure by value, not
5341     // basic types.
5342     if (Flags.isByVal()) {
5343       // Note: Size includes alignment padding, so
5344       //   struct x { short a; char b; }
5345       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5346       // These are the proper values we need for right-justifying the
5347       // aggregate in a parameter register.
5348       unsigned Size = Flags.getByValSize();
5349
5350       // An empty aggregate parameter takes up no storage and no
5351       // registers.
5352       if (Size == 0)
5353         continue;
5354
5355       if (CallConv == CallingConv::Fast)
5356         ComputePtrOff();
5357
5358       // All aggregates smaller than 8 bytes must be passed right-justified.
5359       if (Size==1 || Size==2 || Size==4) {
5360         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5361         if (GPR_idx != NumGPRs) {
5362           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5363                                         MachinePointerInfo(), VT);
5364           MemOpChains.push_back(Load.getValue(1));
5365           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5366
5367           ArgOffset += PtrByteSize;
5368           continue;
5369         }
5370       }
5371
5372       if (GPR_idx == NumGPRs && Size < 8) {
5373         SDValue AddPtr = PtrOff;
5374         if (!isLittleEndian) {
5375           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5376                                           PtrOff.getValueType());
5377           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5378         }
5379         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5380                                                           CallSeqStart,
5381                                                           Flags, DAG, dl);
5382         ArgOffset += PtrByteSize;
5383         continue;
5384       }
5385       // Copy entire object into memory.  There are cases where gcc-generated
5386       // code assumes it is there, even if it could be put entirely into
5387       // registers.  (This is not what the doc says.)
5388
5389       // FIXME: The above statement is likely due to a misunderstanding of the
5390       // documents.  All arguments must be copied into the parameter area BY
5391       // THE CALLEE in the event that the callee takes the address of any
5392       // formal argument.  That has not yet been implemented.  However, it is
5393       // reasonable to use the stack area as a staging area for the register
5394       // load.
5395
5396       // Skip this for small aggregates, as we will use the same slot for a
5397       // right-justified copy, below.
5398       if (Size >= 8)
5399         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5400                                                           CallSeqStart,
5401                                                           Flags, DAG, dl);
5402
5403       // When a register is available, pass a small aggregate right-justified.
5404       if (Size < 8 && GPR_idx != NumGPRs) {
5405         // The easiest way to get this right-justified in a register
5406         // is to copy the structure into the rightmost portion of a
5407         // local variable slot, then load the whole slot into the
5408         // register.
5409         // FIXME: The memcpy seems to produce pretty awful code for
5410         // small aggregates, particularly for packed ones.
5411         // FIXME: It would be preferable to use the slot in the
5412         // parameter save area instead of a new local variable.
5413         SDValue AddPtr = PtrOff;
5414         if (!isLittleEndian) {
5415           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5416           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5417         }
5418         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5419                                                           CallSeqStart,
5420                                                           Flags, DAG, dl);
5421
5422         // Load the slot into the register.
5423         SDValue Load =
5424             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5425         MemOpChains.push_back(Load.getValue(1));
5426         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5427
5428         // Done with this argument.
5429         ArgOffset += PtrByteSize;
5430         continue;
5431       }
5432
5433       // For aggregates larger than PtrByteSize, copy the pieces of the
5434       // object that fit into registers from the parameter save area.
5435       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5436         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5437         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5438         if (GPR_idx != NumGPRs) {
5439           SDValue Load =
5440               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5441           MemOpChains.push_back(Load.getValue(1));
5442           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5443           ArgOffset += PtrByteSize;
5444         } else {
5445           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5446           break;
5447         }
5448       }
5449       continue;
5450     }
5451
5452     switch (Arg.getSimpleValueType().SimpleTy) {
5453     default: llvm_unreachable("Unexpected ValueType for argument!");
5454     case MVT::i1:
5455     case MVT::i32:
5456     case MVT::i64:
5457       if (Flags.isNest()) {
5458         // The 'nest' parameter, if any, is passed in R11.
5459         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5460         hasNest = true;
5461         break;
5462       }
5463
5464       // These can be scalar arguments or elements of an integer array type
5465       // passed directly.  Clang may use those instead of "byval" aggregate
5466       // types to avoid forcing arguments to memory unnecessarily.
5467       if (GPR_idx != NumGPRs) {
5468         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5469       } else {
5470         if (CallConv == CallingConv::Fast)
5471           ComputePtrOff();
5472
5473         assert(HasParameterArea &&
5474                "Parameter area must exist to pass an argument in memory.");
5475         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5476                          true, isTailCall, false, MemOpChains,
5477                          TailCallArguments, dl);
5478         if (CallConv == CallingConv::Fast)
5479           ArgOffset += PtrByteSize;
5480       }
5481       if (CallConv != CallingConv::Fast)
5482         ArgOffset += PtrByteSize;
5483       break;
5484     case MVT::f32:
5485     case MVT::f64: {
5486       // These can be scalar arguments or elements of a float array type
5487       // passed directly.  The latter are used to implement ELFv2 homogenous
5488       // float aggregates.
5489
5490       // Named arguments go into FPRs first, and once they overflow, the
5491       // remaining arguments go into GPRs and then the parameter save area.
5492       // Unnamed arguments for vararg functions always go to GPRs and
5493       // then the parameter save area.  For now, put all arguments to vararg
5494       // routines always in both locations (FPR *and* GPR or stack slot).
5495       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5496       bool NeededLoad = false;
5497
5498       // First load the argument into the next available FPR.
5499       if (FPR_idx != NumFPRs)
5500         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5501
5502       // Next, load the argument into GPR or stack slot if needed.
5503       if (!NeedGPROrStack)
5504         ;
5505       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5506         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5507         // once we support fp <-> gpr moves.
5508
5509         // In the non-vararg case, this can only ever happen in the
5510         // presence of f32 array types, since otherwise we never run
5511         // out of FPRs before running out of GPRs.
5512         SDValue ArgVal;
5513
5514         // Double values are always passed in a single GPR.
5515         if (Arg.getValueType() != MVT::f32) {
5516           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5517
5518         // Non-array float values are extended and passed in a GPR.
5519         } else if (!Flags.isInConsecutiveRegs()) {
5520           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5521           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5522
5523         // If we have an array of floats, we collect every odd element
5524         // together with its predecessor into one GPR.
5525         } else if (ArgOffset % PtrByteSize != 0) {
5526           SDValue Lo, Hi;
5527           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5528           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5529           if (!isLittleEndian)
5530             std::swap(Lo, Hi);
5531           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5532
5533         // The final element, if even, goes into the first half of a GPR.
5534         } else if (Flags.isInConsecutiveRegsLast()) {
5535           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5536           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5537           if (!isLittleEndian)
5538             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5539                                  DAG.getConstant(32, dl, MVT::i32));
5540
5541         // Non-final even elements are skipped; they will be handled
5542         // together the with subsequent argument on the next go-around.
5543         } else
5544           ArgVal = SDValue();
5545
5546         if (ArgVal.getNode())
5547           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5548       } else {
5549         if (CallConv == CallingConv::Fast)
5550           ComputePtrOff();
5551
5552         // Single-precision floating-point values are mapped to the
5553         // second (rightmost) word of the stack doubleword.
5554         if (Arg.getValueType() == MVT::f32 &&
5555             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5556           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5557           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5558         }
5559
5560         assert(HasParameterArea &&
5561                "Parameter area must exist to pass an argument in memory.");
5562         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5563                          true, isTailCall, false, MemOpChains,
5564                          TailCallArguments, dl);
5565
5566         NeededLoad = true;
5567       }
5568       // When passing an array of floats, the array occupies consecutive
5569       // space in the argument area; only round up to the next doubleword
5570       // at the end of the array.  Otherwise, each float takes 8 bytes.
5571       if (CallConv != CallingConv::Fast || NeededLoad) {
5572         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5573                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5574         if (Flags.isInConsecutiveRegsLast())
5575           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5576       }
5577       break;
5578     }
5579     case MVT::v4f32:
5580     case MVT::v4i32:
5581     case MVT::v8i16:
5582     case MVT::v16i8:
5583     case MVT::v2f64:
5584     case MVT::v2i64:
5585     case MVT::v1i128:
5586       if (!Subtarget.hasQPX()) {
5587       // These can be scalar arguments or elements of a vector array type
5588       // passed directly.  The latter are used to implement ELFv2 homogenous
5589       // vector aggregates.
5590
5591       // For a varargs call, named arguments go into VRs or on the stack as
5592       // usual; unnamed arguments always go to the stack or the corresponding
5593       // GPRs when within range.  For now, we always put the value in both
5594       // locations (or even all three).
5595       if (isVarArg) {
5596         assert(HasParameterArea &&
5597                "Parameter area must exist if we have a varargs call.");
5598         // We could elide this store in the case where the object fits
5599         // entirely in R registers.  Maybe later.
5600         SDValue Store =
5601             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5602         MemOpChains.push_back(Store);
5603         if (VR_idx != NumVRs) {
5604           SDValue Load =
5605               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5606           MemOpChains.push_back(Load.getValue(1));
5607           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5608         }
5609         ArgOffset += 16;
5610         for (unsigned i=0; i<16; i+=PtrByteSize) {
5611           if (GPR_idx == NumGPRs)
5612             break;
5613           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5614                                    DAG.getConstant(i, dl, PtrVT));
5615           SDValue Load =
5616               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5617           MemOpChains.push_back(Load.getValue(1));
5618           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5619         }
5620         break;
5621       }
5622
5623       // Non-varargs Altivec params go into VRs or on the stack.
5624       if (VR_idx != NumVRs) {
5625         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5626       } else {
5627         if (CallConv == CallingConv::Fast)
5628           ComputePtrOff();
5629
5630         assert(HasParameterArea &&
5631                "Parameter area must exist to pass an argument in memory.");
5632         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5633                          true, isTailCall, true, MemOpChains,
5634                          TailCallArguments, dl);
5635         if (CallConv == CallingConv::Fast)
5636           ArgOffset += 16;
5637       }
5638
5639       if (CallConv != CallingConv::Fast)
5640         ArgOffset += 16;
5641       break;
5642       } // not QPX
5643
5644       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5645              "Invalid QPX parameter type");
5646
5647       /* fall through */
5648     case MVT::v4f64:
5649     case MVT::v4i1: {
5650       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5651       if (isVarArg) {
5652         assert(HasParameterArea &&
5653                "Parameter area must exist if we have a varargs call.");
5654         // We could elide this store in the case where the object fits
5655         // entirely in R registers.  Maybe later.
5656         SDValue Store =
5657             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5658         MemOpChains.push_back(Store);
5659         if (QFPR_idx != NumQFPRs) {
5660           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5661                                      PtrOff, MachinePointerInfo());
5662           MemOpChains.push_back(Load.getValue(1));
5663           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5664         }
5665         ArgOffset += (IsF32 ? 16 : 32);
5666         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5667           if (GPR_idx == NumGPRs)
5668             break;
5669           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5670                                    DAG.getConstant(i, dl, PtrVT));
5671           SDValue Load =
5672               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5673           MemOpChains.push_back(Load.getValue(1));
5674           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5675         }
5676         break;
5677       }
5678
5679       // Non-varargs QPX params go into registers or on the stack.
5680       if (QFPR_idx != NumQFPRs) {
5681         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5682       } else {
5683         if (CallConv == CallingConv::Fast)
5684           ComputePtrOff();
5685
5686         assert(HasParameterArea &&
5687                "Parameter area must exist to pass an argument in memory.");
5688         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5689                          true, isTailCall, true, MemOpChains,
5690                          TailCallArguments, dl);
5691         if (CallConv == CallingConv::Fast)
5692           ArgOffset += (IsF32 ? 16 : 32);
5693       }
5694
5695       if (CallConv != CallingConv::Fast)
5696         ArgOffset += (IsF32 ? 16 : 32);
5697       break;
5698       }
5699     }
5700   }
5701
5702   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5703          "mismatch in size of parameter area");
5704   (void)NumBytesActuallyUsed;
5705
5706   if (!MemOpChains.empty())
5707     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5708
5709   // Check if this is an indirect call (MTCTR/BCTRL).
5710   // See PrepareCall() for more information about calls through function
5711   // pointers in the 64-bit SVR4 ABI.
5712   if (!isTailCall && !isPatchPoint &&
5713       !isFunctionGlobalAddress(Callee) &&
5714       !isa<ExternalSymbolSDNode>(Callee)) {
5715     // Load r2 into a virtual register and store it to the TOC save area.
5716     setUsesTOCBasePtr(DAG);
5717     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5718     // TOC save area offset.
5719     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5720     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5721     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5722     Chain = DAG.getStore(
5723         Val.getValue(1), dl, Val, AddPtr,
5724         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5725     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5726     // This does not mean the MTCTR instruction must use R12; it's easier
5727     // to model this as an extra parameter, so do that.
5728     if (isELFv2ABI && !isPatchPoint)
5729       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5730   }
5731
5732   // Build a sequence of copy-to-reg nodes chained together with token chain
5733   // and flag operands which copy the outgoing args into the appropriate regs.
5734   SDValue InFlag;
5735   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5736     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5737                              RegsToPass[i].second, InFlag);
5738     InFlag = Chain.getValue(1);
5739   }
5740
5741   if (isTailCall && !IsSibCall)
5742     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5743                     TailCallArguments);
5744
5745   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5746                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5747                     SPDiff, NumBytes, Ins, InVals, CS);
5748 }
5749
5750 SDValue PPCTargetLowering::LowerCall_Darwin(
5751     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5752     bool isTailCall, bool isPatchPoint,
5753     const SmallVectorImpl<ISD::OutputArg> &Outs,
5754     const SmallVectorImpl<SDValue> &OutVals,
5755     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5756     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5757     ImmutableCallSite *CS) const {
5758   unsigned NumOps = Outs.size();
5759
5760   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5761   bool isPPC64 = PtrVT == MVT::i64;
5762   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5763
5764   MachineFunction &MF = DAG.getMachineFunction();
5765
5766   // Mark this function as potentially containing a function that contains a
5767   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5768   // and restoring the callers stack pointer in this functions epilog. This is
5769   // done because by tail calling the called function might overwrite the value
5770   // in this function's (MF) stack pointer stack slot 0(SP).
5771   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5772       CallConv == CallingConv::Fast)
5773     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5774
5775   // Count how many bytes are to be pushed on the stack, including the linkage
5776   // area, and parameter passing area.  We start with 24/48 bytes, which is
5777   // prereserved space for [SP][CR][LR][3 x unused].
5778   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5779   unsigned NumBytes = LinkageSize;
5780
5781   // Add up all the space actually used.
5782   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5783   // they all go in registers, but we must reserve stack space for them for
5784   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5785   // assigned stack space in order, with padding so Altivec parameters are
5786   // 16-byte aligned.
5787   unsigned nAltivecParamsAtEnd = 0;
5788   for (unsigned i = 0; i != NumOps; ++i) {
5789     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5790     EVT ArgVT = Outs[i].VT;
5791     // Varargs Altivec parameters are padded to a 16 byte boundary.
5792     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5793         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5794         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5795       if (!isVarArg && !isPPC64) {
5796         // Non-varargs Altivec parameters go after all the non-Altivec
5797         // parameters; handle those later so we know how much padding we need.
5798         nAltivecParamsAtEnd++;
5799         continue;
5800       }
5801       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5802       NumBytes = ((NumBytes+15)/16)*16;
5803     }
5804     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5805   }
5806
5807   // Allow for Altivec parameters at the end, if needed.
5808   if (nAltivecParamsAtEnd) {
5809     NumBytes = ((NumBytes+15)/16)*16;
5810     NumBytes += 16*nAltivecParamsAtEnd;
5811   }
5812
5813   // The prolog code of the callee may store up to 8 GPR argument registers to
5814   // the stack, allowing va_start to index over them in memory if its varargs.
5815   // Because we cannot tell if this is needed on the caller side, we have to
5816   // conservatively assume that it is needed.  As such, make sure we have at
5817   // least enough stack space for the caller to store the 8 GPRs.
5818   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5819
5820   // Tail call needs the stack to be aligned.
5821   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5822       CallConv == CallingConv::Fast)
5823     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5824
5825   // Calculate by how many bytes the stack has to be adjusted in case of tail
5826   // call optimization.
5827   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5828
5829   // To protect arguments on the stack from being clobbered in a tail call,
5830   // force all the loads to happen before doing any other lowering.
5831   if (isTailCall)
5832     Chain = DAG.getStackArgumentTokenFactor(Chain);
5833
5834   // Adjust the stack pointer for the new arguments...
5835   // These operations are automatically eliminated by the prolog/epilog pass
5836   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5837   SDValue CallSeqStart = Chain;
5838
5839   // Load the return address and frame pointer so it can be move somewhere else
5840   // later.
5841   SDValue LROp, FPOp;
5842   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5843
5844   // Set up a copy of the stack pointer for use loading and storing any
5845   // arguments that may not fit in the registers available for argument
5846   // passing.
5847   SDValue StackPtr;
5848   if (isPPC64)
5849     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5850   else
5851     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5852
5853   // Figure out which arguments are going to go in registers, and which in
5854   // memory.  Also, if this is a vararg function, floating point operations
5855   // must be stored to our stack, and loaded into integer regs as well, if
5856   // any integer regs are available for argument passing.
5857   unsigned ArgOffset = LinkageSize;
5858   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5859
5860   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5861     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5862     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5863   };
5864   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5865     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5866     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5867   };
5868   static const MCPhysReg VR[] = {
5869     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5870     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5871   };
5872   const unsigned NumGPRs = array_lengthof(GPR_32);
5873   const unsigned NumFPRs = 13;
5874   const unsigned NumVRs  = array_lengthof(VR);
5875
5876   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5877
5878   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5879   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5880
5881   SmallVector<SDValue, 8> MemOpChains;
5882   for (unsigned i = 0; i != NumOps; ++i) {
5883     SDValue Arg = OutVals[i];
5884     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5885
5886     // PtrOff will be used to store the current argument to the stack if a
5887     // register cannot be found for it.
5888     SDValue PtrOff;
5889
5890     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5891
5892     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5893
5894     // On PPC64, promote integers to 64-bit values.
5895     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5896       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5897       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5898       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5899     }
5900
5901     // FIXME memcpy is used way more than necessary.  Correctness first.
5902     // Note: "by value" is code for passing a structure by value, not
5903     // basic types.
5904     if (Flags.isByVal()) {
5905       unsigned Size = Flags.getByValSize();
5906       // Very small objects are passed right-justified.  Everything else is
5907       // passed left-justified.
5908       if (Size==1 || Size==2) {
5909         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5910         if (GPR_idx != NumGPRs) {
5911           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5912                                         MachinePointerInfo(), VT);
5913           MemOpChains.push_back(Load.getValue(1));
5914           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5915
5916           ArgOffset += PtrByteSize;
5917         } else {
5918           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5919                                           PtrOff.getValueType());
5920           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5921           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5922                                                             CallSeqStart,
5923                                                             Flags, DAG, dl);
5924           ArgOffset += PtrByteSize;
5925         }
5926         continue;
5927       }
5928       // Copy entire object into memory.  There are cases where gcc-generated
5929       // code assumes it is there, even if it could be put entirely into
5930       // registers.  (This is not what the doc says.)
5931       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5932                                                         CallSeqStart,
5933                                                         Flags, DAG, dl);
5934
5935       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5936       // copy the pieces of the object that fit into registers from the
5937       // parameter save area.
5938       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5939         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5940         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5941         if (GPR_idx != NumGPRs) {
5942           SDValue Load =
5943               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5944           MemOpChains.push_back(Load.getValue(1));
5945           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5946           ArgOffset += PtrByteSize;
5947         } else {
5948           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5949           break;
5950         }
5951       }
5952       continue;
5953     }
5954
5955     switch (Arg.getSimpleValueType().SimpleTy) {
5956     default: llvm_unreachable("Unexpected ValueType for argument!");
5957     case MVT::i1:
5958     case MVT::i32:
5959     case MVT::i64:
5960       if (GPR_idx != NumGPRs) {
5961         if (Arg.getValueType() == MVT::i1)
5962           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5963
5964         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5965       } else {
5966         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5967                          isPPC64, isTailCall, false, MemOpChains,
5968                          TailCallArguments, dl);
5969       }
5970       ArgOffset += PtrByteSize;
5971       break;
5972     case MVT::f32:
5973     case MVT::f64:
5974       if (FPR_idx != NumFPRs) {
5975         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5976
5977         if (isVarArg) {
5978           SDValue Store =
5979               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5980           MemOpChains.push_back(Store);
5981
5982           // Float varargs are always shadowed in available integer registers
5983           if (GPR_idx != NumGPRs) {
5984             SDValue Load =
5985                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5986             MemOpChains.push_back(Load.getValue(1));
5987             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5988           }
5989           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5990             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5991             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5992             SDValue Load =
5993                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5994             MemOpChains.push_back(Load.getValue(1));
5995             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5996           }
5997         } else {
5998           // If we have any FPRs remaining, we may also have GPRs remaining.
5999           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6000           // GPRs.
6001           if (GPR_idx != NumGPRs)
6002             ++GPR_idx;
6003           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6004               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6005             ++GPR_idx;
6006         }
6007       } else
6008         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6009                          isPPC64, isTailCall, false, MemOpChains,
6010                          TailCallArguments, dl);
6011       if (isPPC64)
6012         ArgOffset += 8;
6013       else
6014         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6015       break;
6016     case MVT::v4f32:
6017     case MVT::v4i32:
6018     case MVT::v8i16:
6019     case MVT::v16i8:
6020       if (isVarArg) {
6021         // These go aligned on the stack, or in the corresponding R registers
6022         // when within range.  The Darwin PPC ABI doc claims they also go in
6023         // V registers; in fact gcc does this only for arguments that are
6024         // prototyped, not for those that match the ...  We do it for all
6025         // arguments, seems to work.
6026         while (ArgOffset % 16 !=0) {
6027           ArgOffset += PtrByteSize;
6028           if (GPR_idx != NumGPRs)
6029             GPR_idx++;
6030         }
6031         // We could elide this store in the case where the object fits
6032         // entirely in R registers.  Maybe later.
6033         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6034                              DAG.getConstant(ArgOffset, dl, PtrVT));
6035         SDValue Store =
6036             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6037         MemOpChains.push_back(Store);
6038         if (VR_idx != NumVRs) {
6039           SDValue Load =
6040               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6041           MemOpChains.push_back(Load.getValue(1));
6042           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6043         }
6044         ArgOffset += 16;
6045         for (unsigned i=0; i<16; i+=PtrByteSize) {
6046           if (GPR_idx == NumGPRs)
6047             break;
6048           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6049                                    DAG.getConstant(i, dl, PtrVT));
6050           SDValue Load =
6051               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6052           MemOpChains.push_back(Load.getValue(1));
6053           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6054         }
6055         break;
6056       }
6057
6058       // Non-varargs Altivec params generally go in registers, but have
6059       // stack space allocated at the end.
6060       if (VR_idx != NumVRs) {
6061         // Doesn't have GPR space allocated.
6062         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6063       } else if (nAltivecParamsAtEnd==0) {
6064         // We are emitting Altivec params in order.
6065         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6066                          isPPC64, isTailCall, true, MemOpChains,
6067                          TailCallArguments, dl);
6068         ArgOffset += 16;
6069       }
6070       break;
6071     }
6072   }
6073   // If all Altivec parameters fit in registers, as they usually do,
6074   // they get stack space following the non-Altivec parameters.  We
6075   // don't track this here because nobody below needs it.
6076   // If there are more Altivec parameters than fit in registers emit
6077   // the stores here.
6078   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6079     unsigned j = 0;
6080     // Offset is aligned; skip 1st 12 params which go in V registers.
6081     ArgOffset = ((ArgOffset+15)/16)*16;
6082     ArgOffset += 12*16;
6083     for (unsigned i = 0; i != NumOps; ++i) {
6084       SDValue Arg = OutVals[i];
6085       EVT ArgType = Outs[i].VT;
6086       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6087           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6088         if (++j > NumVRs) {
6089           SDValue PtrOff;
6090           // We are emitting Altivec params in order.
6091           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6092                            isPPC64, isTailCall, true, MemOpChains,
6093                            TailCallArguments, dl);
6094           ArgOffset += 16;
6095         }
6096       }
6097     }
6098   }
6099
6100   if (!MemOpChains.empty())
6101     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6102
6103   // On Darwin, R12 must contain the address of an indirect callee.  This does
6104   // not mean the MTCTR instruction must use R12; it's easier to model this as
6105   // an extra parameter, so do that.
6106   if (!isTailCall &&
6107       !isFunctionGlobalAddress(Callee) &&
6108       !isa<ExternalSymbolSDNode>(Callee) &&
6109       !isBLACompatibleAddress(Callee, DAG))
6110     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6111                                                    PPC::R12), Callee));
6112
6113   // Build a sequence of copy-to-reg nodes chained together with token chain
6114   // and flag operands which copy the outgoing args into the appropriate regs.
6115   SDValue InFlag;
6116   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6117     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6118                              RegsToPass[i].second, InFlag);
6119     InFlag = Chain.getValue(1);
6120   }
6121
6122   if (isTailCall)
6123     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6124                     TailCallArguments);
6125
6126   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6127                     /* unused except on PPC64 ELFv1 */ false, DAG,
6128                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6129                     NumBytes, Ins, InVals, CS);
6130 }
6131
6132 bool
6133 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6134                                   MachineFunction &MF, bool isVarArg,
6135                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6136                                   LLVMContext &Context) const {
6137   SmallVector<CCValAssign, 16> RVLocs;
6138   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6139   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6140 }
6141
6142 SDValue
6143 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6144                                bool isVarArg,
6145                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6146                                const SmallVectorImpl<SDValue> &OutVals,
6147                                const SDLoc &dl, SelectionDAG &DAG) const {
6148   SmallVector<CCValAssign, 16> RVLocs;
6149   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6150                  *DAG.getContext());
6151   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6152
6153   SDValue Flag;
6154   SmallVector<SDValue, 4> RetOps(1, Chain);
6155
6156   // Copy the result values into the output registers.
6157   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6158     CCValAssign &VA = RVLocs[i];
6159     assert(VA.isRegLoc() && "Can only return in registers!");
6160
6161     SDValue Arg = OutVals[i];
6162
6163     switch (VA.getLocInfo()) {
6164     default: llvm_unreachable("Unknown loc info!");
6165     case CCValAssign::Full: break;
6166     case CCValAssign::AExt:
6167       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6168       break;
6169     case CCValAssign::ZExt:
6170       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6171       break;
6172     case CCValAssign::SExt:
6173       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6174       break;
6175     }
6176
6177     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6178     Flag = Chain.getValue(1);
6179     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6180   }
6181
6182   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6183   const MCPhysReg *I =
6184     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6185   if (I) {
6186     for (; *I; ++I) {
6187
6188       if (PPC::G8RCRegClass.contains(*I))
6189         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6190       else if (PPC::F8RCRegClass.contains(*I))
6191         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6192       else if (PPC::CRRCRegClass.contains(*I))
6193         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6194       else if (PPC::VRRCRegClass.contains(*I))
6195         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6196       else
6197         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6198     }
6199   }
6200
6201   RetOps[0] = Chain;  // Update chain.
6202
6203   // Add the flag if we have it.
6204   if (Flag.getNode())
6205     RetOps.push_back(Flag);
6206
6207   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6208 }
6209
6210 SDValue
6211 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6212                                                 SelectionDAG &DAG) const {
6213   SDLoc dl(Op);
6214
6215   // Get the corect type for integers.
6216   EVT IntVT = Op.getValueType();
6217
6218   // Get the inputs.
6219   SDValue Chain = Op.getOperand(0);
6220   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6221   // Build a DYNAREAOFFSET node.
6222   SDValue Ops[2] = {Chain, FPSIdx};
6223   SDVTList VTs = DAG.getVTList(IntVT);
6224   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6225 }
6226
6227 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6228                                              SelectionDAG &DAG) const {
6229   // When we pop the dynamic allocation we need to restore the SP link.
6230   SDLoc dl(Op);
6231
6232   // Get the corect type for pointers.
6233   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6234
6235   // Construct the stack pointer operand.
6236   bool isPPC64 = Subtarget.isPPC64();
6237   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6238   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6239
6240   // Get the operands for the STACKRESTORE.
6241   SDValue Chain = Op.getOperand(0);
6242   SDValue SaveSP = Op.getOperand(1);
6243
6244   // Load the old link SP.
6245   SDValue LoadLinkSP =
6246       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6247
6248   // Restore the stack pointer.
6249   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6250
6251   // Store the old link SP.
6252   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6253 }
6254
6255 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6256   MachineFunction &MF = DAG.getMachineFunction();
6257   bool isPPC64 = Subtarget.isPPC64();
6258   EVT PtrVT = getPointerTy(MF.getDataLayout());
6259
6260   // Get current frame pointer save index.  The users of this index will be
6261   // primarily DYNALLOC instructions.
6262   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6263   int RASI = FI->getReturnAddrSaveIndex();
6264
6265   // If the frame pointer save index hasn't been defined yet.
6266   if (!RASI) {
6267     // Find out what the fix offset of the frame pointer save area.
6268     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6269     // Allocate the frame index for frame pointer save area.
6270     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6271     // Save the result.
6272     FI->setReturnAddrSaveIndex(RASI);
6273   }
6274   return DAG.getFrameIndex(RASI, PtrVT);
6275 }
6276
6277 SDValue
6278 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6279   MachineFunction &MF = DAG.getMachineFunction();
6280   bool isPPC64 = Subtarget.isPPC64();
6281   EVT PtrVT = getPointerTy(MF.getDataLayout());
6282
6283   // Get current frame pointer save index.  The users of this index will be
6284   // primarily DYNALLOC instructions.
6285   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6286   int FPSI = FI->getFramePointerSaveIndex();
6287
6288   // If the frame pointer save index hasn't been defined yet.
6289   if (!FPSI) {
6290     // Find out what the fix offset of the frame pointer save area.
6291     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6292     // Allocate the frame index for frame pointer save area.
6293     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6294     // Save the result.
6295     FI->setFramePointerSaveIndex(FPSI);
6296   }
6297   return DAG.getFrameIndex(FPSI, PtrVT);
6298 }
6299
6300 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6301                                                    SelectionDAG &DAG) const {
6302   // Get the inputs.
6303   SDValue Chain = Op.getOperand(0);
6304   SDValue Size  = Op.getOperand(1);
6305   SDLoc dl(Op);
6306
6307   // Get the corect type for pointers.
6308   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6309   // Negate the size.
6310   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6311                                 DAG.getConstant(0, dl, PtrVT), Size);
6312   // Construct a node for the frame pointer save index.
6313   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6314   // Build a DYNALLOC node.
6315   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6316   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6317   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6318 }
6319
6320 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6321                                                      SelectionDAG &DAG) const {
6322   MachineFunction &MF = DAG.getMachineFunction();
6323
6324   bool isPPC64 = Subtarget.isPPC64();
6325   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6326
6327   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6328   return DAG.getFrameIndex(FI, PtrVT);
6329 }
6330
6331 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6332                                                SelectionDAG &DAG) const {
6333   SDLoc DL(Op);
6334   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6335                      DAG.getVTList(MVT::i32, MVT::Other),
6336                      Op.getOperand(0), Op.getOperand(1));
6337 }
6338
6339 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6340                                                 SelectionDAG &DAG) const {
6341   SDLoc DL(Op);
6342   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6343                      Op.getOperand(0), Op.getOperand(1));
6344 }
6345
6346 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6347   if (Op.getValueType().isVector())
6348     return LowerVectorLoad(Op, DAG);
6349
6350   assert(Op.getValueType() == MVT::i1 &&
6351          "Custom lowering only for i1 loads");
6352
6353   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6354
6355   SDLoc dl(Op);
6356   LoadSDNode *LD = cast<LoadSDNode>(Op);
6357
6358   SDValue Chain = LD->getChain();
6359   SDValue BasePtr = LD->getBasePtr();
6360   MachineMemOperand *MMO = LD->getMemOperand();
6361
6362   SDValue NewLD =
6363       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6364                      BasePtr, MVT::i8, MMO);
6365   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6366
6367   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6368   return DAG.getMergeValues(Ops, dl);
6369 }
6370
6371 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6372   if (Op.getOperand(1).getValueType().isVector())
6373     return LowerVectorStore(Op, DAG);
6374
6375   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6376          "Custom lowering only for i1 stores");
6377
6378   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6379
6380   SDLoc dl(Op);
6381   StoreSDNode *ST = cast<StoreSDNode>(Op);
6382
6383   SDValue Chain = ST->getChain();
6384   SDValue BasePtr = ST->getBasePtr();
6385   SDValue Value = ST->getValue();
6386   MachineMemOperand *MMO = ST->getMemOperand();
6387
6388   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6389                       Value);
6390   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6391 }
6392
6393 // FIXME: Remove this once the ANDI glue bug is fixed:
6394 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6395   assert(Op.getValueType() == MVT::i1 &&
6396          "Custom lowering only for i1 results");
6397
6398   SDLoc DL(Op);
6399   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6400                      Op.getOperand(0));
6401 }
6402
6403 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6404 /// possible.
6405 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6406   // Not FP? Not a fsel.
6407   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6408       !Op.getOperand(2).getValueType().isFloatingPoint())
6409     return Op;
6410
6411   // We might be able to do better than this under some circumstances, but in
6412   // general, fsel-based lowering of select is a finite-math-only optimization.
6413   // For more information, see section F.3 of the 2.06 ISA specification.
6414   if (!DAG.getTarget().Options.NoInfsFPMath ||
6415       !DAG.getTarget().Options.NoNaNsFPMath)
6416     return Op;
6417   // TODO: Propagate flags from the select rather than global settings.
6418   SDNodeFlags Flags;
6419   Flags.setNoInfs(true);
6420   Flags.setNoNaNs(true);
6421
6422   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6423
6424   EVT ResVT = Op.getValueType();
6425   EVT CmpVT = Op.getOperand(0).getValueType();
6426   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6427   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6428   SDLoc dl(Op);
6429
6430   // If the RHS of the comparison is a 0.0, we don't need to do the
6431   // subtraction at all.
6432   SDValue Sel1;
6433   if (isFloatingPointZero(RHS))
6434     switch (CC) {
6435     default: break;       // SETUO etc aren't handled by fsel.
6436     case ISD::SETNE:
6437       std::swap(TV, FV);
6438     case ISD::SETEQ:
6439       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6440         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6441       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6442       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6443         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6444       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6445                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6446     case ISD::SETULT:
6447     case ISD::SETLT:
6448       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6449     case ISD::SETOGE:
6450     case ISD::SETGE:
6451       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6452         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6453       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6454     case ISD::SETUGT:
6455     case ISD::SETGT:
6456       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6457     case ISD::SETOLE:
6458     case ISD::SETLE:
6459       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6460         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6461       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6462                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6463     }
6464
6465   SDValue Cmp;
6466   switch (CC) {
6467   default: break;       // SETUO etc aren't handled by fsel.
6468   case ISD::SETNE:
6469     std::swap(TV, FV);
6470   case ISD::SETEQ:
6471     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6472     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6473       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6474     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6475     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6476       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6477     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6478                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6479   case ISD::SETULT:
6480   case ISD::SETLT:
6481     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6482     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6483       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6484     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6485   case ISD::SETOGE:
6486   case ISD::SETGE:
6487     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6488     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6489       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6490     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6491   case ISD::SETUGT:
6492   case ISD::SETGT:
6493     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6494     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6495       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6496     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6497   case ISD::SETOLE:
6498   case ISD::SETLE:
6499     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6500     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6501       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6502     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6503   }
6504   return Op;
6505 }
6506
6507 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6508                                                SelectionDAG &DAG,
6509                                                const SDLoc &dl) const {
6510   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6511   SDValue Src = Op.getOperand(0);
6512   if (Src.getValueType() == MVT::f32)
6513     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6514
6515   SDValue Tmp;
6516   switch (Op.getSimpleValueType().SimpleTy) {
6517   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6518   case MVT::i32:
6519     Tmp = DAG.getNode(
6520         Op.getOpcode() == ISD::FP_TO_SINT
6521             ? PPCISD::FCTIWZ
6522             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6523         dl, MVT::f64, Src);
6524     break;
6525   case MVT::i64:
6526     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6527            "i64 FP_TO_UINT is supported only with FPCVT");
6528     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6529                                                         PPCISD::FCTIDUZ,
6530                       dl, MVT::f64, Src);
6531     break;
6532   }
6533
6534   // Convert the FP value to an int value through memory.
6535   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6536     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6537   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6538   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6539   MachinePointerInfo MPI =
6540       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6541
6542   // Emit a store to the stack slot.
6543   SDValue Chain;
6544   if (i32Stack) {
6545     MachineFunction &MF = DAG.getMachineFunction();
6546     MachineMemOperand *MMO =
6547       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6548     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6549     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6550               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6551   } else
6552     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6553
6554   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6555   // add in a bias on big endian.
6556   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6557     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6558                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6559     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6560   }
6561
6562   RLI.Chain = Chain;
6563   RLI.Ptr = FIPtr;
6564   RLI.MPI = MPI;
6565 }
6566
6567 /// \brief Custom lowers floating point to integer conversions to use
6568 /// the direct move instructions available in ISA 2.07 to avoid the
6569 /// need for load/store combinations.
6570 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6571                                                     SelectionDAG &DAG,
6572                                                     const SDLoc &dl) const {
6573   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6574   SDValue Src = Op.getOperand(0);
6575
6576   if (Src.getValueType() == MVT::f32)
6577     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6578
6579   SDValue Tmp;
6580   switch (Op.getSimpleValueType().SimpleTy) {
6581   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6582   case MVT::i32:
6583     Tmp = DAG.getNode(
6584         Op.getOpcode() == ISD::FP_TO_SINT
6585             ? PPCISD::FCTIWZ
6586             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6587         dl, MVT::f64, Src);
6588     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6589     break;
6590   case MVT::i64:
6591     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6592            "i64 FP_TO_UINT is supported only with FPCVT");
6593     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6594                                                         PPCISD::FCTIDUZ,
6595                       dl, MVT::f64, Src);
6596     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6597     break;
6598   }
6599   return Tmp;
6600 }
6601
6602 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6603                                           const SDLoc &dl) const {
6604   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6605     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6606
6607   ReuseLoadInfo RLI;
6608   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6609
6610   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6611                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6612 }
6613
6614 // We're trying to insert a regular store, S, and then a load, L. If the
6615 // incoming value, O, is a load, we might just be able to have our load use the
6616 // address used by O. However, we don't know if anything else will store to
6617 // that address before we can load from it. To prevent this situation, we need
6618 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6619 // the same chain operand as O, we create a token factor from the chain results
6620 // of O and L, and we replace all uses of O's chain result with that token
6621 // factor (see spliceIntoChain below for this last part).
6622 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6623                                             ReuseLoadInfo &RLI,
6624                                             SelectionDAG &DAG,
6625                                             ISD::LoadExtType ET) const {
6626   SDLoc dl(Op);
6627   if (ET == ISD::NON_EXTLOAD &&
6628       (Op.getOpcode() == ISD::FP_TO_UINT ||
6629        Op.getOpcode() == ISD::FP_TO_SINT) &&
6630       isOperationLegalOrCustom(Op.getOpcode(),
6631                                Op.getOperand(0).getValueType())) {
6632
6633     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6634     return true;
6635   }
6636
6637   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6638   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6639       LD->isNonTemporal())
6640     return false;
6641   if (LD->getMemoryVT() != MemVT)
6642     return false;
6643
6644   RLI.Ptr = LD->getBasePtr();
6645   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6646     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6647            "Non-pre-inc AM on PPC?");
6648     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6649                           LD->getOffset());
6650   }
6651
6652   RLI.Chain = LD->getChain();
6653   RLI.MPI = LD->getPointerInfo();
6654   RLI.IsDereferenceable = LD->isDereferenceable();
6655   RLI.IsInvariant = LD->isInvariant();
6656   RLI.Alignment = LD->getAlignment();
6657   RLI.AAInfo = LD->getAAInfo();
6658   RLI.Ranges = LD->getRanges();
6659
6660   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6661   return true;
6662 }
6663
6664 // Given the head of the old chain, ResChain, insert a token factor containing
6665 // it and NewResChain, and make users of ResChain now be users of that token
6666 // factor.
6667 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6668                                         SDValue NewResChain,
6669                                         SelectionDAG &DAG) const {
6670   if (!ResChain)
6671     return;
6672
6673   SDLoc dl(NewResChain);
6674
6675   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6676                            NewResChain, DAG.getUNDEF(MVT::Other));
6677   assert(TF.getNode() != NewResChain.getNode() &&
6678          "A new TF really is required here");
6679
6680   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6681   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6682 }
6683
6684 /// \brief Analyze profitability of direct move
6685 /// prefer float load to int load plus direct move
6686 /// when there is no integer use of int load
6687 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6688   SDNode *Origin = Op.getOperand(0).getNode();
6689   if (Origin->getOpcode() != ISD::LOAD)
6690     return true;
6691
6692   // If there is no LXSIBZX/LXSIHZX, like Power8,
6693   // prefer direct move if the memory size is 1 or 2 bytes.
6694   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6695   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6696     return true;
6697
6698   for (SDNode::use_iterator UI = Origin->use_begin(),
6699                             UE = Origin->use_end();
6700        UI != UE; ++UI) {
6701
6702     // Only look at the users of the loaded value.
6703     if (UI.getUse().get().getResNo() != 0)
6704       continue;
6705
6706     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6707         UI->getOpcode() != ISD::UINT_TO_FP)
6708       return true;
6709   }
6710
6711   return false;
6712 }
6713
6714 /// \brief Custom lowers integer to floating point conversions to use
6715 /// the direct move instructions available in ISA 2.07 to avoid the
6716 /// need for load/store combinations.
6717 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6718                                                     SelectionDAG &DAG,
6719                                                     const SDLoc &dl) const {
6720   assert((Op.getValueType() == MVT::f32 ||
6721           Op.getValueType() == MVT::f64) &&
6722          "Invalid floating point type as target of conversion");
6723   assert(Subtarget.hasFPCVT() &&
6724          "Int to FP conversions with direct moves require FPCVT");
6725   SDValue FP;
6726   SDValue Src = Op.getOperand(0);
6727   bool SinglePrec = Op.getValueType() == MVT::f32;
6728   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6729   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6730   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6731                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6732
6733   if (WordInt) {
6734     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6735                      dl, MVT::f64, Src);
6736     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6737   }
6738   else {
6739     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6740     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6741   }
6742
6743   return FP;
6744 }
6745
6746 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6747                                           SelectionDAG &DAG) const {
6748   SDLoc dl(Op);
6749
6750   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6751     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6752       return SDValue();
6753
6754     SDValue Value = Op.getOperand(0);
6755     // The values are now known to be -1 (false) or 1 (true). To convert this
6756     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6757     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6758     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6759
6760     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6761
6762     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6763
6764     if (Op.getValueType() != MVT::v4f64)
6765       Value = DAG.getNode(ISD::FP_ROUND, dl,
6766                           Op.getValueType(), Value,
6767                           DAG.getIntPtrConstant(1, dl));
6768     return Value;
6769   }
6770
6771   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6772   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6773     return SDValue();
6774
6775   if (Op.getOperand(0).getValueType() == MVT::i1)
6776     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6777                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6778                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6779
6780   // If we have direct moves, we can do all the conversion, skip the store/load
6781   // however, without FPCVT we can't do most conversions.
6782   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6783       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6784     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6785
6786   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6787          "UINT_TO_FP is supported only with FPCVT");
6788
6789   // If we have FCFIDS, then use it when converting to single-precision.
6790   // Otherwise, convert to double-precision and then round.
6791   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6792                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6793                                                             : PPCISD::FCFIDS)
6794                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6795                                                             : PPCISD::FCFID);
6796   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6797                   ? MVT::f32
6798                   : MVT::f64;
6799
6800   if (Op.getOperand(0).getValueType() == MVT::i64) {
6801     SDValue SINT = Op.getOperand(0);
6802     // When converting to single-precision, we actually need to convert
6803     // to double-precision first and then round to single-precision.
6804     // To avoid double-rounding effects during that operation, we have
6805     // to prepare the input operand.  Bits that might be truncated when
6806     // converting to double-precision are replaced by a bit that won't
6807     // be lost at this stage, but is below the single-precision rounding
6808     // position.
6809     //
6810     // However, if -enable-unsafe-fp-math is in effect, accept double
6811     // rounding to avoid the extra overhead.
6812     if (Op.getValueType() == MVT::f32 &&
6813         !Subtarget.hasFPCVT() &&
6814         !DAG.getTarget().Options.UnsafeFPMath) {
6815
6816       // Twiddle input to make sure the low 11 bits are zero.  (If this
6817       // is the case, we are guaranteed the value will fit into the 53 bit
6818       // mantissa of an IEEE double-precision value without rounding.)
6819       // If any of those low 11 bits were not zero originally, make sure
6820       // bit 12 (value 2048) is set instead, so that the final rounding
6821       // to single-precision gets the correct result.
6822       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6823                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6824       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6825                           Round, DAG.getConstant(2047, dl, MVT::i64));
6826       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6827       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6828                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6829
6830       // However, we cannot use that value unconditionally: if the magnitude
6831       // of the input value is small, the bit-twiddling we did above might
6832       // end up visibly changing the output.  Fortunately, in that case, we
6833       // don't need to twiddle bits since the original input will convert
6834       // exactly to double-precision floating-point already.  Therefore,
6835       // construct a conditional to use the original value if the top 11
6836       // bits are all sign-bit copies, and use the rounded value computed
6837       // above otherwise.
6838       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6839                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6840       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6841                          Cond, DAG.getConstant(1, dl, MVT::i64));
6842       Cond = DAG.getSetCC(dl, MVT::i32,
6843                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6844
6845       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6846     }
6847
6848     ReuseLoadInfo RLI;
6849     SDValue Bits;
6850
6851     MachineFunction &MF = DAG.getMachineFunction();
6852     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6853       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6854                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6855       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6856     } else if (Subtarget.hasLFIWAX() &&
6857                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6858       MachineMemOperand *MMO =
6859         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6860                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6861       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6862       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6863                                      DAG.getVTList(MVT::f64, MVT::Other),
6864                                      Ops, MVT::i32, MMO);
6865       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6866     } else if (Subtarget.hasFPCVT() &&
6867                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6868       MachineMemOperand *MMO =
6869         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6870                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6871       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6872       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6873                                      DAG.getVTList(MVT::f64, MVT::Other),
6874                                      Ops, MVT::i32, MMO);
6875       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6876     } else if (((Subtarget.hasLFIWAX() &&
6877                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6878                 (Subtarget.hasFPCVT() &&
6879                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6880                SINT.getOperand(0).getValueType() == MVT::i32) {
6881       MachineFrameInfo &MFI = MF.getFrameInfo();
6882       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6883
6884       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6885       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6886
6887       SDValue Store =
6888           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6889                        MachinePointerInfo::getFixedStack(
6890                            DAG.getMachineFunction(), FrameIdx));
6891
6892       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6893              "Expected an i32 store");
6894
6895       RLI.Ptr = FIdx;
6896       RLI.Chain = Store;
6897       RLI.MPI =
6898           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6899       RLI.Alignment = 4;
6900
6901       MachineMemOperand *MMO =
6902         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6903                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6904       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6905       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6906                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6907                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6908                                      Ops, MVT::i32, MMO);
6909     } else
6910       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6911
6912     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6913
6914     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6915       FP = DAG.getNode(ISD::FP_ROUND, dl,
6916                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6917     return FP;
6918   }
6919
6920   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6921          "Unhandled INT_TO_FP type in custom expander!");
6922   // Since we only generate this in 64-bit mode, we can take advantage of
6923   // 64-bit registers.  In particular, sign extend the input value into the
6924   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6925   // then lfd it and fcfid it.
6926   MachineFunction &MF = DAG.getMachineFunction();
6927   MachineFrameInfo &MFI = MF.getFrameInfo();
6928   EVT PtrVT = getPointerTy(MF.getDataLayout());
6929
6930   SDValue Ld;
6931   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6932     ReuseLoadInfo RLI;
6933     bool ReusingLoad;
6934     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6935                                             DAG))) {
6936       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6937       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6938
6939       SDValue Store =
6940           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6941                        MachinePointerInfo::getFixedStack(
6942                            DAG.getMachineFunction(), FrameIdx));
6943
6944       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6945              "Expected an i32 store");
6946
6947       RLI.Ptr = FIdx;
6948       RLI.Chain = Store;
6949       RLI.MPI =
6950           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6951       RLI.Alignment = 4;
6952     }
6953
6954     MachineMemOperand *MMO =
6955       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6956                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6957     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6958     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6959                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6960                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6961                                  Ops, MVT::i32, MMO);
6962     if (ReusingLoad)
6963       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6964   } else {
6965     assert(Subtarget.isPPC64() &&
6966            "i32->FP without LFIWAX supported only on PPC64");
6967
6968     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6969     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6970
6971     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6972                                 Op.getOperand(0));
6973
6974     // STD the extended value into the stack slot.
6975     SDValue Store = DAG.getStore(
6976         DAG.getEntryNode(), dl, Ext64, FIdx,
6977         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6978
6979     // Load the value as a double.
6980     Ld = DAG.getLoad(
6981         MVT::f64, dl, Store, FIdx,
6982         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6983   }
6984
6985   // FCFID it and return it.
6986   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6987   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6988     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6989                      DAG.getIntPtrConstant(0, dl));
6990   return FP;
6991 }
6992
6993 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6994                                             SelectionDAG &DAG) const {
6995   SDLoc dl(Op);
6996   /*
6997    The rounding mode is in bits 30:31 of FPSR, and has the following
6998    settings:
6999      00 Round to nearest
7000      01 Round to 0
7001      10 Round to +inf
7002      11 Round to -inf
7003
7004   FLT_ROUNDS, on the other hand, expects the following:
7005     -1 Undefined
7006      0 Round to 0
7007      1 Round to nearest
7008      2 Round to +inf
7009      3 Round to -inf
7010
7011   To perform the conversion, we do:
7012     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7013   */
7014
7015   MachineFunction &MF = DAG.getMachineFunction();
7016   EVT VT = Op.getValueType();
7017   EVT PtrVT = getPointerTy(MF.getDataLayout());
7018
7019   // Save FP Control Word to register
7020   EVT NodeTys[] = {
7021     MVT::f64,    // return register
7022     MVT::Glue    // unused in this context
7023   };
7024   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7025
7026   // Save FP register to stack slot
7027   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7028   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7029   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7030                                MachinePointerInfo());
7031
7032   // Load FP Control Word from low 32 bits of stack slot.
7033   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7034   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7035   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7036
7037   // Transform as necessary
7038   SDValue CWD1 =
7039     DAG.getNode(ISD::AND, dl, MVT::i32,
7040                 CWD, DAG.getConstant(3, dl, MVT::i32));
7041   SDValue CWD2 =
7042     DAG.getNode(ISD::SRL, dl, MVT::i32,
7043                 DAG.getNode(ISD::AND, dl, MVT::i32,
7044                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7045                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7046                             DAG.getConstant(3, dl, MVT::i32)),
7047                 DAG.getConstant(1, dl, MVT::i32));
7048
7049   SDValue RetVal =
7050     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7051
7052   return DAG.getNode((VT.getSizeInBits() < 16 ?
7053                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7054 }
7055
7056 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7057   EVT VT = Op.getValueType();
7058   unsigned BitWidth = VT.getSizeInBits();
7059   SDLoc dl(Op);
7060   assert(Op.getNumOperands() == 3 &&
7061          VT == Op.getOperand(1).getValueType() &&
7062          "Unexpected SHL!");
7063
7064   // Expand into a bunch of logical ops.  Note that these ops
7065   // depend on the PPC behavior for oversized shift amounts.
7066   SDValue Lo = Op.getOperand(0);
7067   SDValue Hi = Op.getOperand(1);
7068   SDValue Amt = Op.getOperand(2);
7069   EVT AmtVT = Amt.getValueType();
7070
7071   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7072                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7073   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7074   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7075   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7076   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7077                              DAG.getConstant(-BitWidth, dl, AmtVT));
7078   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7079   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7080   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7081   SDValue OutOps[] = { OutLo, OutHi };
7082   return DAG.getMergeValues(OutOps, dl);
7083 }
7084
7085 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7086   EVT VT = Op.getValueType();
7087   SDLoc dl(Op);
7088   unsigned BitWidth = VT.getSizeInBits();
7089   assert(Op.getNumOperands() == 3 &&
7090          VT == Op.getOperand(1).getValueType() &&
7091          "Unexpected SRL!");
7092
7093   // Expand into a bunch of logical ops.  Note that these ops
7094   // depend on the PPC behavior for oversized shift amounts.
7095   SDValue Lo = Op.getOperand(0);
7096   SDValue Hi = Op.getOperand(1);
7097   SDValue Amt = Op.getOperand(2);
7098   EVT AmtVT = Amt.getValueType();
7099
7100   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7101                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7102   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7103   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7104   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7105   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7106                              DAG.getConstant(-BitWidth, dl, AmtVT));
7107   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7108   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7109   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7110   SDValue OutOps[] = { OutLo, OutHi };
7111   return DAG.getMergeValues(OutOps, dl);
7112 }
7113
7114 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7115   SDLoc dl(Op);
7116   EVT VT = Op.getValueType();
7117   unsigned BitWidth = VT.getSizeInBits();
7118   assert(Op.getNumOperands() == 3 &&
7119          VT == Op.getOperand(1).getValueType() &&
7120          "Unexpected SRA!");
7121
7122   // Expand into a bunch of logical ops, followed by a select_cc.
7123   SDValue Lo = Op.getOperand(0);
7124   SDValue Hi = Op.getOperand(1);
7125   SDValue Amt = Op.getOperand(2);
7126   EVT AmtVT = Amt.getValueType();
7127
7128   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7129                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7130   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7131   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7132   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7133   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7134                              DAG.getConstant(-BitWidth, dl, AmtVT));
7135   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7136   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7137   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7138                                   Tmp4, Tmp6, ISD::SETLE);
7139   SDValue OutOps[] = { OutLo, OutHi };
7140   return DAG.getMergeValues(OutOps, dl);
7141 }
7142
7143 //===----------------------------------------------------------------------===//
7144 // Vector related lowering.
7145 //
7146
7147 /// BuildSplatI - Build a canonical splati of Val with an element size of
7148 /// SplatSize.  Cast the result to VT.
7149 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7150                            SelectionDAG &DAG, const SDLoc &dl) {
7151   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7152
7153   static const MVT VTys[] = { // canonical VT to use for each size.
7154     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7155   };
7156
7157   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7158
7159   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7160   if (Val == -1)
7161     SplatSize = 1;
7162
7163   EVT CanonicalVT = VTys[SplatSize-1];
7164
7165   // Build a canonical splat for this value.
7166   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7167 }
7168
7169 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7170 /// specified intrinsic ID.
7171 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7172                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7173   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7174   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7175                      DAG.getConstant(IID, dl, MVT::i32), Op);
7176 }
7177
7178 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7179 /// specified intrinsic ID.
7180 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7181                                 SelectionDAG &DAG, const SDLoc &dl,
7182                                 EVT DestVT = MVT::Other) {
7183   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7184   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7185                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7186 }
7187
7188 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7189 /// specified intrinsic ID.
7190 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7191                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7192                                 EVT DestVT = MVT::Other) {
7193   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7194   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7195                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7196 }
7197
7198 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7199 /// amount.  The result has the specified value type.
7200 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7201                            SelectionDAG &DAG, const SDLoc &dl) {
7202   // Force LHS/RHS to be the right type.
7203   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7204   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7205
7206   int Ops[16];
7207   for (unsigned i = 0; i != 16; ++i)
7208     Ops[i] = i + Amt;
7209   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7210   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7211 }
7212
7213 /// Do we have an efficient pattern in a .td file for this node?
7214 ///
7215 /// \param V - pointer to the BuildVectorSDNode being matched
7216 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7217 ///
7218 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7219 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7220 /// the opposite is true (expansion is beneficial) are:
7221 /// - The node builds a vector out of integers that are not 32 or 64-bits
7222 /// - The node builds a vector out of constants
7223 /// - The node is a "load-and-splat"
7224 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7225 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7226                                             bool HasDirectMove) {
7227   EVT VecVT = V->getValueType(0);
7228   bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7229     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7230   if (!RightType)
7231     return false;
7232
7233   bool IsSplat = true;
7234   bool IsLoad = false;
7235   SDValue Op0 = V->getOperand(0);
7236
7237   // This function is called in a block that confirms the node is not a constant
7238   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7239   // different constants.
7240   if (V->isConstant())
7241     return false;
7242   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7243     if (V->getOperand(i).isUndef())
7244       return false;
7245     // We want to expand nodes that represent load-and-splat even if the
7246     // loaded value is a floating point truncation or conversion to int.
7247     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7248         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7249          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7250         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7251          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7252         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7253          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7254       IsLoad = true;
7255     // If the operands are different or the input is not a load and has more
7256     // uses than just this BV node, then it isn't a splat.
7257     if (V->getOperand(i) != Op0 ||
7258         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7259       IsSplat = false;
7260   }
7261   return !(IsSplat && IsLoad);
7262 }
7263
7264 // If this is a case we can't handle, return null and let the default
7265 // expansion code take care of it.  If we CAN select this case, and if it
7266 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7267 // this case more efficiently than a constant pool load, lower it to the
7268 // sequence of ops that should be used.
7269 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7270                                              SelectionDAG &DAG) const {
7271   SDLoc dl(Op);
7272   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7273   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7274
7275   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7276     // We first build an i32 vector, load it into a QPX register,
7277     // then convert it to a floating-point vector and compare it
7278     // to a zero vector to get the boolean result.
7279     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7280     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7281     MachinePointerInfo PtrInfo =
7282         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7283     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7284     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7285
7286     assert(BVN->getNumOperands() == 4 &&
7287       "BUILD_VECTOR for v4i1 does not have 4 operands");
7288
7289     bool IsConst = true;
7290     for (unsigned i = 0; i < 4; ++i) {
7291       if (BVN->getOperand(i).isUndef()) continue;
7292       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7293         IsConst = false;
7294         break;
7295       }
7296     }
7297
7298     if (IsConst) {
7299       Constant *One =
7300         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7301       Constant *NegOne =
7302         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7303
7304       Constant *CV[4];
7305       for (unsigned i = 0; i < 4; ++i) {
7306         if (BVN->getOperand(i).isUndef())
7307           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7308         else if (isNullConstant(BVN->getOperand(i)))
7309           CV[i] = NegOne;
7310         else
7311           CV[i] = One;
7312       }
7313
7314       Constant *CP = ConstantVector::get(CV);
7315       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7316                                           16 /* alignment */);
7317
7318       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7319       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7320       return DAG.getMemIntrinsicNode(
7321           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7322           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7323     }
7324
7325     SmallVector<SDValue, 4> Stores;
7326     for (unsigned i = 0; i < 4; ++i) {
7327       if (BVN->getOperand(i).isUndef()) continue;
7328
7329       unsigned Offset = 4*i;
7330       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7331       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7332
7333       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7334       if (StoreSize > 4) {
7335         Stores.push_back(
7336             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7337                               PtrInfo.getWithOffset(Offset), MVT::i32));
7338       } else {
7339         SDValue StoreValue = BVN->getOperand(i);
7340         if (StoreSize < 4)
7341           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7342
7343         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7344                                       PtrInfo.getWithOffset(Offset)));
7345       }
7346     }
7347
7348     SDValue StoreChain;
7349     if (!Stores.empty())
7350       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7351     else
7352       StoreChain = DAG.getEntryNode();
7353
7354     // Now load from v4i32 into the QPX register; this will extend it to
7355     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7356     // is typed as v4f64 because the QPX register integer states are not
7357     // explicitly represented.
7358
7359     SDValue Ops[] = {StoreChain,
7360                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7361                      FIdx};
7362     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7363
7364     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7365       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7366     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7367       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7368       LoadedVect);
7369
7370     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7371
7372     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7373   }
7374
7375   // All other QPX vectors are handled by generic code.
7376   if (Subtarget.hasQPX())
7377     return SDValue();
7378
7379   // Check if this is a splat of a constant value.
7380   APInt APSplatBits, APSplatUndef;
7381   unsigned SplatBitSize;
7382   bool HasAnyUndefs;
7383   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7384                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7385       SplatBitSize > 32) {
7386     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7387     // lowered to VSX instructions under certain conditions.
7388     // Without VSX, there is no pattern more efficient than expanding the node.
7389     if (Subtarget.hasVSX() &&
7390         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7391       return Op;
7392     return SDValue();
7393   }
7394
7395   unsigned SplatBits = APSplatBits.getZExtValue();
7396   unsigned SplatUndef = APSplatUndef.getZExtValue();
7397   unsigned SplatSize = SplatBitSize / 8;
7398
7399   // First, handle single instruction cases.
7400
7401   // All zeros?
7402   if (SplatBits == 0) {
7403     // Canonicalize all zero vectors to be v4i32.
7404     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7405       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7406       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7407     }
7408     return Op;
7409   }
7410
7411   // We have XXSPLTIB for constant splats one byte wide
7412   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7413     // This is a splat of 1-byte elements with some elements potentially undef.
7414     // Rather than trying to match undef in the SDAG patterns, ensure that all
7415     // elements are the same constant.
7416     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7417       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7418                                                        dl, MVT::i32));
7419       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7420       if (Op.getValueType() != MVT::v16i8)
7421         return DAG.getBitcast(Op.getValueType(), NewBV);
7422       return NewBV;
7423     }
7424     return Op;
7425   }
7426
7427   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7428   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7429                     (32-SplatBitSize));
7430   if (SextVal >= -16 && SextVal <= 15)
7431     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7432
7433   // Two instruction sequences.
7434
7435   // If this value is in the range [-32,30] and is even, use:
7436   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7437   // If this value is in the range [17,31] and is odd, use:
7438   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7439   // If this value is in the range [-31,-17] and is odd, use:
7440   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7441   // Note the last two are three-instruction sequences.
7442   if (SextVal >= -32 && SextVal <= 31) {
7443     // To avoid having these optimizations undone by constant folding,
7444     // we convert to a pseudo that will be expanded later into one of
7445     // the above forms.
7446     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7447     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7448               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7449     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7450     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7451     if (VT == Op.getValueType())
7452       return RetVal;
7453     else
7454       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7455   }
7456
7457   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7458   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7459   // for fneg/fabs.
7460   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7461     // Make -1 and vspltisw -1:
7462     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7463
7464     // Make the VSLW intrinsic, computing 0x8000_0000.
7465     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7466                                    OnesV, DAG, dl);
7467
7468     // xor by OnesV to invert it.
7469     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7470     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7471   }
7472
7473   // Check to see if this is a wide variety of vsplti*, binop self cases.
7474   static const signed char SplatCsts[] = {
7475     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7476     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7477   };
7478
7479   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7480     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7481     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7482     int i = SplatCsts[idx];
7483
7484     // Figure out what shift amount will be used by altivec if shifted by i in
7485     // this splat size.
7486     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7487
7488     // vsplti + shl self.
7489     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7490       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7491       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7492         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7493         Intrinsic::ppc_altivec_vslw
7494       };
7495       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7496       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7497     }
7498
7499     // vsplti + srl self.
7500     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7501       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7502       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7503         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7504         Intrinsic::ppc_altivec_vsrw
7505       };
7506       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7507       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7508     }
7509
7510     // vsplti + sra self.
7511     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7512       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7513       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7514         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7515         Intrinsic::ppc_altivec_vsraw
7516       };
7517       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7518       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7519     }
7520
7521     // vsplti + rol self.
7522     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7523                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7524       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7525       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7526         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7527         Intrinsic::ppc_altivec_vrlw
7528       };
7529       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7530       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7531     }
7532
7533     // t = vsplti c, result = vsldoi t, t, 1
7534     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7535       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7536       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7537       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7538     }
7539     // t = vsplti c, result = vsldoi t, t, 2
7540     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7541       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7542       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7543       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7544     }
7545     // t = vsplti c, result = vsldoi t, t, 3
7546     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7547       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7548       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7549       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7550     }
7551   }
7552
7553   return SDValue();
7554 }
7555
7556 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7557 /// the specified operations to build the shuffle.
7558 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7559                                       SDValue RHS, SelectionDAG &DAG,
7560                                       const SDLoc &dl) {
7561   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7562   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7563   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7564
7565   enum {
7566     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7567     OP_VMRGHW,
7568     OP_VMRGLW,
7569     OP_VSPLTISW0,
7570     OP_VSPLTISW1,
7571     OP_VSPLTISW2,
7572     OP_VSPLTISW3,
7573     OP_VSLDOI4,
7574     OP_VSLDOI8,
7575     OP_VSLDOI12
7576   };
7577
7578   if (OpNum == OP_COPY) {
7579     if (LHSID == (1*9+2)*9+3) return LHS;
7580     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7581     return RHS;
7582   }
7583
7584   SDValue OpLHS, OpRHS;
7585   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7586   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7587
7588   int ShufIdxs[16];
7589   switch (OpNum) {
7590   default: llvm_unreachable("Unknown i32 permute!");
7591   case OP_VMRGHW:
7592     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7593     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7594     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7595     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7596     break;
7597   case OP_VMRGLW:
7598     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7599     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7600     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7601     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7602     break;
7603   case OP_VSPLTISW0:
7604     for (unsigned i = 0; i != 16; ++i)
7605       ShufIdxs[i] = (i&3)+0;
7606     break;
7607   case OP_VSPLTISW1:
7608     for (unsigned i = 0; i != 16; ++i)
7609       ShufIdxs[i] = (i&3)+4;
7610     break;
7611   case OP_VSPLTISW2:
7612     for (unsigned i = 0; i != 16; ++i)
7613       ShufIdxs[i] = (i&3)+8;
7614     break;
7615   case OP_VSPLTISW3:
7616     for (unsigned i = 0; i != 16; ++i)
7617       ShufIdxs[i] = (i&3)+12;
7618     break;
7619   case OP_VSLDOI4:
7620     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7621   case OP_VSLDOI8:
7622     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7623   case OP_VSLDOI12:
7624     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7625   }
7626   EVT VT = OpLHS.getValueType();
7627   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7628   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7629   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7630   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7631 }
7632
7633 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7634 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7635 /// return the code it can be lowered into.  Worst case, it can always be
7636 /// lowered into a vperm.
7637 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7638                                                SelectionDAG &DAG) const {
7639   SDLoc dl(Op);
7640   SDValue V1 = Op.getOperand(0);
7641   SDValue V2 = Op.getOperand(1);
7642   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7643   EVT VT = Op.getValueType();
7644   bool isLittleEndian = Subtarget.isLittleEndian();
7645
7646   unsigned ShiftElts, InsertAtByte;
7647   bool Swap;
7648   if (Subtarget.hasP9Vector() &&
7649       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7650                            isLittleEndian)) {
7651     if (Swap)
7652       std::swap(V1, V2);
7653     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7654     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7655     if (ShiftElts) {
7656       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7657                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7658       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7659                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7660       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7661     }
7662     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7663                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7664     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7665   }
7666
7667   if (Subtarget.hasVSX()) {
7668     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7669       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7670
7671       // If the source for the shuffle is a scalar_to_vector that came from a
7672       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7673       if (Subtarget.hasP9Vector() &&
7674           ((isLittleEndian && SplatIdx == 3) ||
7675            (!isLittleEndian && SplatIdx == 0))) {
7676         SDValue Src = V1.getOperand(0);
7677         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7678             Src.getOperand(0).getOpcode() == ISD::LOAD &&
7679             Src.getOperand(0).hasOneUse())
7680           return V1;
7681       }
7682       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7683       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7684                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7685       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7686     }
7687
7688     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7689     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7690       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7691       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7692       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7693     }
7694   }
7695
7696   if (Subtarget.hasQPX()) {
7697     if (VT.getVectorNumElements() != 4)
7698       return SDValue();
7699
7700     if (V2.isUndef()) V2 = V1;
7701
7702     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7703     if (AlignIdx != -1) {
7704       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7705                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7706     } else if (SVOp->isSplat()) {
7707       int SplatIdx = SVOp->getSplatIndex();
7708       if (SplatIdx >= 4) {
7709         std::swap(V1, V2);
7710         SplatIdx -= 4;
7711       }
7712
7713       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7714                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7715     }
7716
7717     // Lower this into a qvgpci/qvfperm pair.
7718
7719     // Compute the qvgpci literal
7720     unsigned idx = 0;
7721     for (unsigned i = 0; i < 4; ++i) {
7722       int m = SVOp->getMaskElt(i);
7723       unsigned mm = m >= 0 ? (unsigned) m : i;
7724       idx |= mm << (3-i)*3;
7725     }
7726
7727     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7728                              DAG.getConstant(idx, dl, MVT::i32));
7729     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7730   }
7731
7732   // Cases that are handled by instructions that take permute immediates
7733   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7734   // selected by the instruction selector.
7735   if (V2.isUndef()) {
7736     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7737         PPC::isSplatShuffleMask(SVOp, 2) ||
7738         PPC::isSplatShuffleMask(SVOp, 4) ||
7739         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7740         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7741         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7742         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7743         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7744         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7745         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7746         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7747         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7748         (Subtarget.hasP8Altivec() && (
7749          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7750          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7751          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7752       return Op;
7753     }
7754   }
7755
7756   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7757   // and produce a fixed permutation.  If any of these match, do not lower to
7758   // VPERM.
7759   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7760   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7761       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7762       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7763       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7764       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7765       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7766       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7767       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7768       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7769       (Subtarget.hasP8Altivec() && (
7770        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7771        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7772        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7773     return Op;
7774
7775   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7776   // perfect shuffle table to emit an optimal matching sequence.
7777   ArrayRef<int> PermMask = SVOp->getMask();
7778
7779   unsigned PFIndexes[4];
7780   bool isFourElementShuffle = true;
7781   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7782     unsigned EltNo = 8;   // Start out undef.
7783     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7784       if (PermMask[i*4+j] < 0)
7785         continue;   // Undef, ignore it.
7786
7787       unsigned ByteSource = PermMask[i*4+j];
7788       if ((ByteSource & 3) != j) {
7789         isFourElementShuffle = false;
7790         break;
7791       }
7792
7793       if (EltNo == 8) {
7794         EltNo = ByteSource/4;
7795       } else if (EltNo != ByteSource/4) {
7796         isFourElementShuffle = false;
7797         break;
7798       }
7799     }
7800     PFIndexes[i] = EltNo;
7801   }
7802
7803   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7804   // perfect shuffle vector to determine if it is cost effective to do this as
7805   // discrete instructions, or whether we should use a vperm.
7806   // For now, we skip this for little endian until such time as we have a
7807   // little-endian perfect shuffle table.
7808   if (isFourElementShuffle && !isLittleEndian) {
7809     // Compute the index in the perfect shuffle table.
7810     unsigned PFTableIndex =
7811       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7812
7813     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7814     unsigned Cost  = (PFEntry >> 30);
7815
7816     // Determining when to avoid vperm is tricky.  Many things affect the cost
7817     // of vperm, particularly how many times the perm mask needs to be computed.
7818     // For example, if the perm mask can be hoisted out of a loop or is already
7819     // used (perhaps because there are multiple permutes with the same shuffle
7820     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7821     // the loop requires an extra register.
7822     //
7823     // As a compromise, we only emit discrete instructions if the shuffle can be
7824     // generated in 3 or fewer operations.  When we have loop information
7825     // available, if this block is within a loop, we should avoid using vperm
7826     // for 3-operation perms and use a constant pool load instead.
7827     if (Cost < 3)
7828       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7829   }
7830
7831   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7832   // vector that will get spilled to the constant pool.
7833   if (V2.isUndef()) V2 = V1;
7834
7835   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7836   // that it is in input element units, not in bytes.  Convert now.
7837
7838   // For little endian, the order of the input vectors is reversed, and
7839   // the permutation mask is complemented with respect to 31.  This is
7840   // necessary to produce proper semantics with the big-endian-biased vperm
7841   // instruction.
7842   EVT EltVT = V1.getValueType().getVectorElementType();
7843   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7844
7845   SmallVector<SDValue, 16> ResultMask;
7846   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7847     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7848
7849     for (unsigned j = 0; j != BytesPerElement; ++j)
7850       if (isLittleEndian)
7851         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7852                                              dl, MVT::i32));
7853       else
7854         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7855                                              MVT::i32));
7856   }
7857
7858   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7859   if (isLittleEndian)
7860     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7861                        V2, V1, VPermMask);
7862   else
7863     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7864                        V1, V2, VPermMask);
7865 }
7866
7867 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7868 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7869 /// information about the intrinsic.
7870 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7871                                  bool &isDot, const PPCSubtarget &Subtarget) {
7872   unsigned IntrinsicID =
7873       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7874   CompareOpc = -1;
7875   isDot = false;
7876   switch (IntrinsicID) {
7877   default:
7878     return false;
7879   // Comparison predicates.
7880   case Intrinsic::ppc_altivec_vcmpbfp_p:
7881     CompareOpc = 966;
7882     isDot = true;
7883     break;
7884   case Intrinsic::ppc_altivec_vcmpeqfp_p:
7885     CompareOpc = 198;
7886     isDot = true;
7887     break;
7888   case Intrinsic::ppc_altivec_vcmpequb_p:
7889     CompareOpc = 6;
7890     isDot = true;
7891     break;
7892   case Intrinsic::ppc_altivec_vcmpequh_p:
7893     CompareOpc = 70;
7894     isDot = true;
7895     break;
7896   case Intrinsic::ppc_altivec_vcmpequw_p:
7897     CompareOpc = 134;
7898     isDot = true;
7899     break;
7900   case Intrinsic::ppc_altivec_vcmpequd_p:
7901     if (Subtarget.hasP8Altivec()) {
7902       CompareOpc = 199;
7903       isDot = true;
7904     } else
7905       return false;
7906     break;
7907   case Intrinsic::ppc_altivec_vcmpneb_p:
7908   case Intrinsic::ppc_altivec_vcmpneh_p:
7909   case Intrinsic::ppc_altivec_vcmpnew_p:
7910   case Intrinsic::ppc_altivec_vcmpnezb_p:
7911   case Intrinsic::ppc_altivec_vcmpnezh_p:
7912   case Intrinsic::ppc_altivec_vcmpnezw_p:
7913     if (Subtarget.hasP9Altivec()) {
7914       switch (IntrinsicID) {
7915       default:
7916         llvm_unreachable("Unknown comparison intrinsic.");
7917       case Intrinsic::ppc_altivec_vcmpneb_p:
7918         CompareOpc = 7;
7919         break;
7920       case Intrinsic::ppc_altivec_vcmpneh_p:
7921         CompareOpc = 71;
7922         break;
7923       case Intrinsic::ppc_altivec_vcmpnew_p:
7924         CompareOpc = 135;
7925         break;
7926       case Intrinsic::ppc_altivec_vcmpnezb_p:
7927         CompareOpc = 263;
7928         break;
7929       case Intrinsic::ppc_altivec_vcmpnezh_p:
7930         CompareOpc = 327;
7931         break;
7932       case Intrinsic::ppc_altivec_vcmpnezw_p:
7933         CompareOpc = 391;
7934         break;
7935       }
7936       isDot = true;
7937     } else
7938       return false;
7939     break;
7940   case Intrinsic::ppc_altivec_vcmpgefp_p:
7941     CompareOpc = 454;
7942     isDot = true;
7943     break;
7944   case Intrinsic::ppc_altivec_vcmpgtfp_p:
7945     CompareOpc = 710;
7946     isDot = true;
7947     break;
7948   case Intrinsic::ppc_altivec_vcmpgtsb_p:
7949     CompareOpc = 774;
7950     isDot = true;
7951     break;
7952   case Intrinsic::ppc_altivec_vcmpgtsh_p:
7953     CompareOpc = 838;
7954     isDot = true;
7955     break;
7956   case Intrinsic::ppc_altivec_vcmpgtsw_p:
7957     CompareOpc = 902;
7958     isDot = true;
7959     break;
7960   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7961     if (Subtarget.hasP8Altivec()) {
7962       CompareOpc = 967;
7963       isDot = true;
7964     } else
7965       return false;
7966     break;
7967   case Intrinsic::ppc_altivec_vcmpgtub_p:
7968     CompareOpc = 518;
7969     isDot = true;
7970     break;
7971   case Intrinsic::ppc_altivec_vcmpgtuh_p:
7972     CompareOpc = 582;
7973     isDot = true;
7974     break;
7975   case Intrinsic::ppc_altivec_vcmpgtuw_p:
7976     CompareOpc = 646;
7977     isDot = true;
7978     break;
7979   case Intrinsic::ppc_altivec_vcmpgtud_p:
7980     if (Subtarget.hasP8Altivec()) {
7981       CompareOpc = 711;
7982       isDot = true;
7983     } else
7984       return false;
7985     break;
7986
7987   // VSX predicate comparisons use the same infrastructure
7988   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7989   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7990   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7991   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7992   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7993   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7994     if (Subtarget.hasVSX()) {
7995       switch (IntrinsicID) {
7996       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7997         CompareOpc = 99;
7998         break;
7999       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8000         CompareOpc = 115;
8001         break;
8002       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8003         CompareOpc = 107;
8004         break;
8005       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8006         CompareOpc = 67;
8007         break;
8008       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8009         CompareOpc = 83;
8010         break;
8011       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8012         CompareOpc = 75;
8013         break;
8014       }
8015       isDot = true;
8016     } else
8017       return false;
8018     break;
8019
8020   // Normal Comparisons.
8021   case Intrinsic::ppc_altivec_vcmpbfp:
8022     CompareOpc = 966;
8023     break;
8024   case Intrinsic::ppc_altivec_vcmpeqfp:
8025     CompareOpc = 198;
8026     break;
8027   case Intrinsic::ppc_altivec_vcmpequb:
8028     CompareOpc = 6;
8029     break;
8030   case Intrinsic::ppc_altivec_vcmpequh:
8031     CompareOpc = 70;
8032     break;
8033   case Intrinsic::ppc_altivec_vcmpequw:
8034     CompareOpc = 134;
8035     break;
8036   case Intrinsic::ppc_altivec_vcmpequd:
8037     if (Subtarget.hasP8Altivec())
8038       CompareOpc = 199;
8039     else
8040       return false;
8041     break;
8042   case Intrinsic::ppc_altivec_vcmpneb:
8043   case Intrinsic::ppc_altivec_vcmpneh:
8044   case Intrinsic::ppc_altivec_vcmpnew:
8045   case Intrinsic::ppc_altivec_vcmpnezb:
8046   case Intrinsic::ppc_altivec_vcmpnezh:
8047   case Intrinsic::ppc_altivec_vcmpnezw:
8048     if (Subtarget.hasP9Altivec())
8049       switch (IntrinsicID) {
8050       default:
8051         llvm_unreachable("Unknown comparison intrinsic.");
8052       case Intrinsic::ppc_altivec_vcmpneb:
8053         CompareOpc = 7;
8054         break;
8055       case Intrinsic::ppc_altivec_vcmpneh:
8056         CompareOpc = 71;
8057         break;
8058       case Intrinsic::ppc_altivec_vcmpnew:
8059         CompareOpc = 135;
8060         break;
8061       case Intrinsic::ppc_altivec_vcmpnezb:
8062         CompareOpc = 263;
8063         break;
8064       case Intrinsic::ppc_altivec_vcmpnezh:
8065         CompareOpc = 327;
8066         break;
8067       case Intrinsic::ppc_altivec_vcmpnezw:
8068         CompareOpc = 391;
8069         break;
8070       }
8071     else
8072       return false;
8073     break;
8074   case Intrinsic::ppc_altivec_vcmpgefp:
8075     CompareOpc = 454;
8076     break;
8077   case Intrinsic::ppc_altivec_vcmpgtfp:
8078     CompareOpc = 710;
8079     break;
8080   case Intrinsic::ppc_altivec_vcmpgtsb:
8081     CompareOpc = 774;
8082     break;
8083   case Intrinsic::ppc_altivec_vcmpgtsh:
8084     CompareOpc = 838;
8085     break;
8086   case Intrinsic::ppc_altivec_vcmpgtsw:
8087     CompareOpc = 902;
8088     break;
8089   case Intrinsic::ppc_altivec_vcmpgtsd:
8090     if (Subtarget.hasP8Altivec())
8091       CompareOpc = 967;
8092     else
8093       return false;
8094     break;
8095   case Intrinsic::ppc_altivec_vcmpgtub:
8096     CompareOpc = 518;
8097     break;
8098   case Intrinsic::ppc_altivec_vcmpgtuh:
8099     CompareOpc = 582;
8100     break;
8101   case Intrinsic::ppc_altivec_vcmpgtuw:
8102     CompareOpc = 646;
8103     break;
8104   case Intrinsic::ppc_altivec_vcmpgtud:
8105     if (Subtarget.hasP8Altivec())
8106       CompareOpc = 711;
8107     else
8108       return false;
8109     break;
8110   }
8111   return true;
8112 }
8113
8114 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8115 /// lower, do it, otherwise return null.
8116 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8117                                                    SelectionDAG &DAG) const {
8118   unsigned IntrinsicID =
8119     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8120
8121   if (IntrinsicID == Intrinsic::thread_pointer) {
8122     // Reads the thread pointer register, used for __builtin_thread_pointer.
8123     bool is64bit = Subtarget.isPPC64();
8124     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8125                            is64bit ? MVT::i64 : MVT::i32);
8126   }
8127
8128   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8129   // opcode number of the comparison.
8130   SDLoc dl(Op);
8131   int CompareOpc;
8132   bool isDot;
8133   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8134     return SDValue();    // Don't custom lower most intrinsics.
8135
8136   // If this is a non-dot comparison, make the VCMP node and we are done.
8137   if (!isDot) {
8138     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8139                               Op.getOperand(1), Op.getOperand(2),
8140                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8141     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8142   }
8143
8144   // Create the PPCISD altivec 'dot' comparison node.
8145   SDValue Ops[] = {
8146     Op.getOperand(2),  // LHS
8147     Op.getOperand(3),  // RHS
8148     DAG.getConstant(CompareOpc, dl, MVT::i32)
8149   };
8150   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8151   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8152
8153   // Now that we have the comparison, emit a copy from the CR to a GPR.
8154   // This is flagged to the above dot comparison.
8155   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8156                                 DAG.getRegister(PPC::CR6, MVT::i32),
8157                                 CompNode.getValue(1));
8158
8159   // Unpack the result based on how the target uses it.
8160   unsigned BitNo;   // Bit # of CR6.
8161   bool InvertBit;   // Invert result?
8162   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8163   default:  // Can't happen, don't crash on invalid number though.
8164   case 0:   // Return the value of the EQ bit of CR6.
8165     BitNo = 0; InvertBit = false;
8166     break;
8167   case 1:   // Return the inverted value of the EQ bit of CR6.
8168     BitNo = 0; InvertBit = true;
8169     break;
8170   case 2:   // Return the value of the LT bit of CR6.
8171     BitNo = 2; InvertBit = false;
8172     break;
8173   case 3:   // Return the inverted value of the LT bit of CR6.
8174     BitNo = 2; InvertBit = true;
8175     break;
8176   }
8177
8178   // Shift the bit into the low position.
8179   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8180                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8181   // Isolate the bit.
8182   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8183                       DAG.getConstant(1, dl, MVT::i32));
8184
8185   // If we are supposed to, toggle the bit.
8186   if (InvertBit)
8187     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8188                         DAG.getConstant(1, dl, MVT::i32));
8189   return Flags;
8190 }
8191
8192 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8193                                                SelectionDAG &DAG) const {
8194   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8195   // the beginning of the argument list.
8196   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8197   SDLoc DL(Op);
8198   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8199   case Intrinsic::ppc_cfence: {
8200     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8201     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8202                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8203                                                   Op.getOperand(ArgStart + 1))),
8204                    0);
8205   }
8206   default:
8207     break;
8208   }
8209   return SDValue();
8210 }
8211
8212 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8213                                                   SelectionDAG &DAG) const {
8214   SDLoc dl(Op);
8215   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8216   // instructions), but for smaller types, we need to first extend up to v2i32
8217   // before doing going farther.
8218   if (Op.getValueType() == MVT::v2i64) {
8219     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8220     if (ExtVT != MVT::v2i32) {
8221       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8222       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8223                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8224                                         ExtVT.getVectorElementType(), 4)));
8225       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8226       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8227                        DAG.getValueType(MVT::v2i32));
8228     }
8229
8230     return Op;
8231   }
8232
8233   return SDValue();
8234 }
8235
8236 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8237                                                  SelectionDAG &DAG) const {
8238   SDLoc dl(Op);
8239   // Create a stack slot that is 16-byte aligned.
8240   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8241   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8242   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8243   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8244
8245   // Store the input value into Value#0 of the stack slot.
8246   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8247                                MachinePointerInfo());
8248   // Load it out.
8249   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8250 }
8251
8252 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8253                                                   SelectionDAG &DAG) const {
8254   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8255          "Should only be called for ISD::INSERT_VECTOR_ELT");
8256   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8257   // We have legal lowering for constant indices but not for variable ones.
8258   if (C)
8259     return Op;
8260   return SDValue();
8261 }
8262
8263 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8264                                                    SelectionDAG &DAG) const {
8265   SDLoc dl(Op);
8266   SDNode *N = Op.getNode();
8267
8268   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8269          "Unknown extract_vector_elt type");
8270
8271   SDValue Value = N->getOperand(0);
8272
8273   // The first part of this is like the store lowering except that we don't
8274   // need to track the chain.
8275
8276   // The values are now known to be -1 (false) or 1 (true). To convert this
8277   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8278   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8279   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8280
8281   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8282   // understand how to form the extending load.
8283   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8284
8285   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8286
8287   // Now convert to an integer and store.
8288   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8289     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8290     Value);
8291
8292   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8293   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8294   MachinePointerInfo PtrInfo =
8295       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8296   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8297   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8298
8299   SDValue StoreChain = DAG.getEntryNode();
8300   SDValue Ops[] = {StoreChain,
8301                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8302                    Value, FIdx};
8303   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8304
8305   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8306     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8307
8308   // Extract the value requested.
8309   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8310   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8311   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8312
8313   SDValue IntVal =
8314       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8315
8316   if (!Subtarget.useCRBits())
8317     return IntVal;
8318
8319   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8320 }
8321
8322 /// Lowering for QPX v4i1 loads
8323 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8324                                            SelectionDAG &DAG) const {
8325   SDLoc dl(Op);
8326   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8327   SDValue LoadChain = LN->getChain();
8328   SDValue BasePtr = LN->getBasePtr();
8329
8330   if (Op.getValueType() == MVT::v4f64 ||
8331       Op.getValueType() == MVT::v4f32) {
8332     EVT MemVT = LN->getMemoryVT();
8333     unsigned Alignment = LN->getAlignment();
8334
8335     // If this load is properly aligned, then it is legal.
8336     if (Alignment >= MemVT.getStoreSize())
8337       return Op;
8338
8339     EVT ScalarVT = Op.getValueType().getScalarType(),
8340         ScalarMemVT = MemVT.getScalarType();
8341     unsigned Stride = ScalarMemVT.getStoreSize();
8342
8343     SDValue Vals[4], LoadChains[4];
8344     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8345       SDValue Load;
8346       if (ScalarVT != ScalarMemVT)
8347         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8348                               BasePtr,
8349                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8350                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8351                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8352       else
8353         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8354                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8355                            MinAlign(Alignment, Idx * Stride),
8356                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8357
8358       if (Idx == 0 && LN->isIndexed()) {
8359         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8360                "Unknown addressing mode on vector load");
8361         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8362                                   LN->getAddressingMode());
8363       }
8364
8365       Vals[Idx] = Load;
8366       LoadChains[Idx] = Load.getValue(1);
8367
8368       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8369                             DAG.getConstant(Stride, dl,
8370                                             BasePtr.getValueType()));
8371     }
8372
8373     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8374     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8375
8376     if (LN->isIndexed()) {
8377       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8378       return DAG.getMergeValues(RetOps, dl);
8379     }
8380
8381     SDValue RetOps[] = { Value, TF };
8382     return DAG.getMergeValues(RetOps, dl);
8383   }
8384
8385   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8386   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8387
8388   // To lower v4i1 from a byte array, we load the byte elements of the
8389   // vector and then reuse the BUILD_VECTOR logic.
8390
8391   SDValue VectElmts[4], VectElmtChains[4];
8392   for (unsigned i = 0; i < 4; ++i) {
8393     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8394     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8395
8396     VectElmts[i] = DAG.getExtLoad(
8397         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8398         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8399         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8400     VectElmtChains[i] = VectElmts[i].getValue(1);
8401   }
8402
8403   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8404   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8405
8406   SDValue RVals[] = { Value, LoadChain };
8407   return DAG.getMergeValues(RVals, dl);
8408 }
8409
8410 /// Lowering for QPX v4i1 stores
8411 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8412                                             SelectionDAG &DAG) const {
8413   SDLoc dl(Op);
8414   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8415   SDValue StoreChain = SN->getChain();
8416   SDValue BasePtr = SN->getBasePtr();
8417   SDValue Value = SN->getValue();
8418
8419   if (Value.getValueType() == MVT::v4f64 ||
8420       Value.getValueType() == MVT::v4f32) {
8421     EVT MemVT = SN->getMemoryVT();
8422     unsigned Alignment = SN->getAlignment();
8423
8424     // If this store is properly aligned, then it is legal.
8425     if (Alignment >= MemVT.getStoreSize())
8426       return Op;
8427
8428     EVT ScalarVT = Value.getValueType().getScalarType(),
8429         ScalarMemVT = MemVT.getScalarType();
8430     unsigned Stride = ScalarMemVT.getStoreSize();
8431
8432     SDValue Stores[4];
8433     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8434       SDValue Ex = DAG.getNode(
8435           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8436           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8437       SDValue Store;
8438       if (ScalarVT != ScalarMemVT)
8439         Store =
8440             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8441                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8442                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8443                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8444       else
8445         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8446                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8447                              MinAlign(Alignment, Idx * Stride),
8448                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8449
8450       if (Idx == 0 && SN->isIndexed()) {
8451         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8452                "Unknown addressing mode on vector store");
8453         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8454                                     SN->getAddressingMode());
8455       }
8456
8457       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8458                             DAG.getConstant(Stride, dl,
8459                                             BasePtr.getValueType()));
8460       Stores[Idx] = Store;
8461     }
8462
8463     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8464
8465     if (SN->isIndexed()) {
8466       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8467       return DAG.getMergeValues(RetOps, dl);
8468     }
8469
8470     return TF;
8471   }
8472
8473   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8474   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8475
8476   // The values are now known to be -1 (false) or 1 (true). To convert this
8477   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8478   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8479   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8480
8481   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8482   // understand how to form the extending load.
8483   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8484
8485   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8486
8487   // Now convert to an integer and store.
8488   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8489     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8490     Value);
8491
8492   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8493   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8494   MachinePointerInfo PtrInfo =
8495       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8496   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8497   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8498
8499   SDValue Ops[] = {StoreChain,
8500                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8501                    Value, FIdx};
8502   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8503
8504   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8505     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8506
8507   // Move data into the byte array.
8508   SDValue Loads[4], LoadChains[4];
8509   for (unsigned i = 0; i < 4; ++i) {
8510     unsigned Offset = 4*i;
8511     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8512     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8513
8514     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8515                            PtrInfo.getWithOffset(Offset));
8516     LoadChains[i] = Loads[i].getValue(1);
8517   }
8518
8519   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8520
8521   SDValue Stores[4];
8522   for (unsigned i = 0; i < 4; ++i) {
8523     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8524     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8525
8526     Stores[i] = DAG.getTruncStore(
8527         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8528         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8529         SN->getAAInfo());
8530   }
8531
8532   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8533
8534   return StoreChain;
8535 }
8536
8537 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8538   SDLoc dl(Op);
8539   if (Op.getValueType() == MVT::v4i32) {
8540     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8541
8542     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8543     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8544
8545     SDValue RHSSwap =   // = vrlw RHS, 16
8546       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8547
8548     // Shrinkify inputs to v8i16.
8549     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8550     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8551     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8552
8553     // Low parts multiplied together, generating 32-bit results (we ignore the
8554     // top parts).
8555     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8556                                         LHS, RHS, DAG, dl, MVT::v4i32);
8557
8558     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8559                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8560     // Shift the high parts up 16 bits.
8561     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8562                               Neg16, DAG, dl);
8563     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8564   } else if (Op.getValueType() == MVT::v8i16) {
8565     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8566
8567     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8568
8569     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8570                             LHS, RHS, Zero, DAG, dl);
8571   } else if (Op.getValueType() == MVT::v16i8) {
8572     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8573     bool isLittleEndian = Subtarget.isLittleEndian();
8574
8575     // Multiply the even 8-bit parts, producing 16-bit sums.
8576     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8577                                            LHS, RHS, DAG, dl, MVT::v8i16);
8578     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8579
8580     // Multiply the odd 8-bit parts, producing 16-bit sums.
8581     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8582                                           LHS, RHS, DAG, dl, MVT::v8i16);
8583     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8584
8585     // Merge the results together.  Because vmuleub and vmuloub are
8586     // instructions with a big-endian bias, we must reverse the
8587     // element numbering and reverse the meaning of "odd" and "even"
8588     // when generating little endian code.
8589     int Ops[16];
8590     for (unsigned i = 0; i != 8; ++i) {
8591       if (isLittleEndian) {
8592         Ops[i*2  ] = 2*i;
8593         Ops[i*2+1] = 2*i+16;
8594       } else {
8595         Ops[i*2  ] = 2*i+1;
8596         Ops[i*2+1] = 2*i+1+16;
8597       }
8598     }
8599     if (isLittleEndian)
8600       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8601     else
8602       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8603   } else {
8604     llvm_unreachable("Unknown mul to lower!");
8605   }
8606 }
8607
8608 /// LowerOperation - Provide custom lowering hooks for some operations.
8609 ///
8610 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8611   switch (Op.getOpcode()) {
8612   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8613   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8614   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8615   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8616   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8617   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8618   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8619   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8620   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8621   case ISD::VASTART:
8622     return LowerVASTART(Op, DAG);
8623
8624   case ISD::VAARG:
8625     return LowerVAARG(Op, DAG);
8626
8627   case ISD::VACOPY:
8628     return LowerVACOPY(Op, DAG);
8629
8630   case ISD::STACKRESTORE:
8631     return LowerSTACKRESTORE(Op, DAG);
8632
8633   case ISD::DYNAMIC_STACKALLOC:
8634     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8635
8636   case ISD::GET_DYNAMIC_AREA_OFFSET:
8637     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8638
8639   case ISD::EH_DWARF_CFA:
8640     return LowerEH_DWARF_CFA(Op, DAG);
8641
8642   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8643   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8644
8645   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8646   case ISD::STORE:              return LowerSTORE(Op, DAG);
8647   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8648   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8649   case ISD::FP_TO_UINT:
8650   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8651                                                       SDLoc(Op));
8652   case ISD::UINT_TO_FP:
8653   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8654   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8655
8656   // Lower 64-bit shifts.
8657   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8658   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8659   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8660
8661   // Vector-related lowering.
8662   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8663   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8664   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8665   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8666   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8667   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8668   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8669   case ISD::MUL:                return LowerMUL(Op, DAG);
8670
8671   // For counter-based loop handling.
8672   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8673
8674   // Frame & Return address.
8675   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8676   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8677
8678   case ISD::INTRINSIC_VOID:
8679     return LowerINTRINSIC_VOID(Op, DAG);
8680   }
8681 }
8682
8683 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8684                                            SmallVectorImpl<SDValue>&Results,
8685                                            SelectionDAG &DAG) const {
8686   SDLoc dl(N);
8687   switch (N->getOpcode()) {
8688   default:
8689     llvm_unreachable("Do not know how to custom type legalize this operation!");
8690   case ISD::READCYCLECOUNTER: {
8691     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8692     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8693
8694     Results.push_back(RTB);
8695     Results.push_back(RTB.getValue(1));
8696     Results.push_back(RTB.getValue(2));
8697     break;
8698   }
8699   case ISD::INTRINSIC_W_CHAIN: {
8700     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8701         Intrinsic::ppc_is_decremented_ctr_nonzero)
8702       break;
8703
8704     assert(N->getValueType(0) == MVT::i1 &&
8705            "Unexpected result type for CTR decrement intrinsic");
8706     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8707                                  N->getValueType(0));
8708     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8709     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8710                                  N->getOperand(1));
8711
8712     Results.push_back(NewInt);
8713     Results.push_back(NewInt.getValue(1));
8714     break;
8715   }
8716   case ISD::VAARG: {
8717     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8718       return;
8719
8720     EVT VT = N->getValueType(0);
8721
8722     if (VT == MVT::i64) {
8723       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8724
8725       Results.push_back(NewNode);
8726       Results.push_back(NewNode.getValue(1));
8727     }
8728     return;
8729   }
8730   case ISD::FP_ROUND_INREG: {
8731     assert(N->getValueType(0) == MVT::ppcf128);
8732     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8733     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8734                              MVT::f64, N->getOperand(0),
8735                              DAG.getIntPtrConstant(0, dl));
8736     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8737                              MVT::f64, N->getOperand(0),
8738                              DAG.getIntPtrConstant(1, dl));
8739
8740     // Add the two halves of the long double in round-to-zero mode.
8741     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8742
8743     // We know the low half is about to be thrown away, so just use something
8744     // convenient.
8745     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8746                                 FPreg, FPreg));
8747     return;
8748   }
8749   case ISD::FP_TO_SINT:
8750   case ISD::FP_TO_UINT:
8751     // LowerFP_TO_INT() can only handle f32 and f64.
8752     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8753       return;
8754     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8755     return;
8756   }
8757 }
8758
8759 //===----------------------------------------------------------------------===//
8760 //  Other Lowering Code
8761 //===----------------------------------------------------------------------===//
8762
8763 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8764   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8765   Function *Func = Intrinsic::getDeclaration(M, Id);
8766   return Builder.CreateCall(Func, {});
8767 }
8768
8769 // The mappings for emitLeading/TrailingFence is taken from
8770 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8771 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8772                                                  Instruction *Inst,
8773                                                  AtomicOrdering Ord) const {
8774   if (Ord == AtomicOrdering::SequentiallyConsistent)
8775     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8776   if (isReleaseOrStronger(Ord))
8777     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8778   return nullptr;
8779 }
8780
8781 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8782                                                   Instruction *Inst,
8783                                                   AtomicOrdering Ord) const {
8784   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
8785     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8786     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8787     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8788     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
8789       return Builder.CreateCall(
8790           Intrinsic::getDeclaration(
8791               Builder.GetInsertBlock()->getParent()->getParent(),
8792               Intrinsic::ppc_cfence, {Inst->getType()}),
8793           {Inst});
8794     // FIXME: Can use isync for rmw operation.
8795     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8796   }
8797   return nullptr;
8798 }
8799
8800 MachineBasicBlock *
8801 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8802                                     unsigned AtomicSize,
8803                                     unsigned BinOpcode,
8804                                     unsigned CmpOpcode,
8805                                     unsigned CmpPred) const {
8806   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8807   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8808
8809   auto LoadMnemonic = PPC::LDARX;
8810   auto StoreMnemonic = PPC::STDCX;
8811   switch (AtomicSize) {
8812   default:
8813     llvm_unreachable("Unexpected size of atomic entity");
8814   case 1:
8815     LoadMnemonic = PPC::LBARX;
8816     StoreMnemonic = PPC::STBCX;
8817     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8818     break;
8819   case 2:
8820     LoadMnemonic = PPC::LHARX;
8821     StoreMnemonic = PPC::STHCX;
8822     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8823     break;
8824   case 4:
8825     LoadMnemonic = PPC::LWARX;
8826     StoreMnemonic = PPC::STWCX;
8827     break;
8828   case 8:
8829     LoadMnemonic = PPC::LDARX;
8830     StoreMnemonic = PPC::STDCX;
8831     break;
8832   }
8833
8834   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8835   MachineFunction *F = BB->getParent();
8836   MachineFunction::iterator It = ++BB->getIterator();
8837
8838   unsigned dest = MI.getOperand(0).getReg();
8839   unsigned ptrA = MI.getOperand(1).getReg();
8840   unsigned ptrB = MI.getOperand(2).getReg();
8841   unsigned incr = MI.getOperand(3).getReg();
8842   DebugLoc dl = MI.getDebugLoc();
8843
8844   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8845   MachineBasicBlock *loop2MBB =
8846     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8847   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8848   F->insert(It, loopMBB);
8849   if (CmpOpcode)
8850     F->insert(It, loop2MBB);
8851   F->insert(It, exitMBB);
8852   exitMBB->splice(exitMBB->begin(), BB,
8853                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8854   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8855
8856   MachineRegisterInfo &RegInfo = F->getRegInfo();
8857   unsigned TmpReg = (!BinOpcode) ? incr :
8858     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8859                                            : &PPC::GPRCRegClass);
8860
8861   //  thisMBB:
8862   //   ...
8863   //   fallthrough --> loopMBB
8864   BB->addSuccessor(loopMBB);
8865
8866   //  loopMBB:
8867   //   l[wd]arx dest, ptr
8868   //   add r0, dest, incr
8869   //   st[wd]cx. r0, ptr
8870   //   bne- loopMBB
8871   //   fallthrough --> exitMBB
8872
8873   // For max/min...
8874   //  loopMBB:
8875   //   l[wd]arx dest, ptr
8876   //   cmpl?[wd] incr, dest
8877   //   bgt exitMBB
8878   //  loop2MBB:
8879   //   st[wd]cx. dest, ptr
8880   //   bne- loopMBB
8881   //   fallthrough --> exitMBB
8882
8883   BB = loopMBB;
8884   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8885     .addReg(ptrA).addReg(ptrB);
8886   if (BinOpcode)
8887     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8888   if (CmpOpcode) {
8889     // Signed comparisons of byte or halfword values must be sign-extended.
8890     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8891       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8892       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8893               ExtReg).addReg(dest);
8894       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8895         .addReg(incr).addReg(ExtReg);
8896     } else
8897       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8898         .addReg(incr).addReg(dest);
8899
8900     BuildMI(BB, dl, TII->get(PPC::BCC))
8901       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8902     BB->addSuccessor(loop2MBB);
8903     BB->addSuccessor(exitMBB);
8904     BB = loop2MBB;
8905   }
8906   BuildMI(BB, dl, TII->get(StoreMnemonic))
8907     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8908   BuildMI(BB, dl, TII->get(PPC::BCC))
8909     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8910   BB->addSuccessor(loopMBB);
8911   BB->addSuccessor(exitMBB);
8912
8913   //  exitMBB:
8914   //   ...
8915   BB = exitMBB;
8916   return BB;
8917 }
8918
8919 MachineBasicBlock *
8920 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8921                                             MachineBasicBlock *BB,
8922                                             bool is8bit, // operation
8923                                             unsigned BinOpcode,
8924                                             unsigned CmpOpcode,
8925                                             unsigned CmpPred) const {
8926   // If we support part-word atomic mnemonics, just use them
8927   if (Subtarget.hasPartwordAtomics())
8928     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8929                             CmpOpcode, CmpPred);
8930
8931   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8932   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8933   // In 64 bit mode we have to use 64 bits for addresses, even though the
8934   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8935   // registers without caring whether they're 32 or 64, but here we're
8936   // doing actual arithmetic on the addresses.
8937   bool is64bit = Subtarget.isPPC64();
8938   bool isLittleEndian = Subtarget.isLittleEndian();
8939   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8940
8941   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8942   MachineFunction *F = BB->getParent();
8943   MachineFunction::iterator It = ++BB->getIterator();
8944
8945   unsigned dest = MI.getOperand(0).getReg();
8946   unsigned ptrA = MI.getOperand(1).getReg();
8947   unsigned ptrB = MI.getOperand(2).getReg();
8948   unsigned incr = MI.getOperand(3).getReg();
8949   DebugLoc dl = MI.getDebugLoc();
8950
8951   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8952   MachineBasicBlock *loop2MBB =
8953     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8954   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8955   F->insert(It, loopMBB);
8956   if (CmpOpcode)
8957     F->insert(It, loop2MBB);
8958   F->insert(It, exitMBB);
8959   exitMBB->splice(exitMBB->begin(), BB,
8960                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8961   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8962
8963   MachineRegisterInfo &RegInfo = F->getRegInfo();
8964   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8965                                           : &PPC::GPRCRegClass;
8966   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8967   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8968   unsigned ShiftReg =
8969     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8970   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8971   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8972   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8973   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8974   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8975   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8976   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8977   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8978   unsigned Ptr1Reg;
8979   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8980
8981   //  thisMBB:
8982   //   ...
8983   //   fallthrough --> loopMBB
8984   BB->addSuccessor(loopMBB);
8985
8986   // The 4-byte load must be aligned, while a char or short may be
8987   // anywhere in the word.  Hence all this nasty bookkeeping code.
8988   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8989   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8990   //   xori shift, shift1, 24 [16]
8991   //   rlwinm ptr, ptr1, 0, 0, 29
8992   //   slw incr2, incr, shift
8993   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8994   //   slw mask, mask2, shift
8995   //  loopMBB:
8996   //   lwarx tmpDest, ptr
8997   //   add tmp, tmpDest, incr2
8998   //   andc tmp2, tmpDest, mask
8999   //   and tmp3, tmp, mask
9000   //   or tmp4, tmp3, tmp2
9001   //   stwcx. tmp4, ptr
9002   //   bne- loopMBB
9003   //   fallthrough --> exitMBB
9004   //   srw dest, tmpDest, shift
9005   if (ptrA != ZeroReg) {
9006     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9007     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9008       .addReg(ptrA).addReg(ptrB);
9009   } else {
9010     Ptr1Reg = ptrB;
9011   }
9012   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9013       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9014   if (!isLittleEndian)
9015     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9016         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9017   if (is64bit)
9018     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9019       .addReg(Ptr1Reg).addImm(0).addImm(61);
9020   else
9021     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9022       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9023   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9024       .addReg(incr).addReg(ShiftReg);
9025   if (is8bit)
9026     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9027   else {
9028     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9029     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9030   }
9031   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9032       .addReg(Mask2Reg).addReg(ShiftReg);
9033
9034   BB = loopMBB;
9035   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9036     .addReg(ZeroReg).addReg(PtrReg);
9037   if (BinOpcode)
9038     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9039       .addReg(Incr2Reg).addReg(TmpDestReg);
9040   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9041     .addReg(TmpDestReg).addReg(MaskReg);
9042   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9043     .addReg(TmpReg).addReg(MaskReg);
9044   if (CmpOpcode) {
9045     // For unsigned comparisons, we can directly compare the shifted values.
9046     // For signed comparisons we shift and sign extend.
9047     unsigned SReg = RegInfo.createVirtualRegister(RC);
9048     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9049       .addReg(TmpDestReg).addReg(MaskReg);
9050     unsigned ValueReg = SReg;
9051     unsigned CmpReg = Incr2Reg;
9052     if (CmpOpcode == PPC::CMPW) {
9053       ValueReg = RegInfo.createVirtualRegister(RC);
9054       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9055         .addReg(SReg).addReg(ShiftReg);
9056       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9057       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9058         .addReg(ValueReg);
9059       ValueReg = ValueSReg;
9060       CmpReg = incr;
9061     }
9062     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9063       .addReg(CmpReg).addReg(ValueReg);
9064     BuildMI(BB, dl, TII->get(PPC::BCC))
9065       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9066     BB->addSuccessor(loop2MBB);
9067     BB->addSuccessor(exitMBB);
9068     BB = loop2MBB;
9069   }
9070   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9071     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9072   BuildMI(BB, dl, TII->get(PPC::STWCX))
9073     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9074   BuildMI(BB, dl, TII->get(PPC::BCC))
9075     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9076   BB->addSuccessor(loopMBB);
9077   BB->addSuccessor(exitMBB);
9078
9079   //  exitMBB:
9080   //   ...
9081   BB = exitMBB;
9082   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9083     .addReg(ShiftReg);
9084   return BB;
9085 }
9086
9087 llvm::MachineBasicBlock *
9088 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9089                                     MachineBasicBlock *MBB) const {
9090   DebugLoc DL = MI.getDebugLoc();
9091   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9092   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9093
9094   MachineFunction *MF = MBB->getParent();
9095   MachineRegisterInfo &MRI = MF->getRegInfo();
9096
9097   const BasicBlock *BB = MBB->getBasicBlock();
9098   MachineFunction::iterator I = ++MBB->getIterator();
9099
9100   // Memory Reference
9101   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9102   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9103
9104   unsigned DstReg = MI.getOperand(0).getReg();
9105   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9106   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9107   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9108   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9109
9110   MVT PVT = getPointerTy(MF->getDataLayout());
9111   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9112          "Invalid Pointer Size!");
9113   // For v = setjmp(buf), we generate
9114   //
9115   // thisMBB:
9116   //  SjLjSetup mainMBB
9117   //  bl mainMBB
9118   //  v_restore = 1
9119   //  b sinkMBB
9120   //
9121   // mainMBB:
9122   //  buf[LabelOffset] = LR
9123   //  v_main = 0
9124   //
9125   // sinkMBB:
9126   //  v = phi(main, restore)
9127   //
9128
9129   MachineBasicBlock *thisMBB = MBB;
9130   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9131   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9132   MF->insert(I, mainMBB);
9133   MF->insert(I, sinkMBB);
9134
9135   MachineInstrBuilder MIB;
9136
9137   // Transfer the remainder of BB and its successor edges to sinkMBB.
9138   sinkMBB->splice(sinkMBB->begin(), MBB,
9139                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9140   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9141
9142   // Note that the structure of the jmp_buf used here is not compatible
9143   // with that used by libc, and is not designed to be. Specifically, it
9144   // stores only those 'reserved' registers that LLVM does not otherwise
9145   // understand how to spill. Also, by convention, by the time this
9146   // intrinsic is called, Clang has already stored the frame address in the
9147   // first slot of the buffer and stack address in the third. Following the
9148   // X86 target code, we'll store the jump address in the second slot. We also
9149   // need to save the TOC pointer (R2) to handle jumps between shared
9150   // libraries, and that will be stored in the fourth slot. The thread
9151   // identifier (R13) is not affected.
9152
9153   // thisMBB:
9154   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9155   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9156   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9157
9158   // Prepare IP either in reg.
9159   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9160   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9161   unsigned BufReg = MI.getOperand(1).getReg();
9162
9163   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9164     setUsesTOCBasePtr(*MBB->getParent());
9165     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9166             .addReg(PPC::X2)
9167             .addImm(TOCOffset)
9168             .addReg(BufReg);
9169     MIB.setMemRefs(MMOBegin, MMOEnd);
9170   }
9171
9172   // Naked functions never have a base pointer, and so we use r1. For all
9173   // other functions, this decision must be delayed until during PEI.
9174   unsigned BaseReg;
9175   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9176     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9177   else
9178     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9179
9180   MIB = BuildMI(*thisMBB, MI, DL,
9181                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9182             .addReg(BaseReg)
9183             .addImm(BPOffset)
9184             .addReg(BufReg);
9185   MIB.setMemRefs(MMOBegin, MMOEnd);
9186
9187   // Setup
9188   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9189   MIB.addRegMask(TRI->getNoPreservedMask());
9190
9191   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9192
9193   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9194           .addMBB(mainMBB);
9195   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9196
9197   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9198   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9199
9200   // mainMBB:
9201   //  mainDstReg = 0
9202   MIB =
9203       BuildMI(mainMBB, DL,
9204               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9205
9206   // Store IP
9207   if (Subtarget.isPPC64()) {
9208     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9209             .addReg(LabelReg)
9210             .addImm(LabelOffset)
9211             .addReg(BufReg);
9212   } else {
9213     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9214             .addReg(LabelReg)
9215             .addImm(LabelOffset)
9216             .addReg(BufReg);
9217   }
9218
9219   MIB.setMemRefs(MMOBegin, MMOEnd);
9220
9221   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9222   mainMBB->addSuccessor(sinkMBB);
9223
9224   // sinkMBB:
9225   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9226           TII->get(PPC::PHI), DstReg)
9227     .addReg(mainDstReg).addMBB(mainMBB)
9228     .addReg(restoreDstReg).addMBB(thisMBB);
9229
9230   MI.eraseFromParent();
9231   return sinkMBB;
9232 }
9233
9234 MachineBasicBlock *
9235 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9236                                      MachineBasicBlock *MBB) const {
9237   DebugLoc DL = MI.getDebugLoc();
9238   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9239
9240   MachineFunction *MF = MBB->getParent();
9241   MachineRegisterInfo &MRI = MF->getRegInfo();
9242
9243   // Memory Reference
9244   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9245   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9246
9247   MVT PVT = getPointerTy(MF->getDataLayout());
9248   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9249          "Invalid Pointer Size!");
9250
9251   const TargetRegisterClass *RC =
9252     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9253   unsigned Tmp = MRI.createVirtualRegister(RC);
9254   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9255   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9256   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9257   unsigned BP =
9258       (PVT == MVT::i64)
9259           ? PPC::X30
9260           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9261                                                               : PPC::R30);
9262
9263   MachineInstrBuilder MIB;
9264
9265   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9266   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9267   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9268   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9269
9270   unsigned BufReg = MI.getOperand(0).getReg();
9271
9272   // Reload FP (the jumped-to function may not have had a
9273   // frame pointer, and if so, then its r31 will be restored
9274   // as necessary).
9275   if (PVT == MVT::i64) {
9276     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9277             .addImm(0)
9278             .addReg(BufReg);
9279   } else {
9280     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9281             .addImm(0)
9282             .addReg(BufReg);
9283   }
9284   MIB.setMemRefs(MMOBegin, MMOEnd);
9285
9286   // Reload IP
9287   if (PVT == MVT::i64) {
9288     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9289             .addImm(LabelOffset)
9290             .addReg(BufReg);
9291   } else {
9292     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9293             .addImm(LabelOffset)
9294             .addReg(BufReg);
9295   }
9296   MIB.setMemRefs(MMOBegin, MMOEnd);
9297
9298   // Reload SP
9299   if (PVT == MVT::i64) {
9300     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9301             .addImm(SPOffset)
9302             .addReg(BufReg);
9303   } else {
9304     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9305             .addImm(SPOffset)
9306             .addReg(BufReg);
9307   }
9308   MIB.setMemRefs(MMOBegin, MMOEnd);
9309
9310   // Reload BP
9311   if (PVT == MVT::i64) {
9312     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9313             .addImm(BPOffset)
9314             .addReg(BufReg);
9315   } else {
9316     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9317             .addImm(BPOffset)
9318             .addReg(BufReg);
9319   }
9320   MIB.setMemRefs(MMOBegin, MMOEnd);
9321
9322   // Reload TOC
9323   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9324     setUsesTOCBasePtr(*MBB->getParent());
9325     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9326             .addImm(TOCOffset)
9327             .addReg(BufReg);
9328
9329     MIB.setMemRefs(MMOBegin, MMOEnd);
9330   }
9331
9332   // Jump
9333   BuildMI(*MBB, MI, DL,
9334           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9335   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9336
9337   MI.eraseFromParent();
9338   return MBB;
9339 }
9340
9341 MachineBasicBlock *
9342 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9343                                                MachineBasicBlock *BB) const {
9344   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9345       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9346     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9347         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9348       // Call lowering should have added an r2 operand to indicate a dependence
9349       // on the TOC base pointer value. It can't however, because there is no
9350       // way to mark the dependence as implicit there, and so the stackmap code
9351       // will confuse it with a regular operand. Instead, add the dependence
9352       // here.
9353       setUsesTOCBasePtr(*BB->getParent());
9354       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9355     }
9356
9357     return emitPatchPoint(MI, BB);
9358   }
9359
9360   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9361       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9362     return emitEHSjLjSetJmp(MI, BB);
9363   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9364              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9365     return emitEHSjLjLongJmp(MI, BB);
9366   }
9367
9368   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9369
9370   // To "insert" these instructions we actually have to insert their
9371   // control-flow patterns.
9372   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9373   MachineFunction::iterator It = ++BB->getIterator();
9374
9375   MachineFunction *F = BB->getParent();
9376
9377   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9378        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9379        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9380     SmallVector<MachineOperand, 2> Cond;
9381     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9382         MI.getOpcode() == PPC::SELECT_CC_I8)
9383       Cond.push_back(MI.getOperand(4));
9384     else
9385       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9386     Cond.push_back(MI.getOperand(1));
9387
9388     DebugLoc dl = MI.getDebugLoc();
9389     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9390                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9391   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9392              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9393              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9394              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9395              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9396              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9397              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9398              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9399              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9400              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9401              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9402              MI.getOpcode() == PPC::SELECT_I4 ||
9403              MI.getOpcode() == PPC::SELECT_I8 ||
9404              MI.getOpcode() == PPC::SELECT_F4 ||
9405              MI.getOpcode() == PPC::SELECT_F8 ||
9406              MI.getOpcode() == PPC::SELECT_QFRC ||
9407              MI.getOpcode() == PPC::SELECT_QSRC ||
9408              MI.getOpcode() == PPC::SELECT_QBRC ||
9409              MI.getOpcode() == PPC::SELECT_VRRC ||
9410              MI.getOpcode() == PPC::SELECT_VSFRC ||
9411              MI.getOpcode() == PPC::SELECT_VSSRC ||
9412              MI.getOpcode() == PPC::SELECT_VSRC) {
9413     // The incoming instruction knows the destination vreg to set, the
9414     // condition code register to branch on, the true/false values to
9415     // select between, and a branch opcode to use.
9416
9417     //  thisMBB:
9418     //  ...
9419     //   TrueVal = ...
9420     //   cmpTY ccX, r1, r2
9421     //   bCC copy1MBB
9422     //   fallthrough --> copy0MBB
9423     MachineBasicBlock *thisMBB = BB;
9424     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9425     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9426     DebugLoc dl = MI.getDebugLoc();
9427     F->insert(It, copy0MBB);
9428     F->insert(It, sinkMBB);
9429
9430     // Transfer the remainder of BB and its successor edges to sinkMBB.
9431     sinkMBB->splice(sinkMBB->begin(), BB,
9432                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9433     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9434
9435     // Next, add the true and fallthrough blocks as its successors.
9436     BB->addSuccessor(copy0MBB);
9437     BB->addSuccessor(sinkMBB);
9438
9439     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9440         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9441         MI.getOpcode() == PPC::SELECT_QFRC ||
9442         MI.getOpcode() == PPC::SELECT_QSRC ||
9443         MI.getOpcode() == PPC::SELECT_QBRC ||
9444         MI.getOpcode() == PPC::SELECT_VRRC ||
9445         MI.getOpcode() == PPC::SELECT_VSFRC ||
9446         MI.getOpcode() == PPC::SELECT_VSSRC ||
9447         MI.getOpcode() == PPC::SELECT_VSRC) {
9448       BuildMI(BB, dl, TII->get(PPC::BC))
9449           .addReg(MI.getOperand(1).getReg())
9450           .addMBB(sinkMBB);
9451     } else {
9452       unsigned SelectPred = MI.getOperand(4).getImm();
9453       BuildMI(BB, dl, TII->get(PPC::BCC))
9454           .addImm(SelectPred)
9455           .addReg(MI.getOperand(1).getReg())
9456           .addMBB(sinkMBB);
9457     }
9458
9459     //  copy0MBB:
9460     //   %FalseValue = ...
9461     //   # fallthrough to sinkMBB
9462     BB = copy0MBB;
9463
9464     // Update machine-CFG edges
9465     BB->addSuccessor(sinkMBB);
9466
9467     //  sinkMBB:
9468     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9469     //  ...
9470     BB = sinkMBB;
9471     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9472         .addReg(MI.getOperand(3).getReg())
9473         .addMBB(copy0MBB)
9474         .addReg(MI.getOperand(2).getReg())
9475         .addMBB(thisMBB);
9476   } else if (MI.getOpcode() == PPC::ReadTB) {
9477     // To read the 64-bit time-base register on a 32-bit target, we read the
9478     // two halves. Should the counter have wrapped while it was being read, we
9479     // need to try again.
9480     // ...
9481     // readLoop:
9482     // mfspr Rx,TBU # load from TBU
9483     // mfspr Ry,TB  # load from TB
9484     // mfspr Rz,TBU # load from TBU
9485     // cmpw crX,Rx,Rz # check if 'old'='new'
9486     // bne readLoop   # branch if they're not equal
9487     // ...
9488
9489     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9490     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9491     DebugLoc dl = MI.getDebugLoc();
9492     F->insert(It, readMBB);
9493     F->insert(It, sinkMBB);
9494
9495     // Transfer the remainder of BB and its successor edges to sinkMBB.
9496     sinkMBB->splice(sinkMBB->begin(), BB,
9497                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9498     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9499
9500     BB->addSuccessor(readMBB);
9501     BB = readMBB;
9502
9503     MachineRegisterInfo &RegInfo = F->getRegInfo();
9504     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9505     unsigned LoReg = MI.getOperand(0).getReg();
9506     unsigned HiReg = MI.getOperand(1).getReg();
9507
9508     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9509     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9510     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9511
9512     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9513
9514     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9515       .addReg(HiReg).addReg(ReadAgainReg);
9516     BuildMI(BB, dl, TII->get(PPC::BCC))
9517       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9518
9519     BB->addSuccessor(readMBB);
9520     BB->addSuccessor(sinkMBB);
9521   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9522     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9523   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9524     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9525   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9526     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9527   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9528     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9529
9530   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9531     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9532   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9533     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9534   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9535     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9536   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9537     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9538
9539   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9540     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9541   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9542     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9543   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9544     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9545   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9546     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9547
9548   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9549     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9550   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9551     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9552   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9553     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9554   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9555     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9556
9557   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9558     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9559   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9560     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9561   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9562     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9563   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9564     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9565
9566   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9567     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9568   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9569     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9570   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9571     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9572   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9573     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9574
9575   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9576     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9577   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9578     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9579   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9580     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9581   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9582     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9583
9584   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9585     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9586   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9587     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9588   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9589     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9590   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9591     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9592
9593   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9594     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9595   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9596     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9597   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9598     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9599   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9600     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9601
9602   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9603     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9604   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9605     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9606   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9607     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9608   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9609     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9610
9611   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9612     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9613   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9614     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9615   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9616     BB = EmitAtomicBinary(MI, BB, 4, 0);
9617   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9618     BB = EmitAtomicBinary(MI, BB, 8, 0);
9619   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9620            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9621            (Subtarget.hasPartwordAtomics() &&
9622             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9623            (Subtarget.hasPartwordAtomics() &&
9624             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9625     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9626
9627     auto LoadMnemonic = PPC::LDARX;
9628     auto StoreMnemonic = PPC::STDCX;
9629     switch (MI.getOpcode()) {
9630     default:
9631       llvm_unreachable("Compare and swap of unknown size");
9632     case PPC::ATOMIC_CMP_SWAP_I8:
9633       LoadMnemonic = PPC::LBARX;
9634       StoreMnemonic = PPC::STBCX;
9635       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9636       break;
9637     case PPC::ATOMIC_CMP_SWAP_I16:
9638       LoadMnemonic = PPC::LHARX;
9639       StoreMnemonic = PPC::STHCX;
9640       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9641       break;
9642     case PPC::ATOMIC_CMP_SWAP_I32:
9643       LoadMnemonic = PPC::LWARX;
9644       StoreMnemonic = PPC::STWCX;
9645       break;
9646     case PPC::ATOMIC_CMP_SWAP_I64:
9647       LoadMnemonic = PPC::LDARX;
9648       StoreMnemonic = PPC::STDCX;
9649       break;
9650     }
9651     unsigned dest = MI.getOperand(0).getReg();
9652     unsigned ptrA = MI.getOperand(1).getReg();
9653     unsigned ptrB = MI.getOperand(2).getReg();
9654     unsigned oldval = MI.getOperand(3).getReg();
9655     unsigned newval = MI.getOperand(4).getReg();
9656     DebugLoc dl = MI.getDebugLoc();
9657
9658     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9659     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9660     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9661     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9662     F->insert(It, loop1MBB);
9663     F->insert(It, loop2MBB);
9664     F->insert(It, midMBB);
9665     F->insert(It, exitMBB);
9666     exitMBB->splice(exitMBB->begin(), BB,
9667                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9668     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9669
9670     //  thisMBB:
9671     //   ...
9672     //   fallthrough --> loopMBB
9673     BB->addSuccessor(loop1MBB);
9674
9675     // loop1MBB:
9676     //   l[bhwd]arx dest, ptr
9677     //   cmp[wd] dest, oldval
9678     //   bne- midMBB
9679     // loop2MBB:
9680     //   st[bhwd]cx. newval, ptr
9681     //   bne- loopMBB
9682     //   b exitBB
9683     // midMBB:
9684     //   st[bhwd]cx. dest, ptr
9685     // exitBB:
9686     BB = loop1MBB;
9687     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9688       .addReg(ptrA).addReg(ptrB);
9689     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9690       .addReg(oldval).addReg(dest);
9691     BuildMI(BB, dl, TII->get(PPC::BCC))
9692       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9693     BB->addSuccessor(loop2MBB);
9694     BB->addSuccessor(midMBB);
9695
9696     BB = loop2MBB;
9697     BuildMI(BB, dl, TII->get(StoreMnemonic))
9698       .addReg(newval).addReg(ptrA).addReg(ptrB);
9699     BuildMI(BB, dl, TII->get(PPC::BCC))
9700       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9701     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9702     BB->addSuccessor(loop1MBB);
9703     BB->addSuccessor(exitMBB);
9704
9705     BB = midMBB;
9706     BuildMI(BB, dl, TII->get(StoreMnemonic))
9707       .addReg(dest).addReg(ptrA).addReg(ptrB);
9708     BB->addSuccessor(exitMBB);
9709
9710     //  exitMBB:
9711     //   ...
9712     BB = exitMBB;
9713   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9714              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9715     // We must use 64-bit registers for addresses when targeting 64-bit,
9716     // since we're actually doing arithmetic on them.  Other registers
9717     // can be 32-bit.
9718     bool is64bit = Subtarget.isPPC64();
9719     bool isLittleEndian = Subtarget.isLittleEndian();
9720     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9721
9722     unsigned dest = MI.getOperand(0).getReg();
9723     unsigned ptrA = MI.getOperand(1).getReg();
9724     unsigned ptrB = MI.getOperand(2).getReg();
9725     unsigned oldval = MI.getOperand(3).getReg();
9726     unsigned newval = MI.getOperand(4).getReg();
9727     DebugLoc dl = MI.getDebugLoc();
9728
9729     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9730     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9731     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9732     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9733     F->insert(It, loop1MBB);
9734     F->insert(It, loop2MBB);
9735     F->insert(It, midMBB);
9736     F->insert(It, exitMBB);
9737     exitMBB->splice(exitMBB->begin(), BB,
9738                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9739     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9740
9741     MachineRegisterInfo &RegInfo = F->getRegInfo();
9742     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9743                                             : &PPC::GPRCRegClass;
9744     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9745     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9746     unsigned ShiftReg =
9747       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9748     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9749     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9750     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9751     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9752     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9753     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9754     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9755     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9756     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9757     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9758     unsigned Ptr1Reg;
9759     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9760     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9761     //  thisMBB:
9762     //   ...
9763     //   fallthrough --> loopMBB
9764     BB->addSuccessor(loop1MBB);
9765
9766     // The 4-byte load must be aligned, while a char or short may be
9767     // anywhere in the word.  Hence all this nasty bookkeeping code.
9768     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9769     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9770     //   xori shift, shift1, 24 [16]
9771     //   rlwinm ptr, ptr1, 0, 0, 29
9772     //   slw newval2, newval, shift
9773     //   slw oldval2, oldval,shift
9774     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9775     //   slw mask, mask2, shift
9776     //   and newval3, newval2, mask
9777     //   and oldval3, oldval2, mask
9778     // loop1MBB:
9779     //   lwarx tmpDest, ptr
9780     //   and tmp, tmpDest, mask
9781     //   cmpw tmp, oldval3
9782     //   bne- midMBB
9783     // loop2MBB:
9784     //   andc tmp2, tmpDest, mask
9785     //   or tmp4, tmp2, newval3
9786     //   stwcx. tmp4, ptr
9787     //   bne- loop1MBB
9788     //   b exitBB
9789     // midMBB:
9790     //   stwcx. tmpDest, ptr
9791     // exitBB:
9792     //   srw dest, tmpDest, shift
9793     if (ptrA != ZeroReg) {
9794       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9795       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9796         .addReg(ptrA).addReg(ptrB);
9797     } else {
9798       Ptr1Reg = ptrB;
9799     }
9800     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9801         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9802     if (!isLittleEndian)
9803       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9804           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9805     if (is64bit)
9806       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9807         .addReg(Ptr1Reg).addImm(0).addImm(61);
9808     else
9809       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9810         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9811     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9812         .addReg(newval).addReg(ShiftReg);
9813     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9814         .addReg(oldval).addReg(ShiftReg);
9815     if (is8bit)
9816       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9817     else {
9818       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9819       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9820         .addReg(Mask3Reg).addImm(65535);
9821     }
9822     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9823         .addReg(Mask2Reg).addReg(ShiftReg);
9824     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9825         .addReg(NewVal2Reg).addReg(MaskReg);
9826     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9827         .addReg(OldVal2Reg).addReg(MaskReg);
9828
9829     BB = loop1MBB;
9830     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9831         .addReg(ZeroReg).addReg(PtrReg);
9832     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9833         .addReg(TmpDestReg).addReg(MaskReg);
9834     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9835         .addReg(TmpReg).addReg(OldVal3Reg);
9836     BuildMI(BB, dl, TII->get(PPC::BCC))
9837         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9838     BB->addSuccessor(loop2MBB);
9839     BB->addSuccessor(midMBB);
9840
9841     BB = loop2MBB;
9842     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9843         .addReg(TmpDestReg).addReg(MaskReg);
9844     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9845         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9846     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9847         .addReg(ZeroReg).addReg(PtrReg);
9848     BuildMI(BB, dl, TII->get(PPC::BCC))
9849       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9850     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9851     BB->addSuccessor(loop1MBB);
9852     BB->addSuccessor(exitMBB);
9853
9854     BB = midMBB;
9855     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9856       .addReg(ZeroReg).addReg(PtrReg);
9857     BB->addSuccessor(exitMBB);
9858
9859     //  exitMBB:
9860     //   ...
9861     BB = exitMBB;
9862     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9863       .addReg(ShiftReg);
9864   } else if (MI.getOpcode() == PPC::FADDrtz) {
9865     // This pseudo performs an FADD with rounding mode temporarily forced
9866     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9867     // is not modeled at the SelectionDAG level.
9868     unsigned Dest = MI.getOperand(0).getReg();
9869     unsigned Src1 = MI.getOperand(1).getReg();
9870     unsigned Src2 = MI.getOperand(2).getReg();
9871     DebugLoc dl = MI.getDebugLoc();
9872
9873     MachineRegisterInfo &RegInfo = F->getRegInfo();
9874     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9875
9876     // Save FPSCR value.
9877     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9878
9879     // Set rounding mode to round-to-zero.
9880     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9881     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9882
9883     // Perform addition.
9884     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9885
9886     // Restore FPSCR value.
9887     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9888   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9889              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9890              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9891              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9892     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9893                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9894                           ? PPC::ANDIo8
9895                           : PPC::ANDIo;
9896     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9897                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9898
9899     MachineRegisterInfo &RegInfo = F->getRegInfo();
9900     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9901                                                   &PPC::GPRCRegClass :
9902                                                   &PPC::G8RCRegClass);
9903
9904     DebugLoc dl = MI.getDebugLoc();
9905     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9906         .addReg(MI.getOperand(1).getReg())
9907         .addImm(1);
9908     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9909             MI.getOperand(0).getReg())
9910         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9911   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9912     DebugLoc Dl = MI.getDebugLoc();
9913     MachineRegisterInfo &RegInfo = F->getRegInfo();
9914     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9915     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9916     return BB;
9917   } else {
9918     llvm_unreachable("Unexpected instr type to insert");
9919   }
9920
9921   MI.eraseFromParent(); // The pseudo instruction is gone now.
9922   return BB;
9923 }
9924
9925 //===----------------------------------------------------------------------===//
9926 // Target Optimization Hooks
9927 //===----------------------------------------------------------------------===//
9928
9929 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9930   // For the estimates, convergence is quadratic, so we essentially double the
9931   // number of digits correct after every iteration. For both FRE and FRSQRTE,
9932   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9933   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9934   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9935   if (VT.getScalarType() == MVT::f64)
9936     RefinementSteps++;
9937   return RefinementSteps;
9938 }
9939
9940 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9941                                            int Enabled, int &RefinementSteps,
9942                                            bool &UseOneConstNR,
9943                                            bool Reciprocal) const {
9944   EVT VT = Operand.getValueType();
9945   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9946       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9947       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9948       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9949       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9950       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9951     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9952       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9953
9954     UseOneConstNR = true;
9955     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9956   }
9957   return SDValue();
9958 }
9959
9960 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9961                                             int Enabled,
9962                                             int &RefinementSteps) const {
9963   EVT VT = Operand.getValueType();
9964   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9965       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9966       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9967       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9968       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9969       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9970     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9971       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9972     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9973   }
9974   return SDValue();
9975 }
9976
9977 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9978   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9979   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9980   // enabled for division), this functionality is redundant with the default
9981   // combiner logic (once the division -> reciprocal/multiply transformation
9982   // has taken place). As a result, this matters more for older cores than for
9983   // newer ones.
9984
9985   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9986   // reciprocal if there are two or more FDIVs (for embedded cores with only
9987   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9988   switch (Subtarget.getDarwinDirective()) {
9989   default:
9990     return 3;
9991   case PPC::DIR_440:
9992   case PPC::DIR_A2:
9993   case PPC::DIR_E500mc:
9994   case PPC::DIR_E5500:
9995     return 2;
9996   }
9997 }
9998
9999 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10000 // collapsed, and so we need to look through chains of them.
10001 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10002                                      int64_t& Offset, SelectionDAG &DAG) {
10003   if (DAG.isBaseWithConstantOffset(Loc)) {
10004     Base = Loc.getOperand(0);
10005     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10006
10007     // The base might itself be a base plus an offset, and if so, accumulate
10008     // that as well.
10009     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10010   }
10011 }
10012
10013 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10014                             unsigned Bytes, int Dist,
10015                             SelectionDAG &DAG) {
10016   if (VT.getSizeInBits() / 8 != Bytes)
10017     return false;
10018
10019   SDValue BaseLoc = Base->getBasePtr();
10020   if (Loc.getOpcode() == ISD::FrameIndex) {
10021     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10022       return false;
10023     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10024     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10025     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10026     int FS  = MFI.getObjectSize(FI);
10027     int BFS = MFI.getObjectSize(BFI);
10028     if (FS != BFS || FS != (int)Bytes) return false;
10029     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10030   }
10031
10032   SDValue Base1 = Loc, Base2 = BaseLoc;
10033   int64_t Offset1 = 0, Offset2 = 0;
10034   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10035   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10036   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10037     return true;
10038
10039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10040   const GlobalValue *GV1 = nullptr;
10041   const GlobalValue *GV2 = nullptr;
10042   Offset1 = 0;
10043   Offset2 = 0;
10044   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10045   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10046   if (isGA1 && isGA2 && GV1 == GV2)
10047     return Offset1 == (Offset2 + Dist*Bytes);
10048   return false;
10049 }
10050
10051 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10052 // not enforce equality of the chain operands.
10053 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10054                             unsigned Bytes, int Dist,
10055                             SelectionDAG &DAG) {
10056   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10057     EVT VT = LS->getMemoryVT();
10058     SDValue Loc = LS->getBasePtr();
10059     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10060   }
10061
10062   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10063     EVT VT;
10064     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10065     default: return false;
10066     case Intrinsic::ppc_qpx_qvlfd:
10067     case Intrinsic::ppc_qpx_qvlfda:
10068       VT = MVT::v4f64;
10069       break;
10070     case Intrinsic::ppc_qpx_qvlfs:
10071     case Intrinsic::ppc_qpx_qvlfsa:
10072       VT = MVT::v4f32;
10073       break;
10074     case Intrinsic::ppc_qpx_qvlfcd:
10075     case Intrinsic::ppc_qpx_qvlfcda:
10076       VT = MVT::v2f64;
10077       break;
10078     case Intrinsic::ppc_qpx_qvlfcs:
10079     case Intrinsic::ppc_qpx_qvlfcsa:
10080       VT = MVT::v2f32;
10081       break;
10082     case Intrinsic::ppc_qpx_qvlfiwa:
10083     case Intrinsic::ppc_qpx_qvlfiwz:
10084     case Intrinsic::ppc_altivec_lvx:
10085     case Intrinsic::ppc_altivec_lvxl:
10086     case Intrinsic::ppc_vsx_lxvw4x:
10087     case Intrinsic::ppc_vsx_lxvw4x_be:
10088       VT = MVT::v4i32;
10089       break;
10090     case Intrinsic::ppc_vsx_lxvd2x:
10091     case Intrinsic::ppc_vsx_lxvd2x_be:
10092       VT = MVT::v2f64;
10093       break;
10094     case Intrinsic::ppc_altivec_lvebx:
10095       VT = MVT::i8;
10096       break;
10097     case Intrinsic::ppc_altivec_lvehx:
10098       VT = MVT::i16;
10099       break;
10100     case Intrinsic::ppc_altivec_lvewx:
10101       VT = MVT::i32;
10102       break;
10103     }
10104
10105     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10106   }
10107
10108   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10109     EVT VT;
10110     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10111     default: return false;
10112     case Intrinsic::ppc_qpx_qvstfd:
10113     case Intrinsic::ppc_qpx_qvstfda:
10114       VT = MVT::v4f64;
10115       break;
10116     case Intrinsic::ppc_qpx_qvstfs:
10117     case Intrinsic::ppc_qpx_qvstfsa:
10118       VT = MVT::v4f32;
10119       break;
10120     case Intrinsic::ppc_qpx_qvstfcd:
10121     case Intrinsic::ppc_qpx_qvstfcda:
10122       VT = MVT::v2f64;
10123       break;
10124     case Intrinsic::ppc_qpx_qvstfcs:
10125     case Intrinsic::ppc_qpx_qvstfcsa:
10126       VT = MVT::v2f32;
10127       break;
10128     case Intrinsic::ppc_qpx_qvstfiw:
10129     case Intrinsic::ppc_qpx_qvstfiwa:
10130     case Intrinsic::ppc_altivec_stvx:
10131     case Intrinsic::ppc_altivec_stvxl:
10132     case Intrinsic::ppc_vsx_stxvw4x:
10133       VT = MVT::v4i32;
10134       break;
10135     case Intrinsic::ppc_vsx_stxvd2x:
10136       VT = MVT::v2f64;
10137       break;
10138     case Intrinsic::ppc_vsx_stxvw4x_be:
10139       VT = MVT::v4i32;
10140       break;
10141     case Intrinsic::ppc_vsx_stxvd2x_be:
10142       VT = MVT::v2f64;
10143       break;
10144     case Intrinsic::ppc_altivec_stvebx:
10145       VT = MVT::i8;
10146       break;
10147     case Intrinsic::ppc_altivec_stvehx:
10148       VT = MVT::i16;
10149       break;
10150     case Intrinsic::ppc_altivec_stvewx:
10151       VT = MVT::i32;
10152       break;
10153     }
10154
10155     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10156   }
10157
10158   return false;
10159 }
10160
10161 // Return true is there is a nearyby consecutive load to the one provided
10162 // (regardless of alignment). We search up and down the chain, looking though
10163 // token factors and other loads (but nothing else). As a result, a true result
10164 // indicates that it is safe to create a new consecutive load adjacent to the
10165 // load provided.
10166 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10167   SDValue Chain = LD->getChain();
10168   EVT VT = LD->getMemoryVT();
10169
10170   SmallSet<SDNode *, 16> LoadRoots;
10171   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10172   SmallSet<SDNode *, 16> Visited;
10173
10174   // First, search up the chain, branching to follow all token-factor operands.
10175   // If we find a consecutive load, then we're done, otherwise, record all
10176   // nodes just above the top-level loads and token factors.
10177   while (!Queue.empty()) {
10178     SDNode *ChainNext = Queue.pop_back_val();
10179     if (!Visited.insert(ChainNext).second)
10180       continue;
10181
10182     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10183       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10184         return true;
10185
10186       if (!Visited.count(ChainLD->getChain().getNode()))
10187         Queue.push_back(ChainLD->getChain().getNode());
10188     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10189       for (const SDUse &O : ChainNext->ops())
10190         if (!Visited.count(O.getNode()))
10191           Queue.push_back(O.getNode());
10192     } else
10193       LoadRoots.insert(ChainNext);
10194   }
10195
10196   // Second, search down the chain, starting from the top-level nodes recorded
10197   // in the first phase. These top-level nodes are the nodes just above all
10198   // loads and token factors. Starting with their uses, recursively look though
10199   // all loads (just the chain uses) and token factors to find a consecutive
10200   // load.
10201   Visited.clear();
10202   Queue.clear();
10203
10204   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10205        IE = LoadRoots.end(); I != IE; ++I) {
10206     Queue.push_back(*I);
10207
10208     while (!Queue.empty()) {
10209       SDNode *LoadRoot = Queue.pop_back_val();
10210       if (!Visited.insert(LoadRoot).second)
10211         continue;
10212
10213       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10214         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10215           return true;
10216
10217       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10218            UE = LoadRoot->use_end(); UI != UE; ++UI)
10219         if (((isa<MemSDNode>(*UI) &&
10220             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10221             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10222           Queue.push_back(*UI);
10223     }
10224   }
10225
10226   return false;
10227 }
10228
10229 /// This function is called when we have proved that a SETCC node can be replaced
10230 /// by subtraction (and other supporting instructions) so that the result of
10231 /// comparison is kept in a GPR instead of CR. This function is purely for
10232 /// codegen purposes and has some flags to guide the codegen process.
10233 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10234                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10235   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10236
10237   // Zero extend the operands to the largest legal integer. Originally, they
10238   // must be of a strictly smaller size.
10239   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10240                          DAG.getConstant(Size, DL, MVT::i32));
10241   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10242                          DAG.getConstant(Size, DL, MVT::i32));
10243
10244   // Swap if needed. Depends on the condition code.
10245   if (Swap)
10246     std::swap(Op0, Op1);
10247
10248   // Subtract extended integers.
10249   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10250
10251   // Move the sign bit to the least significant position and zero out the rest.
10252   // Now the least significant bit carries the result of original comparison.
10253   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10254                              DAG.getConstant(Size - 1, DL, MVT::i32));
10255   auto Final = Shifted;
10256
10257   // Complement the result if needed. Based on the condition code.
10258   if (Complement)
10259     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10260                         DAG.getConstant(1, DL, MVT::i64));
10261
10262   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10263 }
10264
10265 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10266                                                   DAGCombinerInfo &DCI) const {
10267   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10268
10269   SelectionDAG &DAG = DCI.DAG;
10270   SDLoc DL(N);
10271
10272   // Size of integers being compared has a critical role in the following
10273   // analysis, so we prefer to do this when all types are legal.
10274   if (!DCI.isAfterLegalizeVectorOps())
10275     return SDValue();
10276
10277   // If all users of SETCC extend its value to a legal integer type
10278   // then we replace SETCC with a subtraction
10279   for (SDNode::use_iterator UI = N->use_begin(),
10280        UE = N->use_end(); UI != UE; ++UI) {
10281     if (UI->getOpcode() != ISD::ZERO_EXTEND)
10282       return SDValue();
10283   }
10284
10285   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10286   auto OpSize = N->getOperand(0).getValueSizeInBits();
10287
10288   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10289
10290   if (OpSize < Size) {
10291     switch (CC) {
10292     default: break;
10293     case ISD::SETULT:
10294       return generateEquivalentSub(N, Size, false, false, DL, DAG);
10295     case ISD::SETULE:
10296       return generateEquivalentSub(N, Size, true, true, DL, DAG);
10297     case ISD::SETUGT:
10298       return generateEquivalentSub(N, Size, false, true, DL, DAG);
10299     case ISD::SETUGE:
10300       return generateEquivalentSub(N, Size, true, false, DL, DAG);
10301     }
10302   }
10303
10304   return SDValue();
10305 }
10306
10307 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10308                                                   DAGCombinerInfo &DCI) const {
10309   SelectionDAG &DAG = DCI.DAG;
10310   SDLoc dl(N);
10311
10312   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10313   // If we're tracking CR bits, we need to be careful that we don't have:
10314   //   trunc(binary-ops(zext(x), zext(y)))
10315   // or
10316   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10317   // such that we're unnecessarily moving things into GPRs when it would be
10318   // better to keep them in CR bits.
10319
10320   // Note that trunc here can be an actual i1 trunc, or can be the effective
10321   // truncation that comes from a setcc or select_cc.
10322   if (N->getOpcode() == ISD::TRUNCATE &&
10323       N->getValueType(0) != MVT::i1)
10324     return SDValue();
10325
10326   if (N->getOperand(0).getValueType() != MVT::i32 &&
10327       N->getOperand(0).getValueType() != MVT::i64)
10328     return SDValue();
10329
10330   if (N->getOpcode() == ISD::SETCC ||
10331       N->getOpcode() == ISD::SELECT_CC) {
10332     // If we're looking at a comparison, then we need to make sure that the
10333     // high bits (all except for the first) don't matter the result.
10334     ISD::CondCode CC =
10335       cast<CondCodeSDNode>(N->getOperand(
10336         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10337     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10338
10339     if (ISD::isSignedIntSetCC(CC)) {
10340       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10341           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10342         return SDValue();
10343     } else if (ISD::isUnsignedIntSetCC(CC)) {
10344       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10345                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10346           !DAG.MaskedValueIsZero(N->getOperand(1),
10347                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10348         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10349                                              : SDValue());
10350     } else {
10351       // This is neither a signed nor an unsigned comparison, just make sure
10352       // that the high bits are equal.
10353       KnownBits Op1Known, Op2Known;
10354       DAG.computeKnownBits(N->getOperand(0), Op1Known);
10355       DAG.computeKnownBits(N->getOperand(1), Op2Known);
10356
10357       // We don't really care about what is known about the first bit (if
10358       // anything), so clear it in all masks prior to comparing them.
10359       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10360       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10361
10362       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10363         return SDValue();
10364     }
10365   }
10366
10367   // We now know that the higher-order bits are irrelevant, we just need to
10368   // make sure that all of the intermediate operations are bit operations, and
10369   // all inputs are extensions.
10370   if (N->getOperand(0).getOpcode() != ISD::AND &&
10371       N->getOperand(0).getOpcode() != ISD::OR  &&
10372       N->getOperand(0).getOpcode() != ISD::XOR &&
10373       N->getOperand(0).getOpcode() != ISD::SELECT &&
10374       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10375       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10376       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10377       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10378       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10379     return SDValue();
10380
10381   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10382       N->getOperand(1).getOpcode() != ISD::AND &&
10383       N->getOperand(1).getOpcode() != ISD::OR  &&
10384       N->getOperand(1).getOpcode() != ISD::XOR &&
10385       N->getOperand(1).getOpcode() != ISD::SELECT &&
10386       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10387       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10388       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10389       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10390       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10391     return SDValue();
10392
10393   SmallVector<SDValue, 4> Inputs;
10394   SmallVector<SDValue, 8> BinOps, PromOps;
10395   SmallPtrSet<SDNode *, 16> Visited;
10396
10397   for (unsigned i = 0; i < 2; ++i) {
10398     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10399           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10400           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10401           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10402         isa<ConstantSDNode>(N->getOperand(i)))
10403       Inputs.push_back(N->getOperand(i));
10404     else
10405       BinOps.push_back(N->getOperand(i));
10406
10407     if (N->getOpcode() == ISD::TRUNCATE)
10408       break;
10409   }
10410
10411   // Visit all inputs, collect all binary operations (and, or, xor and
10412   // select) that are all fed by extensions.
10413   while (!BinOps.empty()) {
10414     SDValue BinOp = BinOps.back();
10415     BinOps.pop_back();
10416
10417     if (!Visited.insert(BinOp.getNode()).second)
10418       continue;
10419
10420     PromOps.push_back(BinOp);
10421
10422     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10423       // The condition of the select is not promoted.
10424       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10425         continue;
10426       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10427         continue;
10428
10429       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10430             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10431             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10432            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10433           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10434         Inputs.push_back(BinOp.getOperand(i));
10435       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10436                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10437                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10438                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10439                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10440                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10441                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10442                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10443                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10444         BinOps.push_back(BinOp.getOperand(i));
10445       } else {
10446         // We have an input that is not an extension or another binary
10447         // operation; we'll abort this transformation.
10448         return SDValue();
10449       }
10450     }
10451   }
10452
10453   // Make sure that this is a self-contained cluster of operations (which
10454   // is not quite the same thing as saying that everything has only one
10455   // use).
10456   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10457     if (isa<ConstantSDNode>(Inputs[i]))
10458       continue;
10459
10460     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10461                               UE = Inputs[i].getNode()->use_end();
10462          UI != UE; ++UI) {
10463       SDNode *User = *UI;
10464       if (User != N && !Visited.count(User))
10465         return SDValue();
10466
10467       // Make sure that we're not going to promote the non-output-value
10468       // operand(s) or SELECT or SELECT_CC.
10469       // FIXME: Although we could sometimes handle this, and it does occur in
10470       // practice that one of the condition inputs to the select is also one of
10471       // the outputs, we currently can't deal with this.
10472       if (User->getOpcode() == ISD::SELECT) {
10473         if (User->getOperand(0) == Inputs[i])
10474           return SDValue();
10475       } else if (User->getOpcode() == ISD::SELECT_CC) {
10476         if (User->getOperand(0) == Inputs[i] ||
10477             User->getOperand(1) == Inputs[i])
10478           return SDValue();
10479       }
10480     }
10481   }
10482
10483   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10484     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10485                               UE = PromOps[i].getNode()->use_end();
10486          UI != UE; ++UI) {
10487       SDNode *User = *UI;
10488       if (User != N && !Visited.count(User))
10489         return SDValue();
10490
10491       // Make sure that we're not going to promote the non-output-value
10492       // operand(s) or SELECT or SELECT_CC.
10493       // FIXME: Although we could sometimes handle this, and it does occur in
10494       // practice that one of the condition inputs to the select is also one of
10495       // the outputs, we currently can't deal with this.
10496       if (User->getOpcode() == ISD::SELECT) {
10497         if (User->getOperand(0) == PromOps[i])
10498           return SDValue();
10499       } else if (User->getOpcode() == ISD::SELECT_CC) {
10500         if (User->getOperand(0) == PromOps[i] ||
10501             User->getOperand(1) == PromOps[i])
10502           return SDValue();
10503       }
10504     }
10505   }
10506
10507   // Replace all inputs with the extension operand.
10508   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10509     // Constants may have users outside the cluster of to-be-promoted nodes,
10510     // and so we need to replace those as we do the promotions.
10511     if (isa<ConstantSDNode>(Inputs[i]))
10512       continue;
10513     else
10514       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10515   }
10516
10517   std::list<HandleSDNode> PromOpHandles;
10518   for (auto &PromOp : PromOps)
10519     PromOpHandles.emplace_back(PromOp);
10520
10521   // Replace all operations (these are all the same, but have a different
10522   // (i1) return type). DAG.getNode will validate that the types of
10523   // a binary operator match, so go through the list in reverse so that
10524   // we've likely promoted both operands first. Any intermediate truncations or
10525   // extensions disappear.
10526   while (!PromOpHandles.empty()) {
10527     SDValue PromOp = PromOpHandles.back().getValue();
10528     PromOpHandles.pop_back();
10529
10530     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10531         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10532         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10533         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10534       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10535           PromOp.getOperand(0).getValueType() != MVT::i1) {
10536         // The operand is not yet ready (see comment below).
10537         PromOpHandles.emplace_front(PromOp);
10538         continue;
10539       }
10540
10541       SDValue RepValue = PromOp.getOperand(0);
10542       if (isa<ConstantSDNode>(RepValue))
10543         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10544
10545       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10546       continue;
10547     }
10548
10549     unsigned C;
10550     switch (PromOp.getOpcode()) {
10551     default:             C = 0; break;
10552     case ISD::SELECT:    C = 1; break;
10553     case ISD::SELECT_CC: C = 2; break;
10554     }
10555
10556     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10557          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10558         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10559          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10560       // The to-be-promoted operands of this node have not yet been
10561       // promoted (this should be rare because we're going through the
10562       // list backward, but if one of the operands has several users in
10563       // this cluster of to-be-promoted nodes, it is possible).
10564       PromOpHandles.emplace_front(PromOp);
10565       continue;
10566     }
10567
10568     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10569                                 PromOp.getNode()->op_end());
10570
10571     // If there are any constant inputs, make sure they're replaced now.
10572     for (unsigned i = 0; i < 2; ++i)
10573       if (isa<ConstantSDNode>(Ops[C+i]))
10574         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10575
10576     DAG.ReplaceAllUsesOfValueWith(PromOp,
10577       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10578   }
10579
10580   // Now we're left with the initial truncation itself.
10581   if (N->getOpcode() == ISD::TRUNCATE)
10582     return N->getOperand(0);
10583
10584   // Otherwise, this is a comparison. The operands to be compared have just
10585   // changed type (to i1), but everything else is the same.
10586   return SDValue(N, 0);
10587 }
10588
10589 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10590                                                   DAGCombinerInfo &DCI) const {
10591   SelectionDAG &DAG = DCI.DAG;
10592   SDLoc dl(N);
10593
10594   // If we're tracking CR bits, we need to be careful that we don't have:
10595   //   zext(binary-ops(trunc(x), trunc(y)))
10596   // or
10597   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10598   // such that we're unnecessarily moving things into CR bits that can more
10599   // efficiently stay in GPRs. Note that if we're not certain that the high
10600   // bits are set as required by the final extension, we still may need to do
10601   // some masking to get the proper behavior.
10602
10603   // This same functionality is important on PPC64 when dealing with
10604   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10605   // the return values of functions. Because it is so similar, it is handled
10606   // here as well.
10607
10608   if (N->getValueType(0) != MVT::i32 &&
10609       N->getValueType(0) != MVT::i64)
10610     return SDValue();
10611
10612   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10613         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10614     return SDValue();
10615
10616   if (N->getOperand(0).getOpcode() != ISD::AND &&
10617       N->getOperand(0).getOpcode() != ISD::OR  &&
10618       N->getOperand(0).getOpcode() != ISD::XOR &&
10619       N->getOperand(0).getOpcode() != ISD::SELECT &&
10620       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10621     return SDValue();
10622
10623   SmallVector<SDValue, 4> Inputs;
10624   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10625   SmallPtrSet<SDNode *, 16> Visited;
10626
10627   // Visit all inputs, collect all binary operations (and, or, xor and
10628   // select) that are all fed by truncations.
10629   while (!BinOps.empty()) {
10630     SDValue BinOp = BinOps.back();
10631     BinOps.pop_back();
10632
10633     if (!Visited.insert(BinOp.getNode()).second)
10634       continue;
10635
10636     PromOps.push_back(BinOp);
10637
10638     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10639       // The condition of the select is not promoted.
10640       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10641         continue;
10642       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10643         continue;
10644
10645       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10646           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10647         Inputs.push_back(BinOp.getOperand(i));
10648       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10649                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10650                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10651                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10652                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10653         BinOps.push_back(BinOp.getOperand(i));
10654       } else {
10655         // We have an input that is not a truncation or another binary
10656         // operation; we'll abort this transformation.
10657         return SDValue();
10658       }
10659     }
10660   }
10661
10662   // The operands of a select that must be truncated when the select is
10663   // promoted because the operand is actually part of the to-be-promoted set.
10664   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10665
10666   // Make sure that this is a self-contained cluster of operations (which
10667   // is not quite the same thing as saying that everything has only one
10668   // use).
10669   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10670     if (isa<ConstantSDNode>(Inputs[i]))
10671       continue;
10672
10673     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10674                               UE = Inputs[i].getNode()->use_end();
10675          UI != UE; ++UI) {
10676       SDNode *User = *UI;
10677       if (User != N && !Visited.count(User))
10678         return SDValue();
10679
10680       // If we're going to promote the non-output-value operand(s) or SELECT or
10681       // SELECT_CC, record them for truncation.
10682       if (User->getOpcode() == ISD::SELECT) {
10683         if (User->getOperand(0) == Inputs[i])
10684           SelectTruncOp[0].insert(std::make_pair(User,
10685                                     User->getOperand(0).getValueType()));
10686       } else if (User->getOpcode() == ISD::SELECT_CC) {
10687         if (User->getOperand(0) == Inputs[i])
10688           SelectTruncOp[0].insert(std::make_pair(User,
10689                                     User->getOperand(0).getValueType()));
10690         if (User->getOperand(1) == Inputs[i])
10691           SelectTruncOp[1].insert(std::make_pair(User,
10692                                     User->getOperand(1).getValueType()));
10693       }
10694     }
10695   }
10696
10697   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10698     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10699                               UE = PromOps[i].getNode()->use_end();
10700          UI != UE; ++UI) {
10701       SDNode *User = *UI;
10702       if (User != N && !Visited.count(User))
10703         return SDValue();
10704
10705       // If we're going to promote the non-output-value operand(s) or SELECT or
10706       // SELECT_CC, record them for truncation.
10707       if (User->getOpcode() == ISD::SELECT) {
10708         if (User->getOperand(0) == PromOps[i])
10709           SelectTruncOp[0].insert(std::make_pair(User,
10710                                     User->getOperand(0).getValueType()));
10711       } else if (User->getOpcode() == ISD::SELECT_CC) {
10712         if (User->getOperand(0) == PromOps[i])
10713           SelectTruncOp[0].insert(std::make_pair(User,
10714                                     User->getOperand(0).getValueType()));
10715         if (User->getOperand(1) == PromOps[i])
10716           SelectTruncOp[1].insert(std::make_pair(User,
10717                                     User->getOperand(1).getValueType()));
10718       }
10719     }
10720   }
10721
10722   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10723   bool ReallyNeedsExt = false;
10724   if (N->getOpcode() != ISD::ANY_EXTEND) {
10725     // If all of the inputs are not already sign/zero extended, then
10726     // we'll still need to do that at the end.
10727     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10728       if (isa<ConstantSDNode>(Inputs[i]))
10729         continue;
10730
10731       unsigned OpBits =
10732         Inputs[i].getOperand(0).getValueSizeInBits();
10733       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10734
10735       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10736            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10737                                   APInt::getHighBitsSet(OpBits,
10738                                                         OpBits-PromBits))) ||
10739           (N->getOpcode() == ISD::SIGN_EXTEND &&
10740            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10741              (OpBits-(PromBits-1)))) {
10742         ReallyNeedsExt = true;
10743         break;
10744       }
10745     }
10746   }
10747
10748   // Replace all inputs, either with the truncation operand, or a
10749   // truncation or extension to the final output type.
10750   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10751     // Constant inputs need to be replaced with the to-be-promoted nodes that
10752     // use them because they might have users outside of the cluster of
10753     // promoted nodes.
10754     if (isa<ConstantSDNode>(Inputs[i]))
10755       continue;
10756
10757     SDValue InSrc = Inputs[i].getOperand(0);
10758     if (Inputs[i].getValueType() == N->getValueType(0))
10759       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10760     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10761       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10762         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10763     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10764       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10765         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10766     else
10767       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10768         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10769   }
10770
10771   std::list<HandleSDNode> PromOpHandles;
10772   for (auto &PromOp : PromOps)
10773     PromOpHandles.emplace_back(PromOp);
10774
10775   // Replace all operations (these are all the same, but have a different
10776   // (promoted) return type). DAG.getNode will validate that the types of
10777   // a binary operator match, so go through the list in reverse so that
10778   // we've likely promoted both operands first.
10779   while (!PromOpHandles.empty()) {
10780     SDValue PromOp = PromOpHandles.back().getValue();
10781     PromOpHandles.pop_back();
10782
10783     unsigned C;
10784     switch (PromOp.getOpcode()) {
10785     default:             C = 0; break;
10786     case ISD::SELECT:    C = 1; break;
10787     case ISD::SELECT_CC: C = 2; break;
10788     }
10789
10790     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10791          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10792         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10793          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10794       // The to-be-promoted operands of this node have not yet been
10795       // promoted (this should be rare because we're going through the
10796       // list backward, but if one of the operands has several users in
10797       // this cluster of to-be-promoted nodes, it is possible).
10798       PromOpHandles.emplace_front(PromOp);
10799       continue;
10800     }
10801
10802     // For SELECT and SELECT_CC nodes, we do a similar check for any
10803     // to-be-promoted comparison inputs.
10804     if (PromOp.getOpcode() == ISD::SELECT ||
10805         PromOp.getOpcode() == ISD::SELECT_CC) {
10806       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10807            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10808           (SelectTruncOp[1].count(PromOp.getNode()) &&
10809            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10810         PromOpHandles.emplace_front(PromOp);
10811         continue;
10812       }
10813     }
10814
10815     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10816                                 PromOp.getNode()->op_end());
10817
10818     // If this node has constant inputs, then they'll need to be promoted here.
10819     for (unsigned i = 0; i < 2; ++i) {
10820       if (!isa<ConstantSDNode>(Ops[C+i]))
10821         continue;
10822       if (Ops[C+i].getValueType() == N->getValueType(0))
10823         continue;
10824
10825       if (N->getOpcode() == ISD::SIGN_EXTEND)
10826         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10827       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10828         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10829       else
10830         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10831     }
10832
10833     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10834     // truncate them again to the original value type.
10835     if (PromOp.getOpcode() == ISD::SELECT ||
10836         PromOp.getOpcode() == ISD::SELECT_CC) {
10837       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10838       if (SI0 != SelectTruncOp[0].end())
10839         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10840       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10841       if (SI1 != SelectTruncOp[1].end())
10842         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10843     }
10844
10845     DAG.ReplaceAllUsesOfValueWith(PromOp,
10846       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10847   }
10848
10849   // Now we're left with the initial extension itself.
10850   if (!ReallyNeedsExt)
10851     return N->getOperand(0);
10852
10853   // To zero extend, just mask off everything except for the first bit (in the
10854   // i1 case).
10855   if (N->getOpcode() == ISD::ZERO_EXTEND)
10856     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10857                        DAG.getConstant(APInt::getLowBitsSet(
10858                                          N->getValueSizeInBits(0), PromBits),
10859                                        dl, N->getValueType(0)));
10860
10861   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10862          "Invalid extension type");
10863   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10864   SDValue ShiftCst =
10865       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10866   return DAG.getNode(
10867       ISD::SRA, dl, N->getValueType(0),
10868       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10869       ShiftCst);
10870 }
10871
10872 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10873 ///
10874 /// If this vector is built out of floating to integer conversions,
10875 /// transform it to a vector built out of floating point values followed by a
10876 /// single floating to integer conversion of the vector.
10877 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
10878 /// becomes (fptosi (build_vector ($A, $B, ...)))
10879 SDValue PPCTargetLowering::
10880 combineElementTruncationToVectorTruncation(SDNode *N,
10881                                            DAGCombinerInfo &DCI) const {
10882   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10883          "Should be called with a BUILD_VECTOR node");
10884
10885   SelectionDAG &DAG = DCI.DAG;
10886   SDLoc dl(N);
10887
10888   SDValue FirstInput = N->getOperand(0);
10889   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10890          "The input operand must be an fp-to-int conversion.");
10891
10892   // This combine happens after legalization so the fp_to_[su]i nodes are
10893   // already converted to PPCSISD nodes.
10894   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10895   if (FirstConversion == PPCISD::FCTIDZ ||
10896       FirstConversion == PPCISD::FCTIDUZ ||
10897       FirstConversion == PPCISD::FCTIWZ ||
10898       FirstConversion == PPCISD::FCTIWUZ) {
10899     bool IsSplat = true;
10900     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10901       FirstConversion == PPCISD::FCTIWUZ;
10902     EVT SrcVT = FirstInput.getOperand(0).getValueType();
10903     SmallVector<SDValue, 4> Ops;
10904     EVT TargetVT = N->getValueType(0);
10905     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10906       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
10907         return SDValue();
10908       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
10909       if (NextConversion != FirstConversion)
10910         return SDValue();
10911       if (N->getOperand(i) != FirstInput)
10912         IsSplat = false;
10913     }
10914
10915     // If this is a splat, we leave it as-is since there will be only a single
10916     // fp-to-int conversion followed by a splat of the integer. This is better
10917     // for 32-bit and smaller ints and neutral for 64-bit ints.
10918     if (IsSplat)
10919       return SDValue();
10920
10921     // Now that we know we have the right type of node, get its operands
10922     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10923       SDValue In = N->getOperand(i).getOperand(0);
10924       // For 32-bit values, we need to add an FP_ROUND node.
10925       if (Is32Bit) {
10926         if (In.isUndef())
10927           Ops.push_back(DAG.getUNDEF(SrcVT));
10928         else {
10929           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
10930                                       MVT::f32, In.getOperand(0),
10931                                       DAG.getIntPtrConstant(1, dl));
10932           Ops.push_back(Trunc);
10933         }
10934       } else
10935         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
10936     }
10937
10938     unsigned Opcode;
10939     if (FirstConversion == PPCISD::FCTIDZ ||
10940         FirstConversion == PPCISD::FCTIWZ)
10941       Opcode = ISD::FP_TO_SINT;
10942     else
10943       Opcode = ISD::FP_TO_UINT;
10944
10945     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
10946     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
10947     return DAG.getNode(Opcode, dl, TargetVT, BV);
10948   }
10949   return SDValue();
10950 }
10951
10952 /// \brief Reduce the number of loads when building a vector.
10953 ///
10954 /// Building a vector out of multiple loads can be converted to a load
10955 /// of the vector type if the loads are consecutive. If the loads are
10956 /// consecutive but in descending order, a shuffle is added at the end
10957 /// to reorder the vector.
10958 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
10959   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10960          "Should be called with a BUILD_VECTOR node");
10961
10962   SDLoc dl(N);
10963   bool InputsAreConsecutiveLoads = true;
10964   bool InputsAreReverseConsecutive = true;
10965   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
10966   SDValue FirstInput = N->getOperand(0);
10967   bool IsRoundOfExtLoad = false;
10968
10969   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
10970       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
10971     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
10972     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
10973   }
10974   // Not a build vector of (possibly fp_rounded) loads.
10975   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
10976     return SDValue();
10977
10978   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
10979     // If any inputs are fp_round(extload), they all must be.
10980     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
10981       return SDValue();
10982
10983     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
10984       N->getOperand(i);
10985     if (NextInput.getOpcode() != ISD::LOAD)
10986       return SDValue();
10987
10988     SDValue PreviousInput =
10989       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
10990     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
10991     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
10992
10993     // If any inputs are fp_round(extload), they all must be.
10994     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
10995       return SDValue();
10996
10997     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
10998       InputsAreConsecutiveLoads = false;
10999     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11000       InputsAreReverseConsecutive = false;
11001
11002     // Exit early if the loads are neither consecutive nor reverse consecutive.
11003     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11004       return SDValue();
11005   }
11006
11007   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11008          "The loads cannot be both consecutive and reverse consecutive.");
11009
11010   SDValue FirstLoadOp =
11011     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11012   SDValue LastLoadOp =
11013     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11014                        N->getOperand(N->getNumOperands()-1);
11015
11016   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11017   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11018   if (InputsAreConsecutiveLoads) {
11019     assert(LD1 && "Input needs to be a LoadSDNode.");
11020     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11021                        LD1->getBasePtr(), LD1->getPointerInfo(),
11022                        LD1->getAlignment());
11023   }
11024   if (InputsAreReverseConsecutive) {
11025     assert(LDL && "Input needs to be a LoadSDNode.");
11026     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11027                                LDL->getBasePtr(), LDL->getPointerInfo(),
11028                                LDL->getAlignment());
11029     SmallVector<int, 16> Ops;
11030     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11031       Ops.push_back(i);
11032
11033     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11034                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11035   }
11036   return SDValue();
11037 }
11038
11039 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11040                                                  DAGCombinerInfo &DCI) const {
11041   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11042          "Should be called with a BUILD_VECTOR node");
11043
11044   SelectionDAG &DAG = DCI.DAG;
11045   SDLoc dl(N);
11046
11047   if (!Subtarget.hasVSX())
11048     return SDValue();
11049
11050   // The target independent DAG combiner will leave a build_vector of
11051   // float-to-int conversions intact. We can generate MUCH better code for
11052   // a float-to-int conversion of a vector of floats.
11053   SDValue FirstInput = N->getOperand(0);
11054   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11055     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11056     if (Reduced)
11057       return Reduced;
11058   }
11059
11060   // If we're building a vector out of consecutive loads, just load that
11061   // vector type.
11062   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11063   if (Reduced)
11064     return Reduced;
11065
11066   if (N->getValueType(0) != MVT::v2f64)
11067     return SDValue();
11068
11069   // Looking for:
11070   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11071   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11072       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11073     return SDValue();
11074   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11075       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11076     return SDValue();
11077   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11078     return SDValue();
11079
11080   SDValue Ext1 = FirstInput.getOperand(0);
11081   SDValue Ext2 = N->getOperand(1).getOperand(0);
11082   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11083      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11084     return SDValue();
11085
11086   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11087   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11088   if (!Ext1Op || !Ext2Op)
11089     return SDValue();
11090   if (Ext1.getValueType() != MVT::i32 ||
11091       Ext2.getValueType() != MVT::i32)
11092   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11093     return SDValue();
11094
11095   int FirstElem = Ext1Op->getZExtValue();
11096   int SecondElem = Ext2Op->getZExtValue();
11097   int SubvecIdx;
11098   if (FirstElem == 0 && SecondElem == 1)
11099     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11100   else if (FirstElem == 2 && SecondElem == 3)
11101     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11102   else
11103     return SDValue();
11104
11105   SDValue SrcVec = Ext1.getOperand(0);
11106   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11107     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11108   return DAG.getNode(NodeType, dl, MVT::v2f64,
11109                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11110 }
11111
11112 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11113                                               DAGCombinerInfo &DCI) const {
11114   assert((N->getOpcode() == ISD::SINT_TO_FP ||
11115           N->getOpcode() == ISD::UINT_TO_FP) &&
11116          "Need an int -> FP conversion node here");
11117
11118   if (useSoftFloat() || !Subtarget.has64BitSupport())
11119     return SDValue();
11120
11121   SelectionDAG &DAG = DCI.DAG;
11122   SDLoc dl(N);
11123   SDValue Op(N, 0);
11124
11125   SDValue FirstOperand(Op.getOperand(0));
11126   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11127     (FirstOperand.getValueType() == MVT::i8 ||
11128      FirstOperand.getValueType() == MVT::i16);
11129   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11130     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11131     bool DstDouble = Op.getValueType() == MVT::f64;
11132     unsigned ConvOp = Signed ?
11133       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
11134       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11135     SDValue WidthConst =
11136       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11137                             dl, false);
11138     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11139     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11140     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11141                                          DAG.getVTList(MVT::f64, MVT::Other),
11142                                          Ops, MVT::i8, LDN->getMemOperand());
11143
11144     // For signed conversion, we need to sign-extend the value in the VSR
11145     if (Signed) {
11146       SDValue ExtOps[] = { Ld, WidthConst };
11147       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11148       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11149     } else
11150       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11151   }
11152
11153   // Don't handle ppc_fp128 here or i1 conversions.
11154   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11155     return SDValue();
11156   if (Op.getOperand(0).getValueType() == MVT::i1)
11157     return SDValue();
11158
11159   // For i32 intermediate values, unfortunately, the conversion functions
11160   // leave the upper 32 bits of the value are undefined. Within the set of
11161   // scalar instructions, we have no method for zero- or sign-extending the
11162   // value. Thus, we cannot handle i32 intermediate values here.
11163   if (Op.getOperand(0).getValueType() == MVT::i32)
11164     return SDValue();
11165
11166   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11167          "UINT_TO_FP is supported only with FPCVT");
11168
11169   // If we have FCFIDS, then use it when converting to single-precision.
11170   // Otherwise, convert to double-precision and then round.
11171   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11172                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11173                                                             : PPCISD::FCFIDS)
11174                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11175                                                             : PPCISD::FCFID);
11176   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11177                   ? MVT::f32
11178                   : MVT::f64;
11179
11180   // If we're converting from a float, to an int, and back to a float again,
11181   // then we don't need the store/load pair at all.
11182   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11183        Subtarget.hasFPCVT()) ||
11184       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11185     SDValue Src = Op.getOperand(0).getOperand(0);
11186     if (Src.getValueType() == MVT::f32) {
11187       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11188       DCI.AddToWorklist(Src.getNode());
11189     } else if (Src.getValueType() != MVT::f64) {
11190       // Make sure that we don't pick up a ppc_fp128 source value.
11191       return SDValue();
11192     }
11193
11194     unsigned FCTOp =
11195       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11196                                                         PPCISD::FCTIDUZ;
11197
11198     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11199     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11200
11201     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11202       FP = DAG.getNode(ISD::FP_ROUND, dl,
11203                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11204       DCI.AddToWorklist(FP.getNode());
11205     }
11206
11207     return FP;
11208   }
11209
11210   return SDValue();
11211 }
11212
11213 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11214 // builtins) into loads with swaps.
11215 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11216                                               DAGCombinerInfo &DCI) const {
11217   SelectionDAG &DAG = DCI.DAG;
11218   SDLoc dl(N);
11219   SDValue Chain;
11220   SDValue Base;
11221   MachineMemOperand *MMO;
11222
11223   switch (N->getOpcode()) {
11224   default:
11225     llvm_unreachable("Unexpected opcode for little endian VSX load");
11226   case ISD::LOAD: {
11227     LoadSDNode *LD = cast<LoadSDNode>(N);
11228     Chain = LD->getChain();
11229     Base = LD->getBasePtr();
11230     MMO = LD->getMemOperand();
11231     // If the MMO suggests this isn't a load of a full vector, leave
11232     // things alone.  For a built-in, we have to make the change for
11233     // correctness, so if there is a size problem that will be a bug.
11234     if (MMO->getSize() < 16)
11235       return SDValue();
11236     break;
11237   }
11238   case ISD::INTRINSIC_W_CHAIN: {
11239     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11240     Chain = Intrin->getChain();
11241     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11242     // us what we want. Get operand 2 instead.
11243     Base = Intrin->getOperand(2);
11244     MMO = Intrin->getMemOperand();
11245     break;
11246   }
11247   }
11248
11249   MVT VecTy = N->getValueType(0).getSimpleVT();
11250
11251   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11252   // aligned and the type is a vector with elements up to 4 bytes
11253   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11254       && VecTy.getScalarSizeInBits() <= 32 ) {
11255     return SDValue();
11256   }
11257
11258   SDValue LoadOps[] = { Chain, Base };
11259   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11260                                          DAG.getVTList(MVT::v2f64, MVT::Other),
11261                                          LoadOps, MVT::v2f64, MMO);
11262
11263   DCI.AddToWorklist(Load.getNode());
11264   Chain = Load.getValue(1);
11265   SDValue Swap = DAG.getNode(
11266       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11267   DCI.AddToWorklist(Swap.getNode());
11268
11269   // Add a bitcast if the resulting load type doesn't match v2f64.
11270   if (VecTy != MVT::v2f64) {
11271     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11272     DCI.AddToWorklist(N.getNode());
11273     // Package {bitcast value, swap's chain} to match Load's shape.
11274     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11275                        N, Swap.getValue(1));
11276   }
11277
11278   return Swap;
11279 }
11280
11281 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11282 // builtins) into stores with swaps.
11283 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11284                                                DAGCombinerInfo &DCI) const {
11285   SelectionDAG &DAG = DCI.DAG;
11286   SDLoc dl(N);
11287   SDValue Chain;
11288   SDValue Base;
11289   unsigned SrcOpnd;
11290   MachineMemOperand *MMO;
11291
11292   switch (N->getOpcode()) {
11293   default:
11294     llvm_unreachable("Unexpected opcode for little endian VSX store");
11295   case ISD::STORE: {
11296     StoreSDNode *ST = cast<StoreSDNode>(N);
11297     Chain = ST->getChain();
11298     Base = ST->getBasePtr();
11299     MMO = ST->getMemOperand();
11300     SrcOpnd = 1;
11301     // If the MMO suggests this isn't a store of a full vector, leave
11302     // things alone.  For a built-in, we have to make the change for
11303     // correctness, so if there is a size problem that will be a bug.
11304     if (MMO->getSize() < 16)
11305       return SDValue();
11306     break;
11307   }
11308   case ISD::INTRINSIC_VOID: {
11309     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11310     Chain = Intrin->getChain();
11311     // Intrin->getBasePtr() oddly does not get what we want.
11312     Base = Intrin->getOperand(3);
11313     MMO = Intrin->getMemOperand();
11314     SrcOpnd = 2;
11315     break;
11316   }
11317   }
11318
11319   SDValue Src = N->getOperand(SrcOpnd);
11320   MVT VecTy = Src.getValueType().getSimpleVT();
11321
11322   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
11323   // aligned and the type is a vector with elements up to 4 bytes
11324   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11325       && VecTy.getScalarSizeInBits() <= 32 ) {
11326     return SDValue();
11327   }
11328
11329   // All stores are done as v2f64 and possible bit cast.
11330   if (VecTy != MVT::v2f64) {
11331     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11332     DCI.AddToWorklist(Src.getNode());
11333   }
11334
11335   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11336                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11337   DCI.AddToWorklist(Swap.getNode());
11338   Chain = Swap.getValue(1);
11339   SDValue StoreOps[] = { Chain, Swap, Base };
11340   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11341                                           DAG.getVTList(MVT::Other),
11342                                           StoreOps, VecTy, MMO);
11343   DCI.AddToWorklist(Store.getNode());
11344   return Store;
11345 }
11346
11347 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11348                                              DAGCombinerInfo &DCI) const {
11349   SelectionDAG &DAG = DCI.DAG;
11350   SDLoc dl(N);
11351   switch (N->getOpcode()) {
11352   default: break;
11353   case ISD::SHL:
11354     return combineSHL(N, DCI);
11355   case ISD::SRA:
11356     return combineSRA(N, DCI);
11357   case ISD::SRL:
11358     return combineSRL(N, DCI);
11359   case PPCISD::SHL:
11360     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11361         return N->getOperand(0);
11362     break;
11363   case PPCISD::SRL:
11364     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11365         return N->getOperand(0);
11366     break;
11367   case PPCISD::SRA:
11368     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11369       if (C->isNullValue() ||   //  0 >>s V -> 0.
11370           C->isAllOnesValue())    // -1 >>s V -> -1.
11371         return N->getOperand(0);
11372     }
11373     break;
11374   case ISD::SIGN_EXTEND:
11375   case ISD::ZERO_EXTEND:
11376   case ISD::ANY_EXTEND:
11377     return DAGCombineExtBoolTrunc(N, DCI);
11378   case ISD::TRUNCATE:
11379   case ISD::SETCC:
11380   case ISD::SELECT_CC:
11381     return DAGCombineTruncBoolExt(N, DCI);
11382   case ISD::SINT_TO_FP:
11383   case ISD::UINT_TO_FP:
11384     return combineFPToIntToFP(N, DCI);
11385   case ISD::STORE: {
11386     EVT Op1VT = N->getOperand(1).getValueType();
11387     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11388       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11389
11390     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11391     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11392         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11393         ValidTypeForStoreFltAsInt &&
11394         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11395       SDValue Val = N->getOperand(1).getOperand(0);
11396       if (Val.getValueType() == MVT::f32) {
11397         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11398         DCI.AddToWorklist(Val.getNode());
11399       }
11400       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11401       DCI.AddToWorklist(Val.getNode());
11402
11403       if (Op1VT == MVT::i32) {
11404         SDValue Ops[] = {
11405           N->getOperand(0), Val, N->getOperand(2),
11406           DAG.getValueType(N->getOperand(1).getValueType())
11407         };
11408
11409         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11410                 DAG.getVTList(MVT::Other), Ops,
11411                 cast<StoreSDNode>(N)->getMemoryVT(),
11412                 cast<StoreSDNode>(N)->getMemOperand());
11413       } else {
11414         unsigned WidthInBytes =
11415           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11416         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11417
11418         SDValue Ops[] = {
11419           N->getOperand(0), Val, N->getOperand(2), WidthConst,
11420           DAG.getValueType(N->getOperand(1).getValueType())
11421         };
11422         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11423                                       DAG.getVTList(MVT::Other), Ops,
11424                                       cast<StoreSDNode>(N)->getMemoryVT(),
11425                                       cast<StoreSDNode>(N)->getMemOperand());
11426       }
11427
11428       DCI.AddToWorklist(Val.getNode());
11429       return Val;
11430     }
11431
11432     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11433     if (cast<StoreSDNode>(N)->isUnindexed() &&
11434         N->getOperand(1).getOpcode() == ISD::BSWAP &&
11435         N->getOperand(1).getNode()->hasOneUse() &&
11436         (N->getOperand(1).getValueType() == MVT::i32 ||
11437          N->getOperand(1).getValueType() == MVT::i16 ||
11438          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11439           N->getOperand(1).getValueType() == MVT::i64))) {
11440       SDValue BSwapOp = N->getOperand(1).getOperand(0);
11441       // Do an any-extend to 32-bits if this is a half-word input.
11442       if (BSwapOp.getValueType() == MVT::i16)
11443         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11444
11445       // If the type of BSWAP operand is wider than stored memory width
11446       // it need to be shifted to the right side before STBRX.
11447       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11448       if (Op1VT.bitsGT(mVT)) {
11449         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11450         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11451                               DAG.getConstant(Shift, dl, MVT::i32));
11452         // Need to truncate if this is a bswap of i64 stored as i32/i16.
11453         if (Op1VT == MVT::i64)
11454           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11455       }
11456
11457       SDValue Ops[] = {
11458         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11459       };
11460       return
11461         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11462                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11463                                 cast<StoreSDNode>(N)->getMemOperand());
11464     }
11465
11466     // For little endian, VSX stores require generating xxswapd/lxvd2x.
11467     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11468     EVT VT = N->getOperand(1).getValueType();
11469     if (VT.isSimple()) {
11470       MVT StoreVT = VT.getSimpleVT();
11471       if (Subtarget.needsSwapsForVSXMemOps() &&
11472           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11473            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11474         return expandVSXStoreForLE(N, DCI);
11475     }
11476     break;
11477   }
11478   case ISD::LOAD: {
11479     LoadSDNode *LD = cast<LoadSDNode>(N);
11480     EVT VT = LD->getValueType(0);
11481
11482     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11483     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11484     if (VT.isSimple()) {
11485       MVT LoadVT = VT.getSimpleVT();
11486       if (Subtarget.needsSwapsForVSXMemOps() &&
11487           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11488            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11489         return expandVSXLoadForLE(N, DCI);
11490     }
11491
11492     // We sometimes end up with a 64-bit integer load, from which we extract
11493     // two single-precision floating-point numbers. This happens with
11494     // std::complex<float>, and other similar structures, because of the way we
11495     // canonicalize structure copies. However, if we lack direct moves,
11496     // then the final bitcasts from the extracted integer values to the
11497     // floating-point numbers turn into store/load pairs. Even with direct moves,
11498     // just loading the two floating-point numbers is likely better.
11499     auto ReplaceTwoFloatLoad = [&]() {
11500       if (VT != MVT::i64)
11501         return false;
11502
11503       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11504           LD->isVolatile())
11505         return false;
11506
11507       //  We're looking for a sequence like this:
11508       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11509       //      t16: i64 = srl t13, Constant:i32<32>
11510       //    t17: i32 = truncate t16
11511       //  t18: f32 = bitcast t17
11512       //    t19: i32 = truncate t13
11513       //  t20: f32 = bitcast t19
11514
11515       if (!LD->hasNUsesOfValue(2, 0))
11516         return false;
11517
11518       auto UI = LD->use_begin();
11519       while (UI.getUse().getResNo() != 0) ++UI;
11520       SDNode *Trunc = *UI++;
11521       while (UI.getUse().getResNo() != 0) ++UI;
11522       SDNode *RightShift = *UI;
11523       if (Trunc->getOpcode() != ISD::TRUNCATE)
11524         std::swap(Trunc, RightShift);
11525
11526       if (Trunc->getOpcode() != ISD::TRUNCATE ||
11527           Trunc->getValueType(0) != MVT::i32 ||
11528           !Trunc->hasOneUse())
11529         return false;
11530       if (RightShift->getOpcode() != ISD::SRL ||
11531           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11532           RightShift->getConstantOperandVal(1) != 32 ||
11533           !RightShift->hasOneUse())
11534         return false;
11535
11536       SDNode *Trunc2 = *RightShift->use_begin();
11537       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11538           Trunc2->getValueType(0) != MVT::i32 ||
11539           !Trunc2->hasOneUse())
11540         return false;
11541
11542       SDNode *Bitcast = *Trunc->use_begin();
11543       SDNode *Bitcast2 = *Trunc2->use_begin();
11544
11545       if (Bitcast->getOpcode() != ISD::BITCAST ||
11546           Bitcast->getValueType(0) != MVT::f32)
11547         return false;
11548       if (Bitcast2->getOpcode() != ISD::BITCAST ||
11549           Bitcast2->getValueType(0) != MVT::f32)
11550         return false;
11551
11552       if (Subtarget.isLittleEndian())
11553         std::swap(Bitcast, Bitcast2);
11554
11555       // Bitcast has the second float (in memory-layout order) and Bitcast2
11556       // has the first one.
11557
11558       SDValue BasePtr = LD->getBasePtr();
11559       if (LD->isIndexed()) {
11560         assert(LD->getAddressingMode() == ISD::PRE_INC &&
11561                "Non-pre-inc AM on PPC?");
11562         BasePtr =
11563           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11564                       LD->getOffset());
11565       }
11566
11567       auto MMOFlags =
11568           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11569       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11570                                       LD->getPointerInfo(), LD->getAlignment(),
11571                                       MMOFlags, LD->getAAInfo());
11572       SDValue AddPtr =
11573         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11574                     BasePtr, DAG.getIntPtrConstant(4, dl));
11575       SDValue FloatLoad2 = DAG.getLoad(
11576           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11577           LD->getPointerInfo().getWithOffset(4),
11578           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11579
11580       if (LD->isIndexed()) {
11581         // Note that DAGCombine should re-form any pre-increment load(s) from
11582         // what is produced here if that makes sense.
11583         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11584       }
11585
11586       DCI.CombineTo(Bitcast2, FloatLoad);
11587       DCI.CombineTo(Bitcast, FloatLoad2);
11588
11589       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11590                                     SDValue(FloatLoad2.getNode(), 1));
11591       return true;
11592     };
11593
11594     if (ReplaceTwoFloatLoad())
11595       return SDValue(N, 0);
11596
11597     EVT MemVT = LD->getMemoryVT();
11598     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11599     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11600     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11601     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11602     if (LD->isUnindexed() && VT.isVector() &&
11603         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11604           // P8 and later hardware should just use LOAD.
11605           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11606                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11607          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11608           LD->getAlignment() >= ScalarABIAlignment)) &&
11609         LD->getAlignment() < ABIAlignment) {
11610       // This is a type-legal unaligned Altivec or QPX load.
11611       SDValue Chain = LD->getChain();
11612       SDValue Ptr = LD->getBasePtr();
11613       bool isLittleEndian = Subtarget.isLittleEndian();
11614
11615       // This implements the loading of unaligned vectors as described in
11616       // the venerable Apple Velocity Engine overview. Specifically:
11617       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11618       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11619       //
11620       // The general idea is to expand a sequence of one or more unaligned
11621       // loads into an alignment-based permutation-control instruction (lvsl
11622       // or lvsr), a series of regular vector loads (which always truncate
11623       // their input address to an aligned address), and a series of
11624       // permutations.  The results of these permutations are the requested
11625       // loaded values.  The trick is that the last "extra" load is not taken
11626       // from the address you might suspect (sizeof(vector) bytes after the
11627       // last requested load), but rather sizeof(vector) - 1 bytes after the
11628       // last requested vector. The point of this is to avoid a page fault if
11629       // the base address happened to be aligned. This works because if the
11630       // base address is aligned, then adding less than a full vector length
11631       // will cause the last vector in the sequence to be (re)loaded.
11632       // Otherwise, the next vector will be fetched as you might suspect was
11633       // necessary.
11634
11635       // We might be able to reuse the permutation generation from
11636       // a different base address offset from this one by an aligned amount.
11637       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11638       // optimization later.
11639       Intrinsic::ID Intr, IntrLD, IntrPerm;
11640       MVT PermCntlTy, PermTy, LDTy;
11641       if (Subtarget.hasAltivec()) {
11642         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
11643                                  Intrinsic::ppc_altivec_lvsl;
11644         IntrLD = Intrinsic::ppc_altivec_lvx;
11645         IntrPerm = Intrinsic::ppc_altivec_vperm;
11646         PermCntlTy = MVT::v16i8;
11647         PermTy = MVT::v4i32;
11648         LDTy = MVT::v4i32;
11649       } else {
11650         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11651                                        Intrinsic::ppc_qpx_qvlpcls;
11652         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11653                                        Intrinsic::ppc_qpx_qvlfs;
11654         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11655         PermCntlTy = MVT::v4f64;
11656         PermTy = MVT::v4f64;
11657         LDTy = MemVT.getSimpleVT();
11658       }
11659
11660       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11661
11662       // Create the new MMO for the new base load. It is like the original MMO,
11663       // but represents an area in memory almost twice the vector size centered
11664       // on the original address. If the address is unaligned, we might start
11665       // reading up to (sizeof(vector)-1) bytes below the address of the
11666       // original unaligned load.
11667       MachineFunction &MF = DAG.getMachineFunction();
11668       MachineMemOperand *BaseMMO =
11669         MF.getMachineMemOperand(LD->getMemOperand(),
11670                                 -(long)MemVT.getStoreSize()+1,
11671                                 2*MemVT.getStoreSize()-1);
11672
11673       // Create the new base load.
11674       SDValue LDXIntID =
11675           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11676       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11677       SDValue BaseLoad =
11678         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11679                                 DAG.getVTList(PermTy, MVT::Other),
11680                                 BaseLoadOps, LDTy, BaseMMO);
11681
11682       // Note that the value of IncOffset (which is provided to the next
11683       // load's pointer info offset value, and thus used to calculate the
11684       // alignment), and the value of IncValue (which is actually used to
11685       // increment the pointer value) are different! This is because we
11686       // require the next load to appear to be aligned, even though it
11687       // is actually offset from the base pointer by a lesser amount.
11688       int IncOffset = VT.getSizeInBits() / 8;
11689       int IncValue = IncOffset;
11690
11691       // Walk (both up and down) the chain looking for another load at the real
11692       // (aligned) offset (the alignment of the other load does not matter in
11693       // this case). If found, then do not use the offset reduction trick, as
11694       // that will prevent the loads from being later combined (as they would
11695       // otherwise be duplicates).
11696       if (!findConsecutiveLoad(LD, DAG))
11697         --IncValue;
11698
11699       SDValue Increment =
11700           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11701       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11702
11703       MachineMemOperand *ExtraMMO =
11704         MF.getMachineMemOperand(LD->getMemOperand(),
11705                                 1, 2*MemVT.getStoreSize()-1);
11706       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11707       SDValue ExtraLoad =
11708         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11709                                 DAG.getVTList(PermTy, MVT::Other),
11710                                 ExtraLoadOps, LDTy, ExtraMMO);
11711
11712       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11713         BaseLoad.getValue(1), ExtraLoad.getValue(1));
11714
11715       // Because vperm has a big-endian bias, we must reverse the order
11716       // of the input vectors and complement the permute control vector
11717       // when generating little endian code.  We have already handled the
11718       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11719       // and ExtraLoad here.
11720       SDValue Perm;
11721       if (isLittleEndian)
11722         Perm = BuildIntrinsicOp(IntrPerm,
11723                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11724       else
11725         Perm = BuildIntrinsicOp(IntrPerm,
11726                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11727
11728       if (VT != PermTy)
11729         Perm = Subtarget.hasAltivec() ?
11730                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11731                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11732                                DAG.getTargetConstant(1, dl, MVT::i64));
11733                                // second argument is 1 because this rounding
11734                                // is always exact.
11735
11736       // The output of the permutation is our loaded result, the TokenFactor is
11737       // our new chain.
11738       DCI.CombineTo(N, Perm, TF);
11739       return SDValue(N, 0);
11740     }
11741     }
11742     break;
11743     case ISD::INTRINSIC_WO_CHAIN: {
11744       bool isLittleEndian = Subtarget.isLittleEndian();
11745       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11746       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11747                                            : Intrinsic::ppc_altivec_lvsl);
11748       if ((IID == Intr ||
11749            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11750            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11751         N->getOperand(1)->getOpcode() == ISD::ADD) {
11752         SDValue Add = N->getOperand(1);
11753
11754         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11755                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11756
11757         if (DAG.MaskedValueIsZero(Add->getOperand(1),
11758                                   APInt::getAllOnesValue(Bits /* alignment */)
11759                                       .zext(Add.getScalarValueSizeInBits()))) {
11760           SDNode *BasePtr = Add->getOperand(0).getNode();
11761           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11762                                     UE = BasePtr->use_end();
11763                UI != UE; ++UI) {
11764             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11765                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11766               // We've found another LVSL/LVSR, and this address is an aligned
11767               // multiple of that one. The results will be the same, so use the
11768               // one we've just found instead.
11769
11770               return SDValue(*UI, 0);
11771             }
11772           }
11773         }
11774
11775         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11776           SDNode *BasePtr = Add->getOperand(0).getNode();
11777           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11778                UE = BasePtr->use_end(); UI != UE; ++UI) {
11779             if (UI->getOpcode() == ISD::ADD &&
11780                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11781                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11782                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11783                 (1ULL << Bits) == 0) {
11784               SDNode *OtherAdd = *UI;
11785               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11786                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11787                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11788                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11789                   return SDValue(*VI, 0);
11790                 }
11791               }
11792             }
11793           }
11794         }
11795       }
11796     }
11797
11798     break;
11799   case ISD::INTRINSIC_W_CHAIN:
11800     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11801     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11802     if (Subtarget.needsSwapsForVSXMemOps()) {
11803       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11804       default:
11805         break;
11806       case Intrinsic::ppc_vsx_lxvw4x:
11807       case Intrinsic::ppc_vsx_lxvd2x:
11808         return expandVSXLoadForLE(N, DCI);
11809       }
11810     }
11811     break;
11812   case ISD::INTRINSIC_VOID:
11813     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11814     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11815     if (Subtarget.needsSwapsForVSXMemOps()) {
11816       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11817       default:
11818         break;
11819       case Intrinsic::ppc_vsx_stxvw4x:
11820       case Intrinsic::ppc_vsx_stxvd2x:
11821         return expandVSXStoreForLE(N, DCI);
11822       }
11823     }
11824     break;
11825   case ISD::BSWAP:
11826     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11827     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11828         N->getOperand(0).hasOneUse() &&
11829         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11830          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11831           N->getValueType(0) == MVT::i64))) {
11832       SDValue Load = N->getOperand(0);
11833       LoadSDNode *LD = cast<LoadSDNode>(Load);
11834       // Create the byte-swapping load.
11835       SDValue Ops[] = {
11836         LD->getChain(),    // Chain
11837         LD->getBasePtr(),  // Ptr
11838         DAG.getValueType(N->getValueType(0)) // VT
11839       };
11840       SDValue BSLoad =
11841         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11842                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11843                                               MVT::i64 : MVT::i32, MVT::Other),
11844                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11845
11846       // If this is an i16 load, insert the truncate.
11847       SDValue ResVal = BSLoad;
11848       if (N->getValueType(0) == MVT::i16)
11849         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11850
11851       // First, combine the bswap away.  This makes the value produced by the
11852       // load dead.
11853       DCI.CombineTo(N, ResVal);
11854
11855       // Next, combine the load away, we give it a bogus result value but a real
11856       // chain result.  The result value is dead because the bswap is dead.
11857       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11858
11859       // Return N so it doesn't get rechecked!
11860       return SDValue(N, 0);
11861     }
11862     break;
11863   case PPCISD::VCMP:
11864     // If a VCMPo node already exists with exactly the same operands as this
11865     // node, use its result instead of this node (VCMPo computes both a CR6 and
11866     // a normal output).
11867     //
11868     if (!N->getOperand(0).hasOneUse() &&
11869         !N->getOperand(1).hasOneUse() &&
11870         !N->getOperand(2).hasOneUse()) {
11871
11872       // Scan all of the users of the LHS, looking for VCMPo's that match.
11873       SDNode *VCMPoNode = nullptr;
11874
11875       SDNode *LHSN = N->getOperand(0).getNode();
11876       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11877            UI != E; ++UI)
11878         if (UI->getOpcode() == PPCISD::VCMPo &&
11879             UI->getOperand(1) == N->getOperand(1) &&
11880             UI->getOperand(2) == N->getOperand(2) &&
11881             UI->getOperand(0) == N->getOperand(0)) {
11882           VCMPoNode = *UI;
11883           break;
11884         }
11885
11886       // If there is no VCMPo node, or if the flag value has a single use, don't
11887       // transform this.
11888       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11889         break;
11890
11891       // Look at the (necessarily single) use of the flag value.  If it has a
11892       // chain, this transformation is more complex.  Note that multiple things
11893       // could use the value result, which we should ignore.
11894       SDNode *FlagUser = nullptr;
11895       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11896            FlagUser == nullptr; ++UI) {
11897         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11898         SDNode *User = *UI;
11899         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11900           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11901             FlagUser = User;
11902             break;
11903           }
11904         }
11905       }
11906
11907       // If the user is a MFOCRF instruction, we know this is safe.
11908       // Otherwise we give up for right now.
11909       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11910         return SDValue(VCMPoNode, 0);
11911     }
11912     break;
11913   case ISD::BRCOND: {
11914     SDValue Cond = N->getOperand(1);
11915     SDValue Target = N->getOperand(2);
11916
11917     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11918         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11919           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11920
11921       // We now need to make the intrinsic dead (it cannot be instruction
11922       // selected).
11923       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11924       assert(Cond.getNode()->hasOneUse() &&
11925              "Counter decrement has more than one use");
11926
11927       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11928                          N->getOperand(0), Target);
11929     }
11930   }
11931   break;
11932   case ISD::BR_CC: {
11933     // If this is a branch on an altivec predicate comparison, lower this so
11934     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11935     // lowering is done pre-legalize, because the legalizer lowers the predicate
11936     // compare down to code that is difficult to reassemble.
11937     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11938     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11939
11940     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11941     // value. If so, pass-through the AND to get to the intrinsic.
11942     if (LHS.getOpcode() == ISD::AND &&
11943         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11944         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11945           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11946         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11947         !isNullConstant(LHS.getOperand(1)))
11948       LHS = LHS.getOperand(0);
11949
11950     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11951         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11952           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11953         isa<ConstantSDNode>(RHS)) {
11954       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11955              "Counter decrement comparison is not EQ or NE");
11956
11957       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11958       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11959                     (CC == ISD::SETNE && !Val);
11960
11961       // We now need to make the intrinsic dead (it cannot be instruction
11962       // selected).
11963       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11964       assert(LHS.getNode()->hasOneUse() &&
11965              "Counter decrement has more than one use");
11966
11967       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11968                          N->getOperand(0), N->getOperand(4));
11969     }
11970
11971     int CompareOpc;
11972     bool isDot;
11973
11974     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11975         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11976         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11977       assert(isDot && "Can't compare against a vector result!");
11978
11979       // If this is a comparison against something other than 0/1, then we know
11980       // that the condition is never/always true.
11981       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11982       if (Val != 0 && Val != 1) {
11983         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11984           return N->getOperand(0);
11985         // Always !=, turn it into an unconditional branch.
11986         return DAG.getNode(ISD::BR, dl, MVT::Other,
11987                            N->getOperand(0), N->getOperand(4));
11988       }
11989
11990       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11991
11992       // Create the PPCISD altivec 'dot' comparison node.
11993       SDValue Ops[] = {
11994         LHS.getOperand(2),  // LHS of compare
11995         LHS.getOperand(3),  // RHS of compare
11996         DAG.getConstant(CompareOpc, dl, MVT::i32)
11997       };
11998       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11999       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12000
12001       // Unpack the result based on how the target uses it.
12002       PPC::Predicate CompOpc;
12003       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12004       default:  // Can't happen, don't crash on invalid number though.
12005       case 0:   // Branch on the value of the EQ bit of CR6.
12006         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12007         break;
12008       case 1:   // Branch on the inverted value of the EQ bit of CR6.
12009         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12010         break;
12011       case 2:   // Branch on the value of the LT bit of CR6.
12012         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12013         break;
12014       case 3:   // Branch on the inverted value of the LT bit of CR6.
12015         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12016         break;
12017       }
12018
12019       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12020                          DAG.getConstant(CompOpc, dl, MVT::i32),
12021                          DAG.getRegister(PPC::CR6, MVT::i32),
12022                          N->getOperand(4), CompNode.getValue(1));
12023     }
12024     break;
12025   }
12026   case ISD::BUILD_VECTOR:
12027     return DAGCombineBuildVector(N, DCI);
12028   }
12029
12030   return SDValue();
12031 }
12032
12033 SDValue
12034 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12035                                   SelectionDAG &DAG,
12036                                   std::vector<SDNode *> *Created) const {
12037   // fold (sdiv X, pow2)
12038   EVT VT = N->getValueType(0);
12039   if (VT == MVT::i64 && !Subtarget.isPPC64())
12040     return SDValue();
12041   if ((VT != MVT::i32 && VT != MVT::i64) ||
12042       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12043     return SDValue();
12044
12045   SDLoc DL(N);
12046   SDValue N0 = N->getOperand(0);
12047
12048   bool IsNegPow2 = (-Divisor).isPowerOf2();
12049   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12050   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12051
12052   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12053   if (Created)
12054     Created->push_back(Op.getNode());
12055
12056   if (IsNegPow2) {
12057     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12058     if (Created)
12059       Created->push_back(Op.getNode());
12060   }
12061
12062   return Op;
12063 }
12064
12065 //===----------------------------------------------------------------------===//
12066 // Inline Assembly Support
12067 //===----------------------------------------------------------------------===//
12068
12069 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12070                                                       KnownBits &Known,
12071                                                       const APInt &DemandedElts,
12072                                                       const SelectionDAG &DAG,
12073                                                       unsigned Depth) const {
12074   Known.resetAll();
12075   switch (Op.getOpcode()) {
12076   default: break;
12077   case PPCISD::LBRX: {
12078     // lhbrx is known to have the top bits cleared out.
12079     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12080       Known.Zero = 0xFFFF0000;
12081     break;
12082   }
12083   case ISD::INTRINSIC_WO_CHAIN: {
12084     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12085     default: break;
12086     case Intrinsic::ppc_altivec_vcmpbfp_p:
12087     case Intrinsic::ppc_altivec_vcmpeqfp_p:
12088     case Intrinsic::ppc_altivec_vcmpequb_p:
12089     case Intrinsic::ppc_altivec_vcmpequh_p:
12090     case Intrinsic::ppc_altivec_vcmpequw_p:
12091     case Intrinsic::ppc_altivec_vcmpequd_p:
12092     case Intrinsic::ppc_altivec_vcmpgefp_p:
12093     case Intrinsic::ppc_altivec_vcmpgtfp_p:
12094     case Intrinsic::ppc_altivec_vcmpgtsb_p:
12095     case Intrinsic::ppc_altivec_vcmpgtsh_p:
12096     case Intrinsic::ppc_altivec_vcmpgtsw_p:
12097     case Intrinsic::ppc_altivec_vcmpgtsd_p:
12098     case Intrinsic::ppc_altivec_vcmpgtub_p:
12099     case Intrinsic::ppc_altivec_vcmpgtuh_p:
12100     case Intrinsic::ppc_altivec_vcmpgtuw_p:
12101     case Intrinsic::ppc_altivec_vcmpgtud_p:
12102       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
12103       break;
12104     }
12105   }
12106   }
12107 }
12108
12109 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12110   switch (Subtarget.getDarwinDirective()) {
12111   default: break;
12112   case PPC::DIR_970:
12113   case PPC::DIR_PWR4:
12114   case PPC::DIR_PWR5:
12115   case PPC::DIR_PWR5X:
12116   case PPC::DIR_PWR6:
12117   case PPC::DIR_PWR6X:
12118   case PPC::DIR_PWR7:
12119   case PPC::DIR_PWR8:
12120   case PPC::DIR_PWR9: {
12121     if (!ML)
12122       break;
12123
12124     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12125
12126     // For small loops (between 5 and 8 instructions), align to a 32-byte
12127     // boundary so that the entire loop fits in one instruction-cache line.
12128     uint64_t LoopSize = 0;
12129     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12130       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12131         LoopSize += TII->getInstSizeInBytes(*J);
12132         if (LoopSize > 32)
12133           break;
12134       }
12135
12136     if (LoopSize > 16 && LoopSize <= 32)
12137       return 5;
12138
12139     break;
12140   }
12141   }
12142
12143   return TargetLowering::getPrefLoopAlignment(ML);
12144 }
12145
12146 /// getConstraintType - Given a constraint, return the type of
12147 /// constraint it is for this target.
12148 PPCTargetLowering::ConstraintType
12149 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12150   if (Constraint.size() == 1) {
12151     switch (Constraint[0]) {
12152     default: break;
12153     case 'b':
12154     case 'r':
12155     case 'f':
12156     case 'd':
12157     case 'v':
12158     case 'y':
12159       return C_RegisterClass;
12160     case 'Z':
12161       // FIXME: While Z does indicate a memory constraint, it specifically
12162       // indicates an r+r address (used in conjunction with the 'y' modifier
12163       // in the replacement string). Currently, we're forcing the base
12164       // register to be r0 in the asm printer (which is interpreted as zero)
12165       // and forming the complete address in the second register. This is
12166       // suboptimal.
12167       return C_Memory;
12168     }
12169   } else if (Constraint == "wc") { // individual CR bits.
12170     return C_RegisterClass;
12171   } else if (Constraint == "wa" || Constraint == "wd" ||
12172              Constraint == "wf" || Constraint == "ws") {
12173     return C_RegisterClass; // VSX registers.
12174   }
12175   return TargetLowering::getConstraintType(Constraint);
12176 }
12177
12178 /// Examine constraint type and operand type and determine a weight value.
12179 /// This object must already have been set up with the operand type
12180 /// and the current alternative constraint selected.
12181 TargetLowering::ConstraintWeight
12182 PPCTargetLowering::getSingleConstraintMatchWeight(
12183     AsmOperandInfo &info, const char *constraint) const {
12184   ConstraintWeight weight = CW_Invalid;
12185   Value *CallOperandVal = info.CallOperandVal;
12186     // If we don't have a value, we can't do a match,
12187     // but allow it at the lowest weight.
12188   if (!CallOperandVal)
12189     return CW_Default;
12190   Type *type = CallOperandVal->getType();
12191
12192   // Look at the constraint type.
12193   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12194     return CW_Register; // an individual CR bit.
12195   else if ((StringRef(constraint) == "wa" ||
12196             StringRef(constraint) == "wd" ||
12197             StringRef(constraint) == "wf") &&
12198            type->isVectorTy())
12199     return CW_Register;
12200   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12201     return CW_Register;
12202
12203   switch (*constraint) {
12204   default:
12205     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12206     break;
12207   case 'b':
12208     if (type->isIntegerTy())
12209       weight = CW_Register;
12210     break;
12211   case 'f':
12212     if (type->isFloatTy())
12213       weight = CW_Register;
12214     break;
12215   case 'd':
12216     if (type->isDoubleTy())
12217       weight = CW_Register;
12218     break;
12219   case 'v':
12220     if (type->isVectorTy())
12221       weight = CW_Register;
12222     break;
12223   case 'y':
12224     weight = CW_Register;
12225     break;
12226   case 'Z':
12227     weight = CW_Memory;
12228     break;
12229   }
12230   return weight;
12231 }
12232
12233 std::pair<unsigned, const TargetRegisterClass *>
12234 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12235                                                 StringRef Constraint,
12236                                                 MVT VT) const {
12237   if (Constraint.size() == 1) {
12238     // GCC RS6000 Constraint Letters
12239     switch (Constraint[0]) {
12240     case 'b':   // R1-R31
12241       if (VT == MVT::i64 && Subtarget.isPPC64())
12242         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12243       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12244     case 'r':   // R0-R31
12245       if (VT == MVT::i64 && Subtarget.isPPC64())
12246         return std::make_pair(0U, &PPC::G8RCRegClass);
12247       return std::make_pair(0U, &PPC::GPRCRegClass);
12248     // 'd' and 'f' constraints are both defined to be "the floating point
12249     // registers", where one is for 32-bit and the other for 64-bit. We don't
12250     // really care overly much here so just give them all the same reg classes.
12251     case 'd':
12252     case 'f':
12253       if (VT == MVT::f32 || VT == MVT::i32)
12254         return std::make_pair(0U, &PPC::F4RCRegClass);
12255       if (VT == MVT::f64 || VT == MVT::i64)
12256         return std::make_pair(0U, &PPC::F8RCRegClass);
12257       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12258         return std::make_pair(0U, &PPC::QFRCRegClass);
12259       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12260         return std::make_pair(0U, &PPC::QSRCRegClass);
12261       break;
12262     case 'v':
12263       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12264         return std::make_pair(0U, &PPC::QFRCRegClass);
12265       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12266         return std::make_pair(0U, &PPC::QSRCRegClass);
12267       if (Subtarget.hasAltivec())
12268         return std::make_pair(0U, &PPC::VRRCRegClass);
12269     case 'y':   // crrc
12270       return std::make_pair(0U, &PPC::CRRCRegClass);
12271     }
12272   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12273     // An individual CR bit.
12274     return std::make_pair(0U, &PPC::CRBITRCRegClass);
12275   } else if ((Constraint == "wa" || Constraint == "wd" ||
12276              Constraint == "wf") && Subtarget.hasVSX()) {
12277     return std::make_pair(0U, &PPC::VSRCRegClass);
12278   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12279     if (VT == MVT::f32 && Subtarget.hasP8Vector())
12280       return std::make_pair(0U, &PPC::VSSRCRegClass);
12281     else
12282       return std::make_pair(0U, &PPC::VSFRCRegClass);
12283   }
12284
12285   std::pair<unsigned, const TargetRegisterClass *> R =
12286       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12287
12288   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12289   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12290   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12291   // register.
12292   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12293   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12294   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12295       PPC::GPRCRegClass.contains(R.first))
12296     return std::make_pair(TRI->getMatchingSuperReg(R.first,
12297                             PPC::sub_32, &PPC::G8RCRegClass),
12298                           &PPC::G8RCRegClass);
12299
12300   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12301   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12302     R.first = PPC::CR0;
12303     R.second = &PPC::CRRCRegClass;
12304   }
12305
12306   return R;
12307 }
12308
12309 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12310 /// vector.  If it is invalid, don't add anything to Ops.
12311 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12312                                                      std::string &Constraint,
12313                                                      std::vector<SDValue>&Ops,
12314                                                      SelectionDAG &DAG) const {
12315   SDValue Result;
12316
12317   // Only support length 1 constraints.
12318   if (Constraint.length() > 1) return;
12319
12320   char Letter = Constraint[0];
12321   switch (Letter) {
12322   default: break;
12323   case 'I':
12324   case 'J':
12325   case 'K':
12326   case 'L':
12327   case 'M':
12328   case 'N':
12329   case 'O':
12330   case 'P': {
12331     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12332     if (!CST) return; // Must be an immediate to match.
12333     SDLoc dl(Op);
12334     int64_t Value = CST->getSExtValue();
12335     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12336                          // numbers are printed as such.
12337     switch (Letter) {
12338     default: llvm_unreachable("Unknown constraint letter!");
12339     case 'I':  // "I" is a signed 16-bit constant.
12340       if (isInt<16>(Value))
12341         Result = DAG.getTargetConstant(Value, dl, TCVT);
12342       break;
12343     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
12344       if (isShiftedUInt<16, 16>(Value))
12345         Result = DAG.getTargetConstant(Value, dl, TCVT);
12346       break;
12347     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
12348       if (isShiftedInt<16, 16>(Value))
12349         Result = DAG.getTargetConstant(Value, dl, TCVT);
12350       break;
12351     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
12352       if (isUInt<16>(Value))
12353         Result = DAG.getTargetConstant(Value, dl, TCVT);
12354       break;
12355     case 'M':  // "M" is a constant that is greater than 31.
12356       if (Value > 31)
12357         Result = DAG.getTargetConstant(Value, dl, TCVT);
12358       break;
12359     case 'N':  // "N" is a positive constant that is an exact power of two.
12360       if (Value > 0 && isPowerOf2_64(Value))
12361         Result = DAG.getTargetConstant(Value, dl, TCVT);
12362       break;
12363     case 'O':  // "O" is the constant zero.
12364       if (Value == 0)
12365         Result = DAG.getTargetConstant(Value, dl, TCVT);
12366       break;
12367     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
12368       if (isInt<16>(-Value))
12369         Result = DAG.getTargetConstant(Value, dl, TCVT);
12370       break;
12371     }
12372     break;
12373   }
12374   }
12375
12376   if (Result.getNode()) {
12377     Ops.push_back(Result);
12378     return;
12379   }
12380
12381   // Handle standard constraint letters.
12382   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12383 }
12384
12385 // isLegalAddressingMode - Return true if the addressing mode represented
12386 // by AM is legal for this target, for a load/store of the specified type.
12387 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12388                                               const AddrMode &AM, Type *Ty,
12389                                               unsigned AS) const {
12390   // PPC does not allow r+i addressing modes for vectors!
12391   if (Ty->isVectorTy() && AM.BaseOffs != 0)
12392     return false;
12393
12394   // PPC allows a sign-extended 16-bit immediate field.
12395   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12396     return false;
12397
12398   // No global is ever allowed as a base.
12399   if (AM.BaseGV)
12400     return false;
12401
12402   // PPC only support r+r,
12403   switch (AM.Scale) {
12404   case 0:  // "r+i" or just "i", depending on HasBaseReg.
12405     break;
12406   case 1:
12407     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
12408       return false;
12409     // Otherwise we have r+r or r+i.
12410     break;
12411   case 2:
12412     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
12413       return false;
12414     // Allow 2*r as r+r.
12415     break;
12416   default:
12417     // No other scales are supported.
12418     return false;
12419   }
12420
12421   return true;
12422 }
12423
12424 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12425                                            SelectionDAG &DAG) const {
12426   MachineFunction &MF = DAG.getMachineFunction();
12427   MachineFrameInfo &MFI = MF.getFrameInfo();
12428   MFI.setReturnAddressIsTaken(true);
12429
12430   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12431     return SDValue();
12432
12433   SDLoc dl(Op);
12434   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12435
12436   // Make sure the function does not optimize away the store of the RA to
12437   // the stack.
12438   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12439   FuncInfo->setLRStoreRequired();
12440   bool isPPC64 = Subtarget.isPPC64();
12441   auto PtrVT = getPointerTy(MF.getDataLayout());
12442
12443   if (Depth > 0) {
12444     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12445     SDValue Offset =
12446         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12447                         isPPC64 ? MVT::i64 : MVT::i32);
12448     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12449                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12450                        MachinePointerInfo());
12451   }
12452
12453   // Just load the return address off the stack.
12454   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12455   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12456                      MachinePointerInfo());
12457 }
12458
12459 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12460                                           SelectionDAG &DAG) const {
12461   SDLoc dl(Op);
12462   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12463
12464   MachineFunction &MF = DAG.getMachineFunction();
12465   MachineFrameInfo &MFI = MF.getFrameInfo();
12466   MFI.setFrameAddressIsTaken(true);
12467
12468   EVT PtrVT = getPointerTy(MF.getDataLayout());
12469   bool isPPC64 = PtrVT == MVT::i64;
12470
12471   // Naked functions never have a frame pointer, and so we use r1. For all
12472   // other functions, this decision must be delayed until during PEI.
12473   unsigned FrameReg;
12474   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12475     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12476   else
12477     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12478
12479   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12480                                          PtrVT);
12481   while (Depth--)
12482     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12483                             FrameAddr, MachinePointerInfo());
12484   return FrameAddr;
12485 }
12486
12487 // FIXME? Maybe this could be a TableGen attribute on some registers and
12488 // this table could be generated automatically from RegInfo.
12489 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12490                                               SelectionDAG &DAG) const {
12491   bool isPPC64 = Subtarget.isPPC64();
12492   bool isDarwinABI = Subtarget.isDarwinABI();
12493
12494   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12495       (!isPPC64 && VT != MVT::i32))
12496     report_fatal_error("Invalid register global variable type");
12497
12498   bool is64Bit = isPPC64 && VT == MVT::i64;
12499   unsigned Reg = StringSwitch<unsigned>(RegName)
12500                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12501                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12502                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12503                                   (is64Bit ? PPC::X13 : PPC::R13))
12504                    .Default(0);
12505
12506   if (Reg)
12507     return Reg;
12508   report_fatal_error("Invalid register name global variable");
12509 }
12510
12511 bool
12512 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12513   // The PowerPC target isn't yet aware of offsets.
12514   return false;
12515 }
12516
12517 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12518                                            const CallInst &I,
12519                                            unsigned Intrinsic) const {
12520   switch (Intrinsic) {
12521   case Intrinsic::ppc_qpx_qvlfd:
12522   case Intrinsic::ppc_qpx_qvlfs:
12523   case Intrinsic::ppc_qpx_qvlfcd:
12524   case Intrinsic::ppc_qpx_qvlfcs:
12525   case Intrinsic::ppc_qpx_qvlfiwa:
12526   case Intrinsic::ppc_qpx_qvlfiwz:
12527   case Intrinsic::ppc_altivec_lvx:
12528   case Intrinsic::ppc_altivec_lvxl:
12529   case Intrinsic::ppc_altivec_lvebx:
12530   case Intrinsic::ppc_altivec_lvehx:
12531   case Intrinsic::ppc_altivec_lvewx:
12532   case Intrinsic::ppc_vsx_lxvd2x:
12533   case Intrinsic::ppc_vsx_lxvw4x: {
12534     EVT VT;
12535     switch (Intrinsic) {
12536     case Intrinsic::ppc_altivec_lvebx:
12537       VT = MVT::i8;
12538       break;
12539     case Intrinsic::ppc_altivec_lvehx:
12540       VT = MVT::i16;
12541       break;
12542     case Intrinsic::ppc_altivec_lvewx:
12543       VT = MVT::i32;
12544       break;
12545     case Intrinsic::ppc_vsx_lxvd2x:
12546       VT = MVT::v2f64;
12547       break;
12548     case Intrinsic::ppc_qpx_qvlfd:
12549       VT = MVT::v4f64;
12550       break;
12551     case Intrinsic::ppc_qpx_qvlfs:
12552       VT = MVT::v4f32;
12553       break;
12554     case Intrinsic::ppc_qpx_qvlfcd:
12555       VT = MVT::v2f64;
12556       break;
12557     case Intrinsic::ppc_qpx_qvlfcs:
12558       VT = MVT::v2f32;
12559       break;
12560     default:
12561       VT = MVT::v4i32;
12562       break;
12563     }
12564
12565     Info.opc = ISD::INTRINSIC_W_CHAIN;
12566     Info.memVT = VT;
12567     Info.ptrVal = I.getArgOperand(0);
12568     Info.offset = -VT.getStoreSize()+1;
12569     Info.size = 2*VT.getStoreSize()-1;
12570     Info.align = 1;
12571     Info.vol = false;
12572     Info.readMem = true;
12573     Info.writeMem = false;
12574     return true;
12575   }
12576   case Intrinsic::ppc_qpx_qvlfda:
12577   case Intrinsic::ppc_qpx_qvlfsa:
12578   case Intrinsic::ppc_qpx_qvlfcda:
12579   case Intrinsic::ppc_qpx_qvlfcsa:
12580   case Intrinsic::ppc_qpx_qvlfiwaa:
12581   case Intrinsic::ppc_qpx_qvlfiwza: {
12582     EVT VT;
12583     switch (Intrinsic) {
12584     case Intrinsic::ppc_qpx_qvlfda:
12585       VT = MVT::v4f64;
12586       break;
12587     case Intrinsic::ppc_qpx_qvlfsa:
12588       VT = MVT::v4f32;
12589       break;
12590     case Intrinsic::ppc_qpx_qvlfcda:
12591       VT = MVT::v2f64;
12592       break;
12593     case Intrinsic::ppc_qpx_qvlfcsa:
12594       VT = MVT::v2f32;
12595       break;
12596     default:
12597       VT = MVT::v4i32;
12598       break;
12599     }
12600
12601     Info.opc = ISD::INTRINSIC_W_CHAIN;
12602     Info.memVT = VT;
12603     Info.ptrVal = I.getArgOperand(0);
12604     Info.offset = 0;
12605     Info.size = VT.getStoreSize();
12606     Info.align = 1;
12607     Info.vol = false;
12608     Info.readMem = true;
12609     Info.writeMem = false;
12610     return true;
12611   }
12612   case Intrinsic::ppc_qpx_qvstfd:
12613   case Intrinsic::ppc_qpx_qvstfs:
12614   case Intrinsic::ppc_qpx_qvstfcd:
12615   case Intrinsic::ppc_qpx_qvstfcs:
12616   case Intrinsic::ppc_qpx_qvstfiw:
12617   case Intrinsic::ppc_altivec_stvx:
12618   case Intrinsic::ppc_altivec_stvxl:
12619   case Intrinsic::ppc_altivec_stvebx:
12620   case Intrinsic::ppc_altivec_stvehx:
12621   case Intrinsic::ppc_altivec_stvewx:
12622   case Intrinsic::ppc_vsx_stxvd2x:
12623   case Intrinsic::ppc_vsx_stxvw4x: {
12624     EVT VT;
12625     switch (Intrinsic) {
12626     case Intrinsic::ppc_altivec_stvebx:
12627       VT = MVT::i8;
12628       break;
12629     case Intrinsic::ppc_altivec_stvehx:
12630       VT = MVT::i16;
12631       break;
12632     case Intrinsic::ppc_altivec_stvewx:
12633       VT = MVT::i32;
12634       break;
12635     case Intrinsic::ppc_vsx_stxvd2x:
12636       VT = MVT::v2f64;
12637       break;
12638     case Intrinsic::ppc_qpx_qvstfd:
12639       VT = MVT::v4f64;
12640       break;
12641     case Intrinsic::ppc_qpx_qvstfs:
12642       VT = MVT::v4f32;
12643       break;
12644     case Intrinsic::ppc_qpx_qvstfcd:
12645       VT = MVT::v2f64;
12646       break;
12647     case Intrinsic::ppc_qpx_qvstfcs:
12648       VT = MVT::v2f32;
12649       break;
12650     default:
12651       VT = MVT::v4i32;
12652       break;
12653     }
12654
12655     Info.opc = ISD::INTRINSIC_VOID;
12656     Info.memVT = VT;
12657     Info.ptrVal = I.getArgOperand(1);
12658     Info.offset = -VT.getStoreSize()+1;
12659     Info.size = 2*VT.getStoreSize()-1;
12660     Info.align = 1;
12661     Info.vol = false;
12662     Info.readMem = false;
12663     Info.writeMem = true;
12664     return true;
12665   }
12666   case Intrinsic::ppc_qpx_qvstfda:
12667   case Intrinsic::ppc_qpx_qvstfsa:
12668   case Intrinsic::ppc_qpx_qvstfcda:
12669   case Intrinsic::ppc_qpx_qvstfcsa:
12670   case Intrinsic::ppc_qpx_qvstfiwa: {
12671     EVT VT;
12672     switch (Intrinsic) {
12673     case Intrinsic::ppc_qpx_qvstfda:
12674       VT = MVT::v4f64;
12675       break;
12676     case Intrinsic::ppc_qpx_qvstfsa:
12677       VT = MVT::v4f32;
12678       break;
12679     case Intrinsic::ppc_qpx_qvstfcda:
12680       VT = MVT::v2f64;
12681       break;
12682     case Intrinsic::ppc_qpx_qvstfcsa:
12683       VT = MVT::v2f32;
12684       break;
12685     default:
12686       VT = MVT::v4i32;
12687       break;
12688     }
12689
12690     Info.opc = ISD::INTRINSIC_VOID;
12691     Info.memVT = VT;
12692     Info.ptrVal = I.getArgOperand(1);
12693     Info.offset = 0;
12694     Info.size = VT.getStoreSize();
12695     Info.align = 1;
12696     Info.vol = false;
12697     Info.readMem = false;
12698     Info.writeMem = true;
12699     return true;
12700   }
12701   default:
12702     break;
12703   }
12704
12705   return false;
12706 }
12707
12708 /// getOptimalMemOpType - Returns the target specific optimal type for load
12709 /// and store operations as a result of memset, memcpy, and memmove
12710 /// lowering. If DstAlign is zero that means it's safe to destination
12711 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12712 /// means there isn't a need to check it against alignment requirement,
12713 /// probably because the source does not need to be loaded. If 'IsMemset' is
12714 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12715 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12716 /// source is constant so it does not need to be loaded.
12717 /// It returns EVT::Other if the type should be determined using generic
12718 /// target-independent logic.
12719 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12720                                            unsigned DstAlign, unsigned SrcAlign,
12721                                            bool IsMemset, bool ZeroMemset,
12722                                            bool MemcpyStrSrc,
12723                                            MachineFunction &MF) const {
12724   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12725     const Function *F = MF.getFunction();
12726     // When expanding a memset, require at least two QPX instructions to cover
12727     // the cost of loading the value to be stored from the constant pool.
12728     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12729        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12730         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12731       return MVT::v4f64;
12732     }
12733
12734     // We should use Altivec/VSX loads and stores when available. For unaligned
12735     // addresses, unaligned VSX loads are only fast starting with the P8.
12736     if (Subtarget.hasAltivec() && Size >= 16 &&
12737         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12738          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12739       return MVT::v4i32;
12740   }
12741
12742   if (Subtarget.isPPC64()) {
12743     return MVT::i64;
12744   }
12745
12746   return MVT::i32;
12747 }
12748
12749 /// \brief Returns true if it is beneficial to convert a load of a constant
12750 /// to just the constant itself.
12751 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12752                                                           Type *Ty) const {
12753   assert(Ty->isIntegerTy());
12754
12755   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12756   return !(BitSize == 0 || BitSize > 64);
12757 }
12758
12759 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12760   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12761     return false;
12762   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12763   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12764   return NumBits1 == 64 && NumBits2 == 32;
12765 }
12766
12767 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12768   if (!VT1.isInteger() || !VT2.isInteger())
12769     return false;
12770   unsigned NumBits1 = VT1.getSizeInBits();
12771   unsigned NumBits2 = VT2.getSizeInBits();
12772   return NumBits1 == 64 && NumBits2 == 32;
12773 }
12774
12775 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12776   // Generally speaking, zexts are not free, but they are free when they can be
12777   // folded with other operations.
12778   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12779     EVT MemVT = LD->getMemoryVT();
12780     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12781          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12782         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12783          LD->getExtensionType() == ISD::ZEXTLOAD))
12784       return true;
12785   }
12786
12787   // FIXME: Add other cases...
12788   //  - 32-bit shifts with a zext to i64
12789   //  - zext after ctlz, bswap, etc.
12790   //  - zext after and by a constant mask
12791
12792   return TargetLowering::isZExtFree(Val, VT2);
12793 }
12794
12795 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12796   assert(VT.isFloatingPoint());
12797   return true;
12798 }
12799
12800 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12801   return isInt<16>(Imm) || isUInt<16>(Imm);
12802 }
12803
12804 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12805   return isInt<16>(Imm) || isUInt<16>(Imm);
12806 }
12807
12808 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12809                                                        unsigned,
12810                                                        unsigned,
12811                                                        bool *Fast) const {
12812   if (DisablePPCUnaligned)
12813     return false;
12814
12815   // PowerPC supports unaligned memory access for simple non-vector types.
12816   // Although accessing unaligned addresses is not as efficient as accessing
12817   // aligned addresses, it is generally more efficient than manual expansion,
12818   // and generally only traps for software emulation when crossing page
12819   // boundaries.
12820
12821   if (!VT.isSimple())
12822     return false;
12823
12824   if (VT.getSimpleVT().isVector()) {
12825     if (Subtarget.hasVSX()) {
12826       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12827           VT != MVT::v4f32 && VT != MVT::v4i32)
12828         return false;
12829     } else {
12830       return false;
12831     }
12832   }
12833
12834   if (VT == MVT::ppcf128)
12835     return false;
12836
12837   if (Fast)
12838     *Fast = true;
12839
12840   return true;
12841 }
12842
12843 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12844   VT = VT.getScalarType();
12845
12846   if (!VT.isSimple())
12847     return false;
12848
12849   switch (VT.getSimpleVT().SimpleTy) {
12850   case MVT::f32:
12851   case MVT::f64:
12852     return true;
12853   default:
12854     break;
12855   }
12856
12857   return false;
12858 }
12859
12860 const MCPhysReg *
12861 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12862   // LR is a callee-save register, but we must treat it as clobbered by any call
12863   // site. Hence we include LR in the scratch registers, which are in turn added
12864   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12865   // to CTR, which is used by any indirect call.
12866   static const MCPhysReg ScratchRegs[] = {
12867     PPC::X12, PPC::LR8, PPC::CTR8, 0
12868   };
12869
12870   return ScratchRegs;
12871 }
12872
12873 unsigned PPCTargetLowering::getExceptionPointerRegister(
12874     const Constant *PersonalityFn) const {
12875   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12876 }
12877
12878 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12879     const Constant *PersonalityFn) const {
12880   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12881 }
12882
12883 bool
12884 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12885                      EVT VT , unsigned DefinedValues) const {
12886   if (VT == MVT::v2i64)
12887     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12888
12889   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12890     return true;
12891
12892   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12893 }
12894
12895 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12896   if (DisableILPPref || Subtarget.enableMachineScheduler())
12897     return TargetLowering::getSchedulingPreference(N);
12898
12899   return Sched::ILP;
12900 }
12901
12902 // Create a fast isel object.
12903 FastISel *
12904 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12905                                   const TargetLibraryInfo *LibInfo) const {
12906   return PPC::createFastISel(FuncInfo, LibInfo);
12907 }
12908
12909 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12910   if (Subtarget.isDarwinABI()) return;
12911   if (!Subtarget.isPPC64()) return;
12912
12913   // Update IsSplitCSR in PPCFunctionInfo
12914   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12915   PFI->setIsSplitCSR(true);
12916 }
12917
12918 void PPCTargetLowering::insertCopiesSplitCSR(
12919   MachineBasicBlock *Entry,
12920   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12921   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12922   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12923   if (!IStart)
12924     return;
12925
12926   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12927   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12928   MachineBasicBlock::iterator MBBI = Entry->begin();
12929   for (const MCPhysReg *I = IStart; *I; ++I) {
12930     const TargetRegisterClass *RC = nullptr;
12931     if (PPC::G8RCRegClass.contains(*I))
12932       RC = &PPC::G8RCRegClass;
12933     else if (PPC::F8RCRegClass.contains(*I))
12934       RC = &PPC::F8RCRegClass;
12935     else if (PPC::CRRCRegClass.contains(*I))
12936       RC = &PPC::CRRCRegClass;
12937     else if (PPC::VRRCRegClass.contains(*I))
12938       RC = &PPC::VRRCRegClass;
12939     else
12940       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12941
12942     unsigned NewVR = MRI->createVirtualRegister(RC);
12943     // Create copy from CSR to a virtual register.
12944     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12945     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12946     // nounwind. If we want to generalize this later, we may need to emit
12947     // CFI pseudo-instructions.
12948     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12949              Attribute::NoUnwind) &&
12950            "Function should be nounwind in insertCopiesSplitCSR!");
12951     Entry->addLiveIn(*I);
12952     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12953       .addReg(*I);
12954
12955     // Insert the copy-back instructions right before the terminator
12956     for (auto *Exit : Exits)
12957       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12958               TII->get(TargetOpcode::COPY), *I)
12959         .addReg(NewVR);
12960   }
12961 }
12962
12963 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12964 bool PPCTargetLowering::useLoadStackGuardNode() const {
12965   if (!Subtarget.isTargetLinux())
12966     return TargetLowering::useLoadStackGuardNode();
12967   return true;
12968 }
12969
12970 // Override to disable global variable loading on Linux.
12971 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12972   if (!Subtarget.isTargetLinux())
12973     return TargetLowering::insertSSPDeclarations(M);
12974 }
12975
12976 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12977   if (!VT.isSimple() || !Subtarget.hasVSX())
12978     return false;
12979
12980   switch(VT.getSimpleVT().SimpleTy) {
12981   default:
12982     // For FP types that are currently not supported by PPC backend, return
12983     // false. Examples: f16, f80.
12984     return false;
12985   case MVT::f32:
12986   case MVT::f64:
12987   case MVT::ppcf128:
12988     return Imm.isPosZero();
12989   }
12990 }
12991
12992 // For vector shift operation op, fold
12993 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
12994 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
12995                                   SelectionDAG &DAG) {
12996   SDValue N0 = N->getOperand(0);
12997   SDValue N1 = N->getOperand(1);
12998   EVT VT = N0.getValueType();
12999   unsigned OpSizeInBits = VT.getScalarSizeInBits();
13000   unsigned Opcode = N->getOpcode();
13001   unsigned TargetOpcode;
13002
13003   switch (Opcode) {
13004   default:
13005     llvm_unreachable("Unexpected shift operation");
13006   case ISD::SHL:
13007     TargetOpcode = PPCISD::SHL;
13008     break;
13009   case ISD::SRL:
13010     TargetOpcode = PPCISD::SRL;
13011     break;
13012   case ISD::SRA:
13013     TargetOpcode = PPCISD::SRA;
13014     break;
13015   }
13016
13017   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13018       N1->getOpcode() == ISD::AND)
13019     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13020       if (Mask->getZExtValue() == OpSizeInBits - 1)
13021         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13022
13023   return SDValue();
13024 }
13025
13026 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13027   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13028     return Value;
13029
13030   return SDValue();
13031 }
13032
13033 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13034   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13035     return Value;
13036
13037   return SDValue();
13038 }
13039
13040 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13041   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13042     return Value;
13043
13044   return SDValue();
13045 }