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/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Target/TargetInstrInfo.h"
85 #include "llvm/Target/TargetLowering.h"
86 #include "llvm/Target/TargetMachine.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include "llvm/Target/TargetRegisterInfo.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstdint>
92 #include <iterator>
93 #include <list>
94 #include <utility>
95 #include <vector>
96 
97 using namespace llvm;
98 
99 #define DEBUG_TYPE "ppc-lowering"
100 
101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
103 
104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
106 
107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
109 
110 static cl::opt<bool> DisableSCO("disable-ppc-sco",
111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
112 
113 STATISTIC(NumTailCalls, "Number of tail calls");
114 STATISTIC(NumSiblingCalls, "Number of sibling calls");
115 
116 // FIXME: Remove this once the bug has been fixed!
117 extern cl::opt<bool> ANDIGlueBug;
118 
119 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
120                                      const PPCSubtarget &STI)
121     : TargetLowering(TM), Subtarget(STI) {
122   // Use _setjmp/_longjmp instead of setjmp/longjmp.
123   setUseUnderscoreSetJmp(true);
124   setUseUnderscoreLongJmp(true);
125 
126   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
127   // arguments are at least 4/8 bytes aligned.
128   bool isPPC64 = Subtarget.isPPC64();
129   setMinStackArgumentAlignment(isPPC64 ? 8:4);
130 
131   // Set up the register classes.
132   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
133   if (!useSoftFloat()) {
134     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
135     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
136   }
137 
138   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
139   for (MVT VT : MVT::integer_valuetypes()) {
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
142   }
143 
144   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
145 
146   // PowerPC has pre-inc load and store's.
147   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
148   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
149   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
150   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
151   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
152   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
153   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
154   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
155   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
156   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
157   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
158   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
159   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
160   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
161 
162   if (Subtarget.useCRBits()) {
163     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
164 
165     if (isPPC64 || Subtarget.hasFPCVT()) {
166       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
167       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
168                          isPPC64 ? MVT::i64 : MVT::i32);
169       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
170       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
171                         isPPC64 ? MVT::i64 : MVT::i32);
172     } else {
173       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
174       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
175     }
176 
177     // PowerPC does not support direct load / store of condition registers
178     setOperationAction(ISD::LOAD, MVT::i1, Custom);
179     setOperationAction(ISD::STORE, MVT::i1, Custom);
180 
181     // FIXME: Remove this once the ANDI glue bug is fixed:
182     if (ANDIGlueBug)
183       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
184 
185     for (MVT VT : MVT::integer_valuetypes()) {
186       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
187       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
188       setTruncStoreAction(VT, MVT::i1, Expand);
189     }
190 
191     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
192   }
193 
194   // This is used in the ppcf128->int sequence.  Note it has different semantics
195   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
196   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
197 
198   // We do not currently implement these libm ops for PowerPC.
199   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
200   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
201   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
202   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
203   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
204   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
205 
206   // PowerPC has no SREM/UREM instructions
207   setOperationAction(ISD::SREM, MVT::i32, Expand);
208   setOperationAction(ISD::UREM, MVT::i32, Expand);
209   setOperationAction(ISD::SREM, MVT::i64, Expand);
210   setOperationAction(ISD::UREM, MVT::i64, Expand);
211 
212   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
213   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
214   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
215   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
216   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
217   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
218   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
219   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
220   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
221 
222   // We don't support sin/cos/sqrt/fmod/pow
223   setOperationAction(ISD::FSIN , MVT::f64, Expand);
224   setOperationAction(ISD::FCOS , MVT::f64, Expand);
225   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
226   setOperationAction(ISD::FREM , MVT::f64, Expand);
227   setOperationAction(ISD::FPOW , MVT::f64, Expand);
228   setOperationAction(ISD::FMA  , MVT::f64, Legal);
229   setOperationAction(ISD::FSIN , MVT::f32, Expand);
230   setOperationAction(ISD::FCOS , MVT::f32, Expand);
231   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
232   setOperationAction(ISD::FREM , MVT::f32, Expand);
233   setOperationAction(ISD::FPOW , MVT::f32, Expand);
234   setOperationAction(ISD::FMA  , MVT::f32, Legal);
235 
236   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
237 
238   // If we're enabling GP optimizations, use hardware square root
239   if (!Subtarget.hasFSQRT() &&
240       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
241         Subtarget.hasFRE()))
242     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
243 
244   if (!Subtarget.hasFSQRT() &&
245       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
246         Subtarget.hasFRES()))
247     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
248 
249   if (Subtarget.hasFCPSGN()) {
250     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
251     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
252   } else {
253     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
254     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
255   }
256 
257   if (Subtarget.hasFPRND()) {
258     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
259     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
260     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
261     setOperationAction(ISD::FROUND, MVT::f64, Legal);
262 
263     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
264     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
265     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
266     setOperationAction(ISD::FROUND, MVT::f32, Legal);
267   }
268 
269   // PowerPC does not have BSWAP
270   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
271   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
272   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
273   if (Subtarget.isISA3_0()) {
274     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
275     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
276   } else {
277     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
278     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
279   }
280 
281   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
282     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
283     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
284   } else {
285     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
286     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
287   }
288 
289   // PowerPC does not have ROTR
290   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
291   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
292 
293   if (!Subtarget.useCRBits()) {
294     // PowerPC does not have Select
295     setOperationAction(ISD::SELECT, MVT::i32, Expand);
296     setOperationAction(ISD::SELECT, MVT::i64, Expand);
297     setOperationAction(ISD::SELECT, MVT::f32, Expand);
298     setOperationAction(ISD::SELECT, MVT::f64, Expand);
299   }
300 
301   // PowerPC wants to turn select_cc of FP into fsel when possible.
302   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
303   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
304 
305   // PowerPC wants to optimize integer setcc a bit
306   if (!Subtarget.useCRBits())
307     setOperationAction(ISD::SETCC, MVT::i32, Custom);
308 
309   // PowerPC does not have BRCOND which requires SetCC
310   if (!Subtarget.useCRBits())
311     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
312 
313   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
314 
315   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
316   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
317 
318   // PowerPC does not have [U|S]INT_TO_FP
319   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
320   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
321 
322   if (Subtarget.hasDirectMove() && isPPC64) {
323     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
324     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
325     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
326     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
327   } else {
328     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
329     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
330     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
331     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
332   }
333 
334   // We cannot sextinreg(i1).  Expand to shifts.
335   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
336 
337   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
338   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
339   // support continuation, user-level threading, and etc.. As a result, no
340   // other SjLj exception interfaces are implemented and please don't build
341   // your own exception handling based on them.
342   // LLVM/Clang supports zero-cost DWARF exception handling.
343   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
344   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
345 
346   // We want to legalize GlobalAddress and ConstantPool nodes into the
347   // appropriate instructions to materialize the address.
348   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
349   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
350   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
351   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
352   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
353   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
354   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
355   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
356   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
357   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
358 
359   // TRAP is legal.
360   setOperationAction(ISD::TRAP, MVT::Other, Legal);
361 
362   // TRAMPOLINE is custom lowered.
363   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
364   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
365 
366   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
367   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
368 
369   if (Subtarget.isSVR4ABI()) {
370     if (isPPC64) {
371       // VAARG always uses double-word chunks, so promote anything smaller.
372       setOperationAction(ISD::VAARG, MVT::i1, Promote);
373       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
374       setOperationAction(ISD::VAARG, MVT::i8, Promote);
375       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
376       setOperationAction(ISD::VAARG, MVT::i16, Promote);
377       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
378       setOperationAction(ISD::VAARG, MVT::i32, Promote);
379       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
380       setOperationAction(ISD::VAARG, MVT::Other, Expand);
381     } else {
382       // VAARG is custom lowered with the 32-bit SVR4 ABI.
383       setOperationAction(ISD::VAARG, MVT::Other, Custom);
384       setOperationAction(ISD::VAARG, MVT::i64, Custom);
385     }
386   } else
387     setOperationAction(ISD::VAARG, MVT::Other, Expand);
388 
389   if (Subtarget.isSVR4ABI() && !isPPC64)
390     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
391     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
392   else
393     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
394 
395   // Use the default implementation.
396   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
397   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
398   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
399   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
400   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
401   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
402   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
403   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
404   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
405 
406   // We want to custom lower some of our intrinsics.
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408 
409   // To handle counter-based loop conditions.
410   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
411 
412   // Comparisons that require checking two conditions.
413   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
414   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
415   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
416   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
417   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
418   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
419   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
420   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
421   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
422   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
423   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
424   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
425 
426   if (Subtarget.has64BitSupport()) {
427     // They also have instructions for converting between i64 and fp.
428     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
429     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
430     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
431     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
432     // This is just the low 32 bits of a (signed) fp->i64 conversion.
433     // We cannot do this with Promote because i64 is not a legal type.
434     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
435 
436     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
437       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
438   } else {
439     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
440     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
441   }
442 
443   // With the instructions enabled under FPCVT, we can do everything.
444   if (Subtarget.hasFPCVT()) {
445     if (Subtarget.has64BitSupport()) {
446       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
447       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
448       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
449       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
450     }
451 
452     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
453     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
454     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
455     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
456   }
457 
458   if (Subtarget.use64BitRegs()) {
459     // 64-bit PowerPC implementations can support i64 types directly
460     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
461     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
462     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
463     // 64-bit PowerPC wants to expand i128 shifts itself.
464     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
465     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
466     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
467   } else {
468     // 32-bit PowerPC wants to expand i64 shifts itself.
469     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
470     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
471     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
472   }
473 
474   if (Subtarget.hasAltivec()) {
475     // First set operation action for all vector types to expand. Then we
476     // will selectively turn on ones that can be effectively codegen'd.
477     for (MVT VT : MVT::vector_valuetypes()) {
478       // add/sub are legal for all supported vector VT's.
479       setOperationAction(ISD::ADD, VT, Legal);
480       setOperationAction(ISD::SUB, VT, Legal);
481 
482       // Vector instructions introduced in P8
483       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
484         setOperationAction(ISD::CTPOP, VT, Legal);
485         setOperationAction(ISD::CTLZ, VT, Legal);
486       }
487       else {
488         setOperationAction(ISD::CTPOP, VT, Expand);
489         setOperationAction(ISD::CTLZ, VT, Expand);
490       }
491 
492       // Vector instructions introduced in P9
493       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
494         setOperationAction(ISD::CTTZ, VT, Legal);
495       else
496         setOperationAction(ISD::CTTZ, VT, Expand);
497 
498       // We promote all shuffles to v16i8.
499       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
500       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
501 
502       // We promote all non-typed operations to v4i32.
503       setOperationAction(ISD::AND   , VT, Promote);
504       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
505       setOperationAction(ISD::OR    , VT, Promote);
506       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
507       setOperationAction(ISD::XOR   , VT, Promote);
508       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
509       setOperationAction(ISD::LOAD  , VT, Promote);
510       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
511       setOperationAction(ISD::SELECT, VT, Promote);
512       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
513       setOperationAction(ISD::SELECT_CC, VT, Promote);
514       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
515       setOperationAction(ISD::STORE, VT, Promote);
516       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
517 
518       // No other operations are legal.
519       setOperationAction(ISD::MUL , VT, Expand);
520       setOperationAction(ISD::SDIV, VT, Expand);
521       setOperationAction(ISD::SREM, VT, Expand);
522       setOperationAction(ISD::UDIV, VT, Expand);
523       setOperationAction(ISD::UREM, VT, Expand);
524       setOperationAction(ISD::FDIV, VT, Expand);
525       setOperationAction(ISD::FREM, VT, Expand);
526       setOperationAction(ISD::FNEG, VT, Expand);
527       setOperationAction(ISD::FSQRT, VT, Expand);
528       setOperationAction(ISD::FLOG, VT, Expand);
529       setOperationAction(ISD::FLOG10, VT, Expand);
530       setOperationAction(ISD::FLOG2, VT, Expand);
531       setOperationAction(ISD::FEXP, VT, Expand);
532       setOperationAction(ISD::FEXP2, VT, Expand);
533       setOperationAction(ISD::FSIN, VT, Expand);
534       setOperationAction(ISD::FCOS, VT, Expand);
535       setOperationAction(ISD::FABS, VT, Expand);
536       setOperationAction(ISD::FPOWI, VT, Expand);
537       setOperationAction(ISD::FFLOOR, VT, Expand);
538       setOperationAction(ISD::FCEIL,  VT, Expand);
539       setOperationAction(ISD::FTRUNC, VT, Expand);
540       setOperationAction(ISD::FRINT,  VT, Expand);
541       setOperationAction(ISD::FNEARBYINT, VT, Expand);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
543       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
544       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
545       setOperationAction(ISD::MULHU, VT, Expand);
546       setOperationAction(ISD::MULHS, VT, Expand);
547       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
548       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
549       setOperationAction(ISD::UDIVREM, VT, Expand);
550       setOperationAction(ISD::SDIVREM, VT, Expand);
551       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
552       setOperationAction(ISD::FPOW, VT, Expand);
553       setOperationAction(ISD::BSWAP, VT, Expand);
554       setOperationAction(ISD::VSELECT, VT, Expand);
555       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
556       setOperationAction(ISD::ROTL, VT, Expand);
557       setOperationAction(ISD::ROTR, VT, Expand);
558 
559       for (MVT InnerVT : MVT::vector_valuetypes()) {
560         setTruncStoreAction(VT, InnerVT, Expand);
561         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
562         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
563         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
564       }
565     }
566 
567     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
568     // with merges, splats, etc.
569     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
570 
571     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
572     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
573     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
574     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
575     setOperationAction(ISD::SELECT, MVT::v4i32,
576                        Subtarget.useCRBits() ? Legal : Expand);
577     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
578     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
579     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
580     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
581     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
582     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
583     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
584     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
585     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
586 
587     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
588     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
589     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
590     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
591 
592     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
593     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
594 
595     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
596       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
597       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
598     }
599 
600     if (Subtarget.hasP8Altivec())
601       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
602     else
603       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
604 
605     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
606     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
607 
608     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
609     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
610 
611     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
612     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
613     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
614     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
615 
616     // Altivec does not contain unordered floating-point compare instructions
617     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
618     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
619     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
620     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
621 
622     if (Subtarget.hasVSX()) {
623       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
624       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
625       if (Subtarget.hasP8Vector()) {
626         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
627         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
628       }
629       if (Subtarget.hasDirectMove() && isPPC64) {
630         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
631         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
632         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
633         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
634         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
635         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
636         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
637         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
638       }
639       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
640 
641       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
642       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
643       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
644       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
645       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
646 
647       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
648 
649       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
650       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
651 
652       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
653       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
654 
655       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
656       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
657       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
658       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
659       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
660 
661       // Share the Altivec comparison restrictions.
662       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
663       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
664       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
665       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
666 
667       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
668       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
669 
670       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
671 
672       if (Subtarget.hasP8Vector())
673         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
674 
675       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
676 
677       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
678       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
679       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
680 
681       if (Subtarget.hasP8Altivec()) {
682         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
683         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
684         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
685 
686         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
687       }
688       else {
689         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
690         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
691         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
692 
693         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
694 
695         // VSX v2i64 only supports non-arithmetic operations.
696         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
697         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
698       }
699 
700       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
701       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
702       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
703       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
704 
705       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
706 
707       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
708       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
709       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
710       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
711 
712       // Vector operation legalization checks the result type of
713       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
714       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
715       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
716       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
717       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
718 
719       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
720       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
721       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
722       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
723 
724       if (Subtarget.hasDirectMove())
725         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
726       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
727 
728       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
729     }
730 
731     if (Subtarget.hasP8Altivec()) {
732       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
733       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
734     }
735 
736     if (Subtarget.hasP9Vector()) {
737       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
738       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
739     }
740   }
741 
742   if (Subtarget.hasQPX()) {
743     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
744     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
745     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
746     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
747 
748     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
749     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
750 
751     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
752     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
753 
754     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
755     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
756 
757     if (!Subtarget.useCRBits())
758       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
759     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
760 
761     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
762     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
763     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
764     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
765     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
766     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
767     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
768 
769     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
770     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
771 
772     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
773     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
774     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
775 
776     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
777     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
778     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
779     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
780     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
781     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
782     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
783     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
784     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
785     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
786     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
787 
788     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
789     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
790 
791     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
792     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
793 
794     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
795 
796     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
799     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
800 
801     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
802     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
803 
804     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
805     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
806 
807     if (!Subtarget.useCRBits())
808       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
809     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
810 
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
812     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
813     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
814     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
815     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
816     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
817     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
818 
819     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
820     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
821 
822     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
823     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
824     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
825     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
826     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
827     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
828     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
829     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
830     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
831     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
832     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
833 
834     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
835     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
836 
837     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
838     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
839 
840     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
841 
842     setOperationAction(ISD::AND , MVT::v4i1, Legal);
843     setOperationAction(ISD::OR , MVT::v4i1, Legal);
844     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
845 
846     if (!Subtarget.useCRBits())
847       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
848     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
849 
850     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
851     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
852 
853     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
854     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
855     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
856     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
857     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
858     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
859     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
860 
861     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
862     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
863 
864     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
865 
866     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
867     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
868     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
869     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
870 
871     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
872     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
873     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
874     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
875 
876     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
877     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
878 
879     // These need to set FE_INEXACT, and so cannot be vectorized here.
880     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
881     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
882 
883     if (TM.Options.UnsafeFPMath) {
884       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
885       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
886 
887       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
888       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
889     } else {
890       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
891       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
892 
893       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
894       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
895     }
896   }
897 
898   if (Subtarget.has64BitSupport())
899     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
900 
901   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
902 
903   if (!isPPC64) {
904     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
905     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
906   }
907 
908   setBooleanContents(ZeroOrOneBooleanContent);
909 
910   if (Subtarget.hasAltivec()) {
911     // Altivec instructions set fields to all zeros or all ones.
912     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
913   }
914 
915   if (!isPPC64) {
916     // These libcalls are not available in 32-bit.
917     setLibcallName(RTLIB::SHL_I128, nullptr);
918     setLibcallName(RTLIB::SRL_I128, nullptr);
919     setLibcallName(RTLIB::SRA_I128, nullptr);
920   }
921 
922   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
923 
924   // We have target-specific dag combine patterns for the following nodes:
925   setTargetDAGCombine(ISD::SINT_TO_FP);
926   setTargetDAGCombine(ISD::BUILD_VECTOR);
927   if (Subtarget.hasFPCVT())
928     setTargetDAGCombine(ISD::UINT_TO_FP);
929   setTargetDAGCombine(ISD::LOAD);
930   setTargetDAGCombine(ISD::STORE);
931   setTargetDAGCombine(ISD::BR_CC);
932   if (Subtarget.useCRBits())
933     setTargetDAGCombine(ISD::BRCOND);
934   setTargetDAGCombine(ISD::BSWAP);
935   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
936   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
937   setTargetDAGCombine(ISD::INTRINSIC_VOID);
938 
939   setTargetDAGCombine(ISD::SIGN_EXTEND);
940   setTargetDAGCombine(ISD::ZERO_EXTEND);
941   setTargetDAGCombine(ISD::ANY_EXTEND);
942 
943   if (Subtarget.useCRBits()) {
944     setTargetDAGCombine(ISD::TRUNCATE);
945     setTargetDAGCombine(ISD::SETCC);
946     setTargetDAGCombine(ISD::SELECT_CC);
947   }
948 
949   // Use reciprocal estimates.
950   if (TM.Options.UnsafeFPMath) {
951     setTargetDAGCombine(ISD::FDIV);
952     setTargetDAGCombine(ISD::FSQRT);
953   }
954 
955   // Darwin long double math library functions have $LDBL128 appended.
956   if (Subtarget.isDarwin()) {
957     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
958     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
959     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
960     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
961     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
962     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
963     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
964     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
965     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
966     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
967   }
968 
969   // With 32 condition bits, we don't need to sink (and duplicate) compares
970   // aggressively in CodeGenPrep.
971   if (Subtarget.useCRBits()) {
972     setHasMultipleConditionRegisters();
973     setJumpIsExpensive();
974   }
975 
976   setMinFunctionAlignment(2);
977   if (Subtarget.isDarwin())
978     setPrefFunctionAlignment(4);
979 
980   switch (Subtarget.getDarwinDirective()) {
981   default: break;
982   case PPC::DIR_970:
983   case PPC::DIR_A2:
984   case PPC::DIR_E500mc:
985   case PPC::DIR_E5500:
986   case PPC::DIR_PWR4:
987   case PPC::DIR_PWR5:
988   case PPC::DIR_PWR5X:
989   case PPC::DIR_PWR6:
990   case PPC::DIR_PWR6X:
991   case PPC::DIR_PWR7:
992   case PPC::DIR_PWR8:
993   case PPC::DIR_PWR9:
994     setPrefFunctionAlignment(4);
995     setPrefLoopAlignment(4);
996     break;
997   }
998 
999   if (Subtarget.enableMachineScheduler())
1000     setSchedulingPreference(Sched::Source);
1001   else
1002     setSchedulingPreference(Sched::Hybrid);
1003 
1004   computeRegisterProperties(STI.getRegisterInfo());
1005 
1006   // The Freescale cores do better with aggressive inlining of memcpy and
1007   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1008   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1009       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1010     MaxStoresPerMemset = 32;
1011     MaxStoresPerMemsetOptSize = 16;
1012     MaxStoresPerMemcpy = 32;
1013     MaxStoresPerMemcpyOptSize = 8;
1014     MaxStoresPerMemmove = 32;
1015     MaxStoresPerMemmoveOptSize = 8;
1016   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1017     // The A2 also benefits from (very) aggressive inlining of memcpy and
1018     // friends. The overhead of a the function call, even when warm, can be
1019     // over one hundred cycles.
1020     MaxStoresPerMemset = 128;
1021     MaxStoresPerMemcpy = 128;
1022     MaxStoresPerMemmove = 128;
1023   }
1024 }
1025 
1026 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1027 /// the desired ByVal argument alignment.
1028 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1029                              unsigned MaxMaxAlign) {
1030   if (MaxAlign == MaxMaxAlign)
1031     return;
1032   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1033     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1034       MaxAlign = 32;
1035     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1036       MaxAlign = 16;
1037   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1038     unsigned EltAlign = 0;
1039     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1040     if (EltAlign > MaxAlign)
1041       MaxAlign = EltAlign;
1042   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1043     for (auto *EltTy : STy->elements()) {
1044       unsigned EltAlign = 0;
1045       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1046       if (EltAlign > MaxAlign)
1047         MaxAlign = EltAlign;
1048       if (MaxAlign == MaxMaxAlign)
1049         break;
1050     }
1051   }
1052 }
1053 
1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1055 /// function arguments in the caller parameter area.
1056 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1057                                                   const DataLayout &DL) const {
1058   // Darwin passes everything on 4 byte boundary.
1059   if (Subtarget.isDarwin())
1060     return 4;
1061 
1062   // 16byte and wider vectors are passed on 16byte boundary.
1063   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1064   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1065   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1066     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1067   return Align;
1068 }
1069 
1070 bool PPCTargetLowering::useSoftFloat() const {
1071   return Subtarget.useSoftFloat();
1072 }
1073 
1074 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1075   switch ((PPCISD::NodeType)Opcode) {
1076   case PPCISD::FIRST_NUMBER:    break;
1077   case PPCISD::FSEL:            return "PPCISD::FSEL";
1078   case PPCISD::FCFID:           return "PPCISD::FCFID";
1079   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1080   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1081   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1082   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1083   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1084   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1085   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1086   case PPCISD::FRE:             return "PPCISD::FRE";
1087   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1088   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1089   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1090   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1091   case PPCISD::VPERM:           return "PPCISD::VPERM";
1092   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1093   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1094   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1095   case PPCISD::CMPB:            return "PPCISD::CMPB";
1096   case PPCISD::Hi:              return "PPCISD::Hi";
1097   case PPCISD::Lo:              return "PPCISD::Lo";
1098   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1099   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1100   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1101   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1102   case PPCISD::SRL:             return "PPCISD::SRL";
1103   case PPCISD::SRA:             return "PPCISD::SRA";
1104   case PPCISD::SHL:             return "PPCISD::SHL";
1105   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1106   case PPCISD::CALL:            return "PPCISD::CALL";
1107   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1108   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1109   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1110   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1111   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1112   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1113   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1114   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1115   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1116   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1117   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1118   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1119   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1120   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1121   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1122   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1123   case PPCISD::VCMP:            return "PPCISD::VCMP";
1124   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1125   case PPCISD::LBRX:            return "PPCISD::LBRX";
1126   case PPCISD::STBRX:           return "PPCISD::STBRX";
1127   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1128   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1129   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1130   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1131   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1132   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1133   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1134   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1135   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1136   case PPCISD::BDZ:             return "PPCISD::BDZ";
1137   case PPCISD::MFFS:            return "PPCISD::MFFS";
1138   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1139   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1140   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1141   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1142   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1143   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1144   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1145   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1146   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1147   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1148   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1149   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1150   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1151   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1152   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1153   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1154   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1155   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1156   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1157   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1158   case PPCISD::SC:              return "PPCISD::SC";
1159   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1160   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1161   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1162   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1163   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1164   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1165   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1166   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1167   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1168   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1169   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1170   }
1171   return nullptr;
1172 }
1173 
1174 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1175                                           EVT VT) const {
1176   if (!VT.isVector())
1177     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1178 
1179   if (Subtarget.hasQPX())
1180     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1181 
1182   return VT.changeVectorElementTypeToInteger();
1183 }
1184 
1185 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1186   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1187   return true;
1188 }
1189 
1190 //===----------------------------------------------------------------------===//
1191 // Node matching predicates, for use by the tblgen matching code.
1192 //===----------------------------------------------------------------------===//
1193 
1194 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1195 static bool isFloatingPointZero(SDValue Op) {
1196   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1197     return CFP->getValueAPF().isZero();
1198   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1199     // Maybe this has already been legalized into the constant pool?
1200     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1201       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1202         return CFP->getValueAPF().isZero();
1203   }
1204   return false;
1205 }
1206 
1207 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1208 /// true if Op is undef or if it matches the specified value.
1209 static bool isConstantOrUndef(int Op, int Val) {
1210   return Op < 0 || Op == Val;
1211 }
1212 
1213 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1214 /// VPKUHUM instruction.
1215 /// The ShuffleKind distinguishes between big-endian operations with
1216 /// two different inputs (0), either-endian operations with two identical
1217 /// inputs (1), and little-endian operations with two different inputs (2).
1218 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1219 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1220                                SelectionDAG &DAG) {
1221   bool IsLE = DAG.getDataLayout().isLittleEndian();
1222   if (ShuffleKind == 0) {
1223     if (IsLE)
1224       return false;
1225     for (unsigned i = 0; i != 16; ++i)
1226       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1227         return false;
1228   } else if (ShuffleKind == 2) {
1229     if (!IsLE)
1230       return false;
1231     for (unsigned i = 0; i != 16; ++i)
1232       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1233         return false;
1234   } else if (ShuffleKind == 1) {
1235     unsigned j = IsLE ? 0 : 1;
1236     for (unsigned i = 0; i != 8; ++i)
1237       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1238           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1239         return false;
1240   }
1241   return true;
1242 }
1243 
1244 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1245 /// VPKUWUM instruction.
1246 /// The ShuffleKind distinguishes between big-endian operations with
1247 /// two different inputs (0), either-endian operations with two identical
1248 /// inputs (1), and little-endian operations with two different inputs (2).
1249 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1250 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1251                                SelectionDAG &DAG) {
1252   bool IsLE = DAG.getDataLayout().isLittleEndian();
1253   if (ShuffleKind == 0) {
1254     if (IsLE)
1255       return false;
1256     for (unsigned i = 0; i != 16; i += 2)
1257       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1258           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1259         return false;
1260   } else if (ShuffleKind == 2) {
1261     if (!IsLE)
1262       return false;
1263     for (unsigned i = 0; i != 16; i += 2)
1264       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1265           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1266         return false;
1267   } else if (ShuffleKind == 1) {
1268     unsigned j = IsLE ? 0 : 2;
1269     for (unsigned i = 0; i != 8; i += 2)
1270       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1271           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1272           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1273           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1274         return false;
1275   }
1276   return true;
1277 }
1278 
1279 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1280 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1281 /// current subtarget.
1282 ///
1283 /// The ShuffleKind distinguishes between big-endian operations with
1284 /// two different inputs (0), either-endian operations with two identical
1285 /// inputs (1), and little-endian operations with two different inputs (2).
1286 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1287 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1288                                SelectionDAG &DAG) {
1289   const PPCSubtarget& Subtarget =
1290     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1291   if (!Subtarget.hasP8Vector())
1292     return false;
1293 
1294   bool IsLE = DAG.getDataLayout().isLittleEndian();
1295   if (ShuffleKind == 0) {
1296     if (IsLE)
1297       return false;
1298     for (unsigned i = 0; i != 16; i += 4)
1299       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1300           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1301           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1302           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1303         return false;
1304   } else if (ShuffleKind == 2) {
1305     if (!IsLE)
1306       return false;
1307     for (unsigned i = 0; i != 16; i += 4)
1308       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1309           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1310           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1311           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1312         return false;
1313   } else if (ShuffleKind == 1) {
1314     unsigned j = IsLE ? 0 : 4;
1315     for (unsigned i = 0; i != 8; i += 4)
1316       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1317           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1318           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1319           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1320           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1321           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1322           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1323           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1324         return false;
1325   }
1326   return true;
1327 }
1328 
1329 /// isVMerge - Common function, used to match vmrg* shuffles.
1330 ///
1331 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1332                      unsigned LHSStart, unsigned RHSStart) {
1333   if (N->getValueType(0) != MVT::v16i8)
1334     return false;
1335   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1336          "Unsupported merge size!");
1337 
1338   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1339     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1340       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1341                              LHSStart+j+i*UnitSize) ||
1342           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1343                              RHSStart+j+i*UnitSize))
1344         return false;
1345     }
1346   return true;
1347 }
1348 
1349 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1350 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1351 /// The ShuffleKind distinguishes between big-endian merges with two
1352 /// different inputs (0), either-endian merges with two identical inputs (1),
1353 /// and little-endian merges with two different inputs (2).  For the latter,
1354 /// the input operands are swapped (see PPCInstrAltivec.td).
1355 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1356                              unsigned ShuffleKind, SelectionDAG &DAG) {
1357   if (DAG.getDataLayout().isLittleEndian()) {
1358     if (ShuffleKind == 1) // unary
1359       return isVMerge(N, UnitSize, 0, 0);
1360     else if (ShuffleKind == 2) // swapped
1361       return isVMerge(N, UnitSize, 0, 16);
1362     else
1363       return false;
1364   } else {
1365     if (ShuffleKind == 1) // unary
1366       return isVMerge(N, UnitSize, 8, 8);
1367     else if (ShuffleKind == 0) // normal
1368       return isVMerge(N, UnitSize, 8, 24);
1369     else
1370       return false;
1371   }
1372 }
1373 
1374 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1375 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1376 /// The ShuffleKind distinguishes between big-endian merges with two
1377 /// different inputs (0), either-endian merges with two identical inputs (1),
1378 /// and little-endian merges with two different inputs (2).  For the latter,
1379 /// the input operands are swapped (see PPCInstrAltivec.td).
1380 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1381                              unsigned ShuffleKind, SelectionDAG &DAG) {
1382   if (DAG.getDataLayout().isLittleEndian()) {
1383     if (ShuffleKind == 1) // unary
1384       return isVMerge(N, UnitSize, 8, 8);
1385     else if (ShuffleKind == 2) // swapped
1386       return isVMerge(N, UnitSize, 8, 24);
1387     else
1388       return false;
1389   } else {
1390     if (ShuffleKind == 1) // unary
1391       return isVMerge(N, UnitSize, 0, 0);
1392     else if (ShuffleKind == 0) // normal
1393       return isVMerge(N, UnitSize, 0, 16);
1394     else
1395       return false;
1396   }
1397 }
1398 
1399 /**
1400  * \brief Common function used to match vmrgew and vmrgow shuffles
1401  *
1402  * The indexOffset determines whether to look for even or odd words in
1403  * the shuffle mask. This is based on the of the endianness of the target
1404  * machine.
1405  *   - Little Endian:
1406  *     - Use offset of 0 to check for odd elements
1407  *     - Use offset of 4 to check for even elements
1408  *   - Big Endian:
1409  *     - Use offset of 0 to check for even elements
1410  *     - Use offset of 4 to check for odd elements
1411  * A detailed description of the vector element ordering for little endian and
1412  * big endian can be found at
1413  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1414  * Targeting your applications - what little endian and big endian IBM XL C/C++
1415  * compiler differences mean to you
1416  *
1417  * The mask to the shuffle vector instruction specifies the indices of the
1418  * elements from the two input vectors to place in the result. The elements are
1419  * numbered in array-access order, starting with the first vector. These vectors
1420  * are always of type v16i8, thus each vector will contain 16 elements of size
1421  * 8. More info on the shuffle vector can be found in the
1422  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1423  * Language Reference.
1424  *
1425  * The RHSStartValue indicates whether the same input vectors are used (unary)
1426  * or two different input vectors are used, based on the following:
1427  *   - If the instruction uses the same vector for both inputs, the range of the
1428  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1429  *     be 0.
1430  *   - If the instruction has two different vectors then the range of the
1431  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1432  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1433  *     to 31 specify elements in the second vector).
1434  *
1435  * \param[in] N The shuffle vector SD Node to analyze
1436  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1437  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1438  * vector to the shuffle_vector instruction
1439  * \return true iff this shuffle vector represents an even or odd word merge
1440  */
1441 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1442                      unsigned RHSStartValue) {
1443   if (N->getValueType(0) != MVT::v16i8)
1444     return false;
1445 
1446   for (unsigned i = 0; i < 2; ++i)
1447     for (unsigned j = 0; j < 4; ++j)
1448       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1449                              i*RHSStartValue+j+IndexOffset) ||
1450           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1451                              i*RHSStartValue+j+IndexOffset+8))
1452         return false;
1453   return true;
1454 }
1455 
1456 /**
1457  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1458  * vmrgow instructions.
1459  *
1460  * \param[in] N The shuffle vector SD Node to analyze
1461  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1462  * \param[in] ShuffleKind Identify the type of merge:
1463  *   - 0 = big-endian merge with two different inputs;
1464  *   - 1 = either-endian merge with two identical inputs;
1465  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1466  *     little-endian merges).
1467  * \param[in] DAG The current SelectionDAG
1468  * \return true iff this shuffle mask
1469  */
1470 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1471                               unsigned ShuffleKind, SelectionDAG &DAG) {
1472   if (DAG.getDataLayout().isLittleEndian()) {
1473     unsigned indexOffset = CheckEven ? 4 : 0;
1474     if (ShuffleKind == 1) // Unary
1475       return isVMerge(N, indexOffset, 0);
1476     else if (ShuffleKind == 2) // swapped
1477       return isVMerge(N, indexOffset, 16);
1478     else
1479       return false;
1480   }
1481   else {
1482     unsigned indexOffset = CheckEven ? 0 : 4;
1483     if (ShuffleKind == 1) // Unary
1484       return isVMerge(N, indexOffset, 0);
1485     else if (ShuffleKind == 0) // Normal
1486       return isVMerge(N, indexOffset, 16);
1487     else
1488       return false;
1489   }
1490   return false;
1491 }
1492 
1493 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1494 /// amount, otherwise return -1.
1495 /// The ShuffleKind distinguishes between big-endian operations with two
1496 /// different inputs (0), either-endian operations with two identical inputs
1497 /// (1), and little-endian operations with two different inputs (2).  For the
1498 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1499 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1500                              SelectionDAG &DAG) {
1501   if (N->getValueType(0) != MVT::v16i8)
1502     return -1;
1503 
1504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1505 
1506   // Find the first non-undef value in the shuffle mask.
1507   unsigned i;
1508   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1509     /*search*/;
1510 
1511   if (i == 16) return -1;  // all undef.
1512 
1513   // Otherwise, check to see if the rest of the elements are consecutively
1514   // numbered from this value.
1515   unsigned ShiftAmt = SVOp->getMaskElt(i);
1516   if (ShiftAmt < i) return -1;
1517 
1518   ShiftAmt -= i;
1519   bool isLE = DAG.getDataLayout().isLittleEndian();
1520 
1521   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1522     // Check the rest of the elements to see if they are consecutive.
1523     for (++i; i != 16; ++i)
1524       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1525         return -1;
1526   } else if (ShuffleKind == 1) {
1527     // Check the rest of the elements to see if they are consecutive.
1528     for (++i; i != 16; ++i)
1529       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1530         return -1;
1531   } else
1532     return -1;
1533 
1534   if (isLE)
1535     ShiftAmt = 16 - ShiftAmt;
1536 
1537   return ShiftAmt;
1538 }
1539 
1540 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1541 /// specifies a splat of a single element that is suitable for input to
1542 /// VSPLTB/VSPLTH/VSPLTW.
1543 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1544   assert(N->getValueType(0) == MVT::v16i8 &&
1545          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1546 
1547   // The consecutive indices need to specify an element, not part of two
1548   // different elements.  So abandon ship early if this isn't the case.
1549   if (N->getMaskElt(0) % EltSize != 0)
1550     return false;
1551 
1552   // This is a splat operation if each element of the permute is the same, and
1553   // if the value doesn't reference the second vector.
1554   unsigned ElementBase = N->getMaskElt(0);
1555 
1556   // FIXME: Handle UNDEF elements too!
1557   if (ElementBase >= 16)
1558     return false;
1559 
1560   // Check that the indices are consecutive, in the case of a multi-byte element
1561   // splatted with a v16i8 mask.
1562   for (unsigned i = 1; i != EltSize; ++i)
1563     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1564       return false;
1565 
1566   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1567     if (N->getMaskElt(i) < 0) continue;
1568     for (unsigned j = 0; j != EltSize; ++j)
1569       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1570         return false;
1571   }
1572   return true;
1573 }
1574 
1575 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1576                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1577   // Check that the mask is shuffling words
1578   for (unsigned i = 0; i < 4; ++i) {
1579     unsigned B0 = N->getMaskElt(i*4);
1580     unsigned B1 = N->getMaskElt(i*4+1);
1581     unsigned B2 = N->getMaskElt(i*4+2);
1582     unsigned B3 = N->getMaskElt(i*4+3);
1583     if (B0 % 4)
1584       return false;
1585     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1586       return false;
1587   }
1588 
1589   // Now we look at mask elements 0,4,8,12
1590   unsigned M0 = N->getMaskElt(0) / 4;
1591   unsigned M1 = N->getMaskElt(4) / 4;
1592   unsigned M2 = N->getMaskElt(8) / 4;
1593   unsigned M3 = N->getMaskElt(12) / 4;
1594   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1595   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1596 
1597   // Below, let H and L be arbitrary elements of the shuffle mask
1598   // where H is in the range [4,7] and L is in the range [0,3].
1599   // H, 1, 2, 3 or L, 5, 6, 7
1600   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1601       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1602     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1603     InsertAtByte = IsLE ? 12 : 0;
1604     Swap = M0 < 4;
1605     return true;
1606   }
1607   // 0, H, 2, 3 or 4, L, 6, 7
1608   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1609       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1610     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1611     InsertAtByte = IsLE ? 8 : 4;
1612     Swap = M1 < 4;
1613     return true;
1614   }
1615   // 0, 1, H, 3 or 4, 5, L, 7
1616   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1617       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1618     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1619     InsertAtByte = IsLE ? 4 : 8;
1620     Swap = M2 < 4;
1621     return true;
1622   }
1623   // 0, 1, 2, H or 4, 5, 6, L
1624   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1625       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1626     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1627     InsertAtByte = IsLE ? 0 : 12;
1628     Swap = M3 < 4;
1629     return true;
1630   }
1631 
1632   // If both vector operands for the shuffle are the same vector, the mask will
1633   // contain only elements from the first one and the second one will be undef.
1634   if (N->getOperand(1).isUndef()) {
1635     ShiftElts = 0;
1636     Swap = true;
1637     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1638     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1639       InsertAtByte = IsLE ? 12 : 0;
1640       return true;
1641     }
1642     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1643       InsertAtByte = IsLE ? 8 : 4;
1644       return true;
1645     }
1646     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1647       InsertAtByte = IsLE ? 4 : 8;
1648       return true;
1649     }
1650     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1651       InsertAtByte = IsLE ? 0 : 12;
1652       return true;
1653     }
1654   }
1655 
1656   return false;
1657 }
1658 
1659 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1660 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1661 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1662                                 SelectionDAG &DAG) {
1663   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1664   assert(isSplatShuffleMask(SVOp, EltSize));
1665   if (DAG.getDataLayout().isLittleEndian())
1666     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1667   else
1668     return SVOp->getMaskElt(0) / EltSize;
1669 }
1670 
1671 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1672 /// by using a vspltis[bhw] instruction of the specified element size, return
1673 /// the constant being splatted.  The ByteSize field indicates the number of
1674 /// bytes of each element [124] -> [bhw].
1675 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1676   SDValue OpVal(nullptr, 0);
1677 
1678   // If ByteSize of the splat is bigger than the element size of the
1679   // build_vector, then we have a case where we are checking for a splat where
1680   // multiple elements of the buildvector are folded together into a single
1681   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1682   unsigned EltSize = 16/N->getNumOperands();
1683   if (EltSize < ByteSize) {
1684     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1685     SDValue UniquedVals[4];
1686     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1687 
1688     // See if all of the elements in the buildvector agree across.
1689     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1690       if (N->getOperand(i).isUndef()) continue;
1691       // If the element isn't a constant, bail fully out.
1692       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1693 
1694       if (!UniquedVals[i&(Multiple-1)].getNode())
1695         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1696       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1697         return SDValue();  // no match.
1698     }
1699 
1700     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1701     // either constant or undef values that are identical for each chunk.  See
1702     // if these chunks can form into a larger vspltis*.
1703 
1704     // Check to see if all of the leading entries are either 0 or -1.  If
1705     // neither, then this won't fit into the immediate field.
1706     bool LeadingZero = true;
1707     bool LeadingOnes = true;
1708     for (unsigned i = 0; i != Multiple-1; ++i) {
1709       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1710 
1711       LeadingZero &= isNullConstant(UniquedVals[i]);
1712       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1713     }
1714     // Finally, check the least significant entry.
1715     if (LeadingZero) {
1716       if (!UniquedVals[Multiple-1].getNode())
1717         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1718       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1719       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1720         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1721     }
1722     if (LeadingOnes) {
1723       if (!UniquedVals[Multiple-1].getNode())
1724         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1725       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1726       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1727         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1728     }
1729 
1730     return SDValue();
1731   }
1732 
1733   // Check to see if this buildvec has a single non-undef value in its elements.
1734   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1735     if (N->getOperand(i).isUndef()) continue;
1736     if (!OpVal.getNode())
1737       OpVal = N->getOperand(i);
1738     else if (OpVal != N->getOperand(i))
1739       return SDValue();
1740   }
1741 
1742   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1743 
1744   unsigned ValSizeInBytes = EltSize;
1745   uint64_t Value = 0;
1746   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1747     Value = CN->getZExtValue();
1748   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1749     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1750     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1751   }
1752 
1753   // If the splat value is larger than the element value, then we can never do
1754   // this splat.  The only case that we could fit the replicated bits into our
1755   // immediate field for would be zero, and we prefer to use vxor for it.
1756   if (ValSizeInBytes < ByteSize) return SDValue();
1757 
1758   // If the element value is larger than the splat value, check if it consists
1759   // of a repeated bit pattern of size ByteSize.
1760   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1761     return SDValue();
1762 
1763   // Properly sign extend the value.
1764   int MaskVal = SignExtend32(Value, ByteSize * 8);
1765 
1766   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1767   if (MaskVal == 0) return SDValue();
1768 
1769   // Finally, if this value fits in a 5 bit sext field, return it
1770   if (SignExtend32<5>(MaskVal) == MaskVal)
1771     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1772   return SDValue();
1773 }
1774 
1775 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1776 /// amount, otherwise return -1.
1777 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1778   EVT VT = N->getValueType(0);
1779   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1780     return -1;
1781 
1782   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1783 
1784   // Find the first non-undef value in the shuffle mask.
1785   unsigned i;
1786   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1787     /*search*/;
1788 
1789   if (i == 4) return -1;  // all undef.
1790 
1791   // Otherwise, check to see if the rest of the elements are consecutively
1792   // numbered from this value.
1793   unsigned ShiftAmt = SVOp->getMaskElt(i);
1794   if (ShiftAmt < i) return -1;
1795   ShiftAmt -= i;
1796 
1797   // Check the rest of the elements to see if they are consecutive.
1798   for (++i; i != 4; ++i)
1799     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1800       return -1;
1801 
1802   return ShiftAmt;
1803 }
1804 
1805 //===----------------------------------------------------------------------===//
1806 //  Addressing Mode Selection
1807 //===----------------------------------------------------------------------===//
1808 
1809 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1810 /// or 64-bit immediate, and if the value can be accurately represented as a
1811 /// sign extension from a 16-bit value.  If so, this returns true and the
1812 /// immediate.
1813 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1814   if (!isa<ConstantSDNode>(N))
1815     return false;
1816 
1817   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1818   if (N->getValueType(0) == MVT::i32)
1819     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1820   else
1821     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1822 }
1823 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1824   return isIntS16Immediate(Op.getNode(), Imm);
1825 }
1826 
1827 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1828 /// can be represented as an indexed [r+r] operation.  Returns false if it
1829 /// can be more efficiently represented with [r+imm].
1830 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1831                                             SDValue &Index,
1832                                             SelectionDAG &DAG) const {
1833   short imm = 0;
1834   if (N.getOpcode() == ISD::ADD) {
1835     if (isIntS16Immediate(N.getOperand(1), imm))
1836       return false;    // r+i
1837     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1838       return false;    // r+i
1839 
1840     Base = N.getOperand(0);
1841     Index = N.getOperand(1);
1842     return true;
1843   } else if (N.getOpcode() == ISD::OR) {
1844     if (isIntS16Immediate(N.getOperand(1), imm))
1845       return false;    // r+i can fold it if we can.
1846 
1847     // If this is an or of disjoint bitfields, we can codegen this as an add
1848     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1849     // disjoint.
1850     APInt LHSKnownZero, LHSKnownOne;
1851     APInt RHSKnownZero, RHSKnownOne;
1852     DAG.computeKnownBits(N.getOperand(0),
1853                          LHSKnownZero, LHSKnownOne);
1854 
1855     if (LHSKnownZero.getBoolValue()) {
1856       DAG.computeKnownBits(N.getOperand(1),
1857                            RHSKnownZero, RHSKnownOne);
1858       // If all of the bits are known zero on the LHS or RHS, the add won't
1859       // carry.
1860       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1861         Base = N.getOperand(0);
1862         Index = N.getOperand(1);
1863         return true;
1864       }
1865     }
1866   }
1867 
1868   return false;
1869 }
1870 
1871 // If we happen to be doing an i64 load or store into a stack slot that has
1872 // less than a 4-byte alignment, then the frame-index elimination may need to
1873 // use an indexed load or store instruction (because the offset may not be a
1874 // multiple of 4). The extra register needed to hold the offset comes from the
1875 // register scavenger, and it is possible that the scavenger will need to use
1876 // an emergency spill slot. As a result, we need to make sure that a spill slot
1877 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1878 // stack slot.
1879 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1880   // FIXME: This does not handle the LWA case.
1881   if (VT != MVT::i64)
1882     return;
1883 
1884   // NOTE: We'll exclude negative FIs here, which come from argument
1885   // lowering, because there are no known test cases triggering this problem
1886   // using packed structures (or similar). We can remove this exclusion if
1887   // we find such a test case. The reason why this is so test-case driven is
1888   // because this entire 'fixup' is only to prevent crashes (from the
1889   // register scavenger) on not-really-valid inputs. For example, if we have:
1890   //   %a = alloca i1
1891   //   %b = bitcast i1* %a to i64*
1892   //   store i64* a, i64 b
1893   // then the store should really be marked as 'align 1', but is not. If it
1894   // were marked as 'align 1' then the indexed form would have been
1895   // instruction-selected initially, and the problem this 'fixup' is preventing
1896   // won't happen regardless.
1897   if (FrameIdx < 0)
1898     return;
1899 
1900   MachineFunction &MF = DAG.getMachineFunction();
1901   MachineFrameInfo &MFI = MF.getFrameInfo();
1902 
1903   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1904   if (Align >= 4)
1905     return;
1906 
1907   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1908   FuncInfo->setHasNonRISpills();
1909 }
1910 
1911 /// Returns true if the address N can be represented by a base register plus
1912 /// a signed 16-bit displacement [r+imm], and if it is not better
1913 /// represented as reg+reg.  If Aligned is true, only accept displacements
1914 /// suitable for STD and friends, i.e. multiples of 4.
1915 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1916                                             SDValue &Base,
1917                                             SelectionDAG &DAG,
1918                                             bool Aligned) const {
1919   // FIXME dl should come from parent load or store, not from address
1920   SDLoc dl(N);
1921   // If this can be more profitably realized as r+r, fail.
1922   if (SelectAddressRegReg(N, Disp, Base, DAG))
1923     return false;
1924 
1925   if (N.getOpcode() == ISD::ADD) {
1926     short imm = 0;
1927     if (isIntS16Immediate(N.getOperand(1), imm) &&
1928         (!Aligned || (imm & 3) == 0)) {
1929       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1930       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1931         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1932         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1933       } else {
1934         Base = N.getOperand(0);
1935       }
1936       return true; // [r+i]
1937     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1938       // Match LOAD (ADD (X, Lo(G))).
1939       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1940              && "Cannot handle constant offsets yet!");
1941       Disp = N.getOperand(1).getOperand(0);  // The global address.
1942       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1943              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1944              Disp.getOpcode() == ISD::TargetConstantPool ||
1945              Disp.getOpcode() == ISD::TargetJumpTable);
1946       Base = N.getOperand(0);
1947       return true;  // [&g+r]
1948     }
1949   } else if (N.getOpcode() == ISD::OR) {
1950     short imm = 0;
1951     if (isIntS16Immediate(N.getOperand(1), imm) &&
1952         (!Aligned || (imm & 3) == 0)) {
1953       // If this is an or of disjoint bitfields, we can codegen this as an add
1954       // (for better address arithmetic) if the LHS and RHS of the OR are
1955       // provably disjoint.
1956       APInt LHSKnownZero, LHSKnownOne;
1957       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1958 
1959       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1960         // If all of the bits are known zero on the LHS or RHS, the add won't
1961         // carry.
1962         if (FrameIndexSDNode *FI =
1963               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1964           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1965           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1966         } else {
1967           Base = N.getOperand(0);
1968         }
1969         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1970         return true;
1971       }
1972     }
1973   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1974     // Loading from a constant address.
1975 
1976     // If this address fits entirely in a 16-bit sext immediate field, codegen
1977     // this as "d, 0"
1978     short Imm;
1979     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1980       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1981       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1982                              CN->getValueType(0));
1983       return true;
1984     }
1985 
1986     // Handle 32-bit sext immediates with LIS + addr mode.
1987     if ((CN->getValueType(0) == MVT::i32 ||
1988          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1989         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1990       int Addr = (int)CN->getZExtValue();
1991 
1992       // Otherwise, break this down into an LIS + disp.
1993       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1994 
1995       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1996                                    MVT::i32);
1997       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1998       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1999       return true;
2000     }
2001   }
2002 
2003   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2004   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2005     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2006     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2007   } else
2008     Base = N;
2009   return true;      // [r+0]
2010 }
2011 
2012 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2013 /// represented as an indexed [r+r] operation.
2014 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2015                                                 SDValue &Index,
2016                                                 SelectionDAG &DAG) const {
2017   // Check to see if we can easily represent this as an [r+r] address.  This
2018   // will fail if it thinks that the address is more profitably represented as
2019   // reg+imm, e.g. where imm = 0.
2020   if (SelectAddressRegReg(N, Base, Index, DAG))
2021     return true;
2022 
2023   // If the operand is an addition, always emit this as [r+r], since this is
2024   // better (for code size, and execution, as the memop does the add for free)
2025   // than emitting an explicit add.
2026   if (N.getOpcode() == ISD::ADD) {
2027     Base = N.getOperand(0);
2028     Index = N.getOperand(1);
2029     return true;
2030   }
2031 
2032   // Otherwise, do it the hard way, using R0 as the base register.
2033   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2034                          N.getValueType());
2035   Index = N;
2036   return true;
2037 }
2038 
2039 /// getPreIndexedAddressParts - returns true by value, base pointer and
2040 /// offset pointer and addressing mode by reference if the node's address
2041 /// can be legally represented as pre-indexed load / store address.
2042 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2043                                                   SDValue &Offset,
2044                                                   ISD::MemIndexedMode &AM,
2045                                                   SelectionDAG &DAG) const {
2046   if (DisablePPCPreinc) return false;
2047 
2048   bool isLoad = true;
2049   SDValue Ptr;
2050   EVT VT;
2051   unsigned Alignment;
2052   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2053     Ptr = LD->getBasePtr();
2054     VT = LD->getMemoryVT();
2055     Alignment = LD->getAlignment();
2056   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2057     Ptr = ST->getBasePtr();
2058     VT  = ST->getMemoryVT();
2059     Alignment = ST->getAlignment();
2060     isLoad = false;
2061   } else
2062     return false;
2063 
2064   // PowerPC doesn't have preinc load/store instructions for vectors (except
2065   // for QPX, which does have preinc r+r forms).
2066   if (VT.isVector()) {
2067     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2068       return false;
2069     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2070       AM = ISD::PRE_INC;
2071       return true;
2072     }
2073   }
2074 
2075   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2076     // Common code will reject creating a pre-inc form if the base pointer
2077     // is a frame index, or if N is a store and the base pointer is either
2078     // the same as or a predecessor of the value being stored.  Check for
2079     // those situations here, and try with swapped Base/Offset instead.
2080     bool Swap = false;
2081 
2082     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2083       Swap = true;
2084     else if (!isLoad) {
2085       SDValue Val = cast<StoreSDNode>(N)->getValue();
2086       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2087         Swap = true;
2088     }
2089 
2090     if (Swap)
2091       std::swap(Base, Offset);
2092 
2093     AM = ISD::PRE_INC;
2094     return true;
2095   }
2096 
2097   // LDU/STU can only handle immediates that are a multiple of 4.
2098   if (VT != MVT::i64) {
2099     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2100       return false;
2101   } else {
2102     // LDU/STU need an address with at least 4-byte alignment.
2103     if (Alignment < 4)
2104       return false;
2105 
2106     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2107       return false;
2108   }
2109 
2110   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2111     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2112     // sext i32 to i64 when addr mode is r+i.
2113     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2114         LD->getExtensionType() == ISD::SEXTLOAD &&
2115         isa<ConstantSDNode>(Offset))
2116       return false;
2117   }
2118 
2119   AM = ISD::PRE_INC;
2120   return true;
2121 }
2122 
2123 //===----------------------------------------------------------------------===//
2124 //  LowerOperation implementation
2125 //===----------------------------------------------------------------------===//
2126 
2127 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2128 /// and LoOpFlags to the target MO flags.
2129 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2130                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2131                                const GlobalValue *GV = nullptr) {
2132   HiOpFlags = PPCII::MO_HA;
2133   LoOpFlags = PPCII::MO_LO;
2134 
2135   // Don't use the pic base if not in PIC relocation model.
2136   if (IsPIC) {
2137     HiOpFlags |= PPCII::MO_PIC_FLAG;
2138     LoOpFlags |= PPCII::MO_PIC_FLAG;
2139   }
2140 
2141   // If this is a reference to a global value that requires a non-lazy-ptr, make
2142   // sure that instruction lowering adds it.
2143   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2144     HiOpFlags |= PPCII::MO_NLP_FLAG;
2145     LoOpFlags |= PPCII::MO_NLP_FLAG;
2146 
2147     if (GV->hasHiddenVisibility()) {
2148       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2149       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2150     }
2151   }
2152 }
2153 
2154 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2155                              SelectionDAG &DAG) {
2156   SDLoc DL(HiPart);
2157   EVT PtrVT = HiPart.getValueType();
2158   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2159 
2160   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2161   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2162 
2163   // With PIC, the first instruction is actually "GR+hi(&G)".
2164   if (isPIC)
2165     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2166                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2167 
2168   // Generate non-pic code that has direct accesses to the constant pool.
2169   // The address of the global is just (hi(&g)+lo(&g)).
2170   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2171 }
2172 
2173 static void setUsesTOCBasePtr(MachineFunction &MF) {
2174   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2175   FuncInfo->setUsesTOCBasePtr();
2176 }
2177 
2178 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2179   setUsesTOCBasePtr(DAG.getMachineFunction());
2180 }
2181 
2182 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2183                            SDValue GA) {
2184   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2185   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2186                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2187 
2188   SDValue Ops[] = { GA, Reg };
2189   return DAG.getMemIntrinsicNode(
2190       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2191       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2192       false, 0);
2193 }
2194 
2195 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2196                                              SelectionDAG &DAG) const {
2197   EVT PtrVT = Op.getValueType();
2198   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2199   const Constant *C = CP->getConstVal();
2200 
2201   // 64-bit SVR4 ABI code is always position-independent.
2202   // The actual address of the GlobalValue is stored in the TOC.
2203   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2204     setUsesTOCBasePtr(DAG);
2205     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2206     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2207   }
2208 
2209   unsigned MOHiFlag, MOLoFlag;
2210   bool IsPIC = isPositionIndependent();
2211   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2212 
2213   if (IsPIC && Subtarget.isSVR4ABI()) {
2214     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2215                                            PPCII::MO_PIC_FLAG);
2216     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2217   }
2218 
2219   SDValue CPIHi =
2220     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2221   SDValue CPILo =
2222     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2223   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2224 }
2225 
2226 // For 64-bit PowerPC, prefer the more compact relative encodings.
2227 // This trades 32 bits per jump table entry for one or two instructions
2228 // on the jump site.
2229 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2230   if (isJumpTableRelative())
2231     return MachineJumpTableInfo::EK_LabelDifference32;
2232 
2233   return TargetLowering::getJumpTableEncoding();
2234 }
2235 
2236 bool PPCTargetLowering::isJumpTableRelative() const {
2237   if (Subtarget.isPPC64())
2238     return true;
2239   return TargetLowering::isJumpTableRelative();
2240 }
2241 
2242 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2243                                                     SelectionDAG &DAG) const {
2244   if (!Subtarget.isPPC64())
2245     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2246 
2247   switch (getTargetMachine().getCodeModel()) {
2248   case CodeModel::Default:
2249   case CodeModel::Small:
2250   case CodeModel::Medium:
2251     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2252   default:
2253     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2254                        getPointerTy(DAG.getDataLayout()));
2255   }
2256 }
2257 
2258 const MCExpr *
2259 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2260                                                 unsigned JTI,
2261                                                 MCContext &Ctx) const {
2262   if (!Subtarget.isPPC64())
2263     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2264 
2265   switch (getTargetMachine().getCodeModel()) {
2266   case CodeModel::Default:
2267   case CodeModel::Small:
2268   case CodeModel::Medium:
2269     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2270   default:
2271     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2272   }
2273 }
2274 
2275 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2276   EVT PtrVT = Op.getValueType();
2277   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2278 
2279   // 64-bit SVR4 ABI code is always position-independent.
2280   // The actual address of the GlobalValue is stored in the TOC.
2281   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2282     setUsesTOCBasePtr(DAG);
2283     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2284     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2285   }
2286 
2287   unsigned MOHiFlag, MOLoFlag;
2288   bool IsPIC = isPositionIndependent();
2289   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2290 
2291   if (IsPIC && Subtarget.isSVR4ABI()) {
2292     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2293                                         PPCII::MO_PIC_FLAG);
2294     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2295   }
2296 
2297   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2298   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2299   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2300 }
2301 
2302 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2303                                              SelectionDAG &DAG) const {
2304   EVT PtrVT = Op.getValueType();
2305   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2306   const BlockAddress *BA = BASDN->getBlockAddress();
2307 
2308   // 64-bit SVR4 ABI code is always position-independent.
2309   // The actual BlockAddress is stored in the TOC.
2310   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2311     setUsesTOCBasePtr(DAG);
2312     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2313     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2314   }
2315 
2316   unsigned MOHiFlag, MOLoFlag;
2317   bool IsPIC = isPositionIndependent();
2318   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2319   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2320   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2321   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2322 }
2323 
2324 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2325                                               SelectionDAG &DAG) const {
2326   // FIXME: TLS addresses currently use medium model code sequences,
2327   // which is the most useful form.  Eventually support for small and
2328   // large models could be added if users need it, at the cost of
2329   // additional complexity.
2330   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2331   if (DAG.getTarget().Options.EmulatedTLS)
2332     return LowerToTLSEmulatedModel(GA, DAG);
2333 
2334   SDLoc dl(GA);
2335   const GlobalValue *GV = GA->getGlobal();
2336   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2337   bool is64bit = Subtarget.isPPC64();
2338   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2339   PICLevel::Level picLevel = M->getPICLevel();
2340 
2341   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2342 
2343   if (Model == TLSModel::LocalExec) {
2344     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2345                                                PPCII::MO_TPREL_HA);
2346     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2347                                                PPCII::MO_TPREL_LO);
2348     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2349                                      is64bit ? MVT::i64 : MVT::i32);
2350     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2351     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2352   }
2353 
2354   if (Model == TLSModel::InitialExec) {
2355     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2356     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2357                                                 PPCII::MO_TLS);
2358     SDValue GOTPtr;
2359     if (is64bit) {
2360       setUsesTOCBasePtr(DAG);
2361       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2362       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2363                            PtrVT, GOTReg, TGA);
2364     } else
2365       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2366     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2367                                    PtrVT, TGA, GOTPtr);
2368     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2369   }
2370 
2371   if (Model == TLSModel::GeneralDynamic) {
2372     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2373     SDValue GOTPtr;
2374     if (is64bit) {
2375       setUsesTOCBasePtr(DAG);
2376       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2377       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2378                                    GOTReg, TGA);
2379     } else {
2380       if (picLevel == PICLevel::SmallPIC)
2381         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2382       else
2383         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2384     }
2385     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2386                        GOTPtr, TGA, TGA);
2387   }
2388 
2389   if (Model == TLSModel::LocalDynamic) {
2390     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2391     SDValue GOTPtr;
2392     if (is64bit) {
2393       setUsesTOCBasePtr(DAG);
2394       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2395       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2396                            GOTReg, TGA);
2397     } else {
2398       if (picLevel == PICLevel::SmallPIC)
2399         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2400       else
2401         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2402     }
2403     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2404                                   PtrVT, GOTPtr, TGA, TGA);
2405     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2406                                       PtrVT, TLSAddr, TGA);
2407     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2408   }
2409 
2410   llvm_unreachable("Unknown TLS model!");
2411 }
2412 
2413 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2414                                               SelectionDAG &DAG) const {
2415   EVT PtrVT = Op.getValueType();
2416   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2417   SDLoc DL(GSDN);
2418   const GlobalValue *GV = GSDN->getGlobal();
2419 
2420   // 64-bit SVR4 ABI code is always position-independent.
2421   // The actual address of the GlobalValue is stored in the TOC.
2422   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2423     setUsesTOCBasePtr(DAG);
2424     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2425     return getTOCEntry(DAG, DL, true, GA);
2426   }
2427 
2428   unsigned MOHiFlag, MOLoFlag;
2429   bool IsPIC = isPositionIndependent();
2430   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2431 
2432   if (IsPIC && Subtarget.isSVR4ABI()) {
2433     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2434                                             GSDN->getOffset(),
2435                                             PPCII::MO_PIC_FLAG);
2436     return getTOCEntry(DAG, DL, false, GA);
2437   }
2438 
2439   SDValue GAHi =
2440     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2441   SDValue GALo =
2442     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2443 
2444   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2445 
2446   // If the global reference is actually to a non-lazy-pointer, we have to do an
2447   // extra load to get the address of the global.
2448   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2449     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2450   return Ptr;
2451 }
2452 
2453 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2454   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2455   SDLoc dl(Op);
2456 
2457   if (Op.getValueType() == MVT::v2i64) {
2458     // When the operands themselves are v2i64 values, we need to do something
2459     // special because VSX has no underlying comparison operations for these.
2460     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2461       // Equality can be handled by casting to the legal type for Altivec
2462       // comparisons, everything else needs to be expanded.
2463       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2464         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2465                  DAG.getSetCC(dl, MVT::v4i32,
2466                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2467                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2468                    CC));
2469       }
2470 
2471       return SDValue();
2472     }
2473 
2474     // We handle most of these in the usual way.
2475     return Op;
2476   }
2477 
2478   // If we're comparing for equality to zero, expose the fact that this is
2479   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2480   // fold the new nodes.
2481   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2482     return V;
2483 
2484   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2485     // Leave comparisons against 0 and -1 alone for now, since they're usually
2486     // optimized.  FIXME: revisit this when we can custom lower all setcc
2487     // optimizations.
2488     if (C->isAllOnesValue() || C->isNullValue())
2489       return SDValue();
2490   }
2491 
2492   // If we have an integer seteq/setne, turn it into a compare against zero
2493   // by xor'ing the rhs with the lhs, which is faster than setting a
2494   // condition register, reading it back out, and masking the correct bit.  The
2495   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2496   // the result to other bit-twiddling opportunities.
2497   EVT LHSVT = Op.getOperand(0).getValueType();
2498   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2499     EVT VT = Op.getValueType();
2500     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2501                                 Op.getOperand(1));
2502     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2503   }
2504   return SDValue();
2505 }
2506 
2507 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2508   SDNode *Node = Op.getNode();
2509   EVT VT = Node->getValueType(0);
2510   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2511   SDValue InChain = Node->getOperand(0);
2512   SDValue VAListPtr = Node->getOperand(1);
2513   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2514   SDLoc dl(Node);
2515 
2516   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2517 
2518   // gpr_index
2519   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2520                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2521   InChain = GprIndex.getValue(1);
2522 
2523   if (VT == MVT::i64) {
2524     // Check if GprIndex is even
2525     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2526                                  DAG.getConstant(1, dl, MVT::i32));
2527     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2528                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2529     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2530                                           DAG.getConstant(1, dl, MVT::i32));
2531     // Align GprIndex to be even if it isn't
2532     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2533                            GprIndex);
2534   }
2535 
2536   // fpr index is 1 byte after gpr
2537   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2538                                DAG.getConstant(1, dl, MVT::i32));
2539 
2540   // fpr
2541   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2542                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2543   InChain = FprIndex.getValue(1);
2544 
2545   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2546                                        DAG.getConstant(8, dl, MVT::i32));
2547 
2548   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2549                                         DAG.getConstant(4, dl, MVT::i32));
2550 
2551   // areas
2552   SDValue OverflowArea =
2553       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2554   InChain = OverflowArea.getValue(1);
2555 
2556   SDValue RegSaveArea =
2557       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2558   InChain = RegSaveArea.getValue(1);
2559 
2560   // select overflow_area if index > 8
2561   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2562                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2563 
2564   // adjustment constant gpr_index * 4/8
2565   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2566                                     VT.isInteger() ? GprIndex : FprIndex,
2567                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2568                                                     MVT::i32));
2569 
2570   // OurReg = RegSaveArea + RegConstant
2571   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2572                                RegConstant);
2573 
2574   // Floating types are 32 bytes into RegSaveArea
2575   if (VT.isFloatingPoint())
2576     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2577                          DAG.getConstant(32, dl, MVT::i32));
2578 
2579   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2580   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2581                                    VT.isInteger() ? GprIndex : FprIndex,
2582                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2583                                                    MVT::i32));
2584 
2585   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2586                               VT.isInteger() ? VAListPtr : FprPtr,
2587                               MachinePointerInfo(SV), MVT::i8);
2588 
2589   // determine if we should load from reg_save_area or overflow_area
2590   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2591 
2592   // increase overflow_area by 4/8 if gpr/fpr > 8
2593   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2594                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2595                                           dl, MVT::i32));
2596 
2597   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2598                              OverflowAreaPlusN);
2599 
2600   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2601                               MachinePointerInfo(), MVT::i32);
2602 
2603   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2604 }
2605 
2606 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2607   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2608 
2609   // We have to copy the entire va_list struct:
2610   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2611   return DAG.getMemcpy(Op.getOperand(0), Op,
2612                        Op.getOperand(1), Op.getOperand(2),
2613                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2614                        false, MachinePointerInfo(), MachinePointerInfo());
2615 }
2616 
2617 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2618                                                   SelectionDAG &DAG) const {
2619   return Op.getOperand(0);
2620 }
2621 
2622 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2623                                                 SelectionDAG &DAG) const {
2624   SDValue Chain = Op.getOperand(0);
2625   SDValue Trmp = Op.getOperand(1); // trampoline
2626   SDValue FPtr = Op.getOperand(2); // nested function
2627   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2628   SDLoc dl(Op);
2629 
2630   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2631   bool isPPC64 = (PtrVT == MVT::i64);
2632   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2633 
2634   TargetLowering::ArgListTy Args;
2635   TargetLowering::ArgListEntry Entry;
2636 
2637   Entry.Ty = IntPtrTy;
2638   Entry.Node = Trmp; Args.push_back(Entry);
2639 
2640   // TrampSize == (isPPC64 ? 48 : 40);
2641   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2642                                isPPC64 ? MVT::i64 : MVT::i32);
2643   Args.push_back(Entry);
2644 
2645   Entry.Node = FPtr; Args.push_back(Entry);
2646   Entry.Node = Nest; Args.push_back(Entry);
2647 
2648   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2649   TargetLowering::CallLoweringInfo CLI(DAG);
2650   CLI.setDebugLoc(dl).setChain(Chain)
2651     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2652                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2653                std::move(Args));
2654 
2655   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2656   return CallResult.second;
2657 }
2658 
2659 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2660   MachineFunction &MF = DAG.getMachineFunction();
2661   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2662   EVT PtrVT = getPointerTy(MF.getDataLayout());
2663 
2664   SDLoc dl(Op);
2665 
2666   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2667     // vastart just stores the address of the VarArgsFrameIndex slot into the
2668     // memory location argument.
2669     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2670     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2671     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2672                         MachinePointerInfo(SV));
2673   }
2674 
2675   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2676   // We suppose the given va_list is already allocated.
2677   //
2678   // typedef struct {
2679   //  char gpr;     /* index into the array of 8 GPRs
2680   //                 * stored in the register save area
2681   //                 * gpr=0 corresponds to r3,
2682   //                 * gpr=1 to r4, etc.
2683   //                 */
2684   //  char fpr;     /* index into the array of 8 FPRs
2685   //                 * stored in the register save area
2686   //                 * fpr=0 corresponds to f1,
2687   //                 * fpr=1 to f2, etc.
2688   //                 */
2689   //  char *overflow_arg_area;
2690   //                /* location on stack that holds
2691   //                 * the next overflow argument
2692   //                 */
2693   //  char *reg_save_area;
2694   //               /* where r3:r10 and f1:f8 (if saved)
2695   //                * are stored
2696   //                */
2697   // } va_list[1];
2698 
2699   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2700   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2701   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2702                                             PtrVT);
2703   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2704                                  PtrVT);
2705 
2706   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2707   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2708 
2709   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2710   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2711 
2712   uint64_t FPROffset = 1;
2713   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2714 
2715   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2716 
2717   // Store first byte : number of int regs
2718   SDValue firstStore =
2719       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2720                         MachinePointerInfo(SV), MVT::i8);
2721   uint64_t nextOffset = FPROffset;
2722   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2723                                   ConstFPROffset);
2724 
2725   // Store second byte : number of float regs
2726   SDValue secondStore =
2727       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2728                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2729   nextOffset += StackOffset;
2730   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2731 
2732   // Store second word : arguments given on stack
2733   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2734                                     MachinePointerInfo(SV, nextOffset));
2735   nextOffset += FrameOffset;
2736   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2737 
2738   // Store third word : arguments given in registers
2739   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2740                       MachinePointerInfo(SV, nextOffset));
2741 }
2742 
2743 #include "PPCGenCallingConv.inc"
2744 
2745 // Function whose sole purpose is to kill compiler warnings
2746 // stemming from unused functions included from PPCGenCallingConv.inc.
2747 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2748   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2749 }
2750 
2751 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2752                                       CCValAssign::LocInfo &LocInfo,
2753                                       ISD::ArgFlagsTy &ArgFlags,
2754                                       CCState &State) {
2755   return true;
2756 }
2757 
2758 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2759                                              MVT &LocVT,
2760                                              CCValAssign::LocInfo &LocInfo,
2761                                              ISD::ArgFlagsTy &ArgFlags,
2762                                              CCState &State) {
2763   static const MCPhysReg ArgRegs[] = {
2764     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2765     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2766   };
2767   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2768 
2769   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2770 
2771   // Skip one register if the first unallocated register has an even register
2772   // number and there are still argument registers available which have not been
2773   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2774   // need to skip a register if RegNum is odd.
2775   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2776     State.AllocateReg(ArgRegs[RegNum]);
2777   }
2778 
2779   // Always return false here, as this function only makes sure that the first
2780   // unallocated register has an odd register number and does not actually
2781   // allocate a register for the current argument.
2782   return false;
2783 }
2784 
2785 bool
2786 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2787                                                   MVT &LocVT,
2788                                                   CCValAssign::LocInfo &LocInfo,
2789                                                   ISD::ArgFlagsTy &ArgFlags,
2790                                                   CCState &State) {
2791   static const MCPhysReg ArgRegs[] = {
2792     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2793     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2794   };
2795   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2796 
2797   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2798   int RegsLeft = NumArgRegs - RegNum;
2799 
2800   // Skip if there is not enough registers left for long double type (4 gpr regs
2801   // in soft float mode) and put long double argument on the stack.
2802   if (RegNum != NumArgRegs && RegsLeft < 4) {
2803     for (int i = 0; i < RegsLeft; i++) {
2804       State.AllocateReg(ArgRegs[RegNum + i]);
2805     }
2806   }
2807 
2808   return false;
2809 }
2810 
2811 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2812                                                MVT &LocVT,
2813                                                CCValAssign::LocInfo &LocInfo,
2814                                                ISD::ArgFlagsTy &ArgFlags,
2815                                                CCState &State) {
2816   static const MCPhysReg ArgRegs[] = {
2817     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2818     PPC::F8
2819   };
2820 
2821   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2822 
2823   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2824 
2825   // If there is only one Floating-point register left we need to put both f64
2826   // values of a split ppc_fp128 value on the stack.
2827   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2828     State.AllocateReg(ArgRegs[RegNum]);
2829   }
2830 
2831   // Always return false here, as this function only makes sure that the two f64
2832   // values a ppc_fp128 value is split into are both passed in registers or both
2833   // passed on the stack and does not actually allocate a register for the
2834   // current argument.
2835   return false;
2836 }
2837 
2838 /// FPR - The set of FP registers that should be allocated for arguments,
2839 /// on Darwin.
2840 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2841                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2842                                 PPC::F11, PPC::F12, PPC::F13};
2843 
2844 /// QFPR - The set of QPX registers that should be allocated for arguments.
2845 static const MCPhysReg QFPR[] = {
2846     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2847     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2848 
2849 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2850 /// the stack.
2851 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2852                                        unsigned PtrByteSize) {
2853   unsigned ArgSize = ArgVT.getStoreSize();
2854   if (Flags.isByVal())
2855     ArgSize = Flags.getByValSize();
2856 
2857   // Round up to multiples of the pointer size, except for array members,
2858   // which are always packed.
2859   if (!Flags.isInConsecutiveRegs())
2860     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2861 
2862   return ArgSize;
2863 }
2864 
2865 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2866 /// on the stack.
2867 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2868                                             ISD::ArgFlagsTy Flags,
2869                                             unsigned PtrByteSize) {
2870   unsigned Align = PtrByteSize;
2871 
2872   // Altivec parameters are padded to a 16 byte boundary.
2873   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2874       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2875       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2876       ArgVT == MVT::v1i128)
2877     Align = 16;
2878   // QPX vector types stored in double-precision are padded to a 32 byte
2879   // boundary.
2880   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2881     Align = 32;
2882 
2883   // ByVal parameters are aligned as requested.
2884   if (Flags.isByVal()) {
2885     unsigned BVAlign = Flags.getByValAlign();
2886     if (BVAlign > PtrByteSize) {
2887       if (BVAlign % PtrByteSize != 0)
2888           llvm_unreachable(
2889             "ByVal alignment is not a multiple of the pointer size");
2890 
2891       Align = BVAlign;
2892     }
2893   }
2894 
2895   // Array members are always packed to their original alignment.
2896   if (Flags.isInConsecutiveRegs()) {
2897     // If the array member was split into multiple registers, the first
2898     // needs to be aligned to the size of the full type.  (Except for
2899     // ppcf128, which is only aligned as its f64 components.)
2900     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2901       Align = OrigVT.getStoreSize();
2902     else
2903       Align = ArgVT.getStoreSize();
2904   }
2905 
2906   return Align;
2907 }
2908 
2909 /// CalculateStackSlotUsed - Return whether this argument will use its
2910 /// stack slot (instead of being passed in registers).  ArgOffset,
2911 /// AvailableFPRs, and AvailableVRs must hold the current argument
2912 /// position, and will be updated to account for this argument.
2913 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2914                                    ISD::ArgFlagsTy Flags,
2915                                    unsigned PtrByteSize,
2916                                    unsigned LinkageSize,
2917                                    unsigned ParamAreaSize,
2918                                    unsigned &ArgOffset,
2919                                    unsigned &AvailableFPRs,
2920                                    unsigned &AvailableVRs, bool HasQPX) {
2921   bool UseMemory = false;
2922 
2923   // Respect alignment of argument on the stack.
2924   unsigned Align =
2925     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2926   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2927   // If there's no space left in the argument save area, we must
2928   // use memory (this check also catches zero-sized arguments).
2929   if (ArgOffset >= LinkageSize + ParamAreaSize)
2930     UseMemory = true;
2931 
2932   // Allocate argument on the stack.
2933   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2934   if (Flags.isInConsecutiveRegsLast())
2935     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2936   // If we overran the argument save area, we must use memory
2937   // (this check catches arguments passed partially in memory)
2938   if (ArgOffset > LinkageSize + ParamAreaSize)
2939     UseMemory = true;
2940 
2941   // However, if the argument is actually passed in an FPR or a VR,
2942   // we don't use memory after all.
2943   if (!Flags.isByVal()) {
2944     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2945         // QPX registers overlap with the scalar FP registers.
2946         (HasQPX && (ArgVT == MVT::v4f32 ||
2947                     ArgVT == MVT::v4f64 ||
2948                     ArgVT == MVT::v4i1)))
2949       if (AvailableFPRs > 0) {
2950         --AvailableFPRs;
2951         return false;
2952       }
2953     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2954         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2955         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2956         ArgVT == MVT::v1i128)
2957       if (AvailableVRs > 0) {
2958         --AvailableVRs;
2959         return false;
2960       }
2961   }
2962 
2963   return UseMemory;
2964 }
2965 
2966 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2967 /// ensure minimum alignment required for target.
2968 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2969                                      unsigned NumBytes) {
2970   unsigned TargetAlign = Lowering->getStackAlignment();
2971   unsigned AlignMask = TargetAlign - 1;
2972   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2973   return NumBytes;
2974 }
2975 
2976 SDValue PPCTargetLowering::LowerFormalArguments(
2977     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2978     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2979     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2980   if (Subtarget.isSVR4ABI()) {
2981     if (Subtarget.isPPC64())
2982       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2983                                          dl, DAG, InVals);
2984     else
2985       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2986                                          dl, DAG, InVals);
2987   } else {
2988     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2989                                        dl, DAG, InVals);
2990   }
2991 }
2992 
2993 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2994     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2995     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2996     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2997 
2998   // 32-bit SVR4 ABI Stack Frame Layout:
2999   //              +-----------------------------------+
3000   //        +-->  |            Back chain             |
3001   //        |     +-----------------------------------+
3002   //        |     | Floating-point register save area |
3003   //        |     +-----------------------------------+
3004   //        |     |    General register save area     |
3005   //        |     +-----------------------------------+
3006   //        |     |          CR save word             |
3007   //        |     +-----------------------------------+
3008   //        |     |         VRSAVE save word          |
3009   //        |     +-----------------------------------+
3010   //        |     |         Alignment padding         |
3011   //        |     +-----------------------------------+
3012   //        |     |     Vector register save area     |
3013   //        |     +-----------------------------------+
3014   //        |     |       Local variable space        |
3015   //        |     +-----------------------------------+
3016   //        |     |        Parameter list area        |
3017   //        |     +-----------------------------------+
3018   //        |     |           LR save word            |
3019   //        |     +-----------------------------------+
3020   // SP-->  +---  |            Back chain             |
3021   //              +-----------------------------------+
3022   //
3023   // Specifications:
3024   //   System V Application Binary Interface PowerPC Processor Supplement
3025   //   AltiVec Technology Programming Interface Manual
3026 
3027   MachineFunction &MF = DAG.getMachineFunction();
3028   MachineFrameInfo &MFI = MF.getFrameInfo();
3029   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3030 
3031   EVT PtrVT = getPointerTy(MF.getDataLayout());
3032   // Potential tail calls could cause overwriting of argument stack slots.
3033   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3034                        (CallConv == CallingConv::Fast));
3035   unsigned PtrByteSize = 4;
3036 
3037   // Assign locations to all of the incoming arguments.
3038   SmallVector<CCValAssign, 16> ArgLocs;
3039   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3040                  *DAG.getContext());
3041 
3042   // Reserve space for the linkage area on the stack.
3043   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3044   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3045   if (useSoftFloat())
3046     CCInfo.PreAnalyzeFormalArguments(Ins);
3047 
3048   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3049   CCInfo.clearWasPPCF128();
3050 
3051   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3052     CCValAssign &VA = ArgLocs[i];
3053 
3054     // Arguments stored in registers.
3055     if (VA.isRegLoc()) {
3056       const TargetRegisterClass *RC;
3057       EVT ValVT = VA.getValVT();
3058 
3059       switch (ValVT.getSimpleVT().SimpleTy) {
3060         default:
3061           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3062         case MVT::i1:
3063         case MVT::i32:
3064           RC = &PPC::GPRCRegClass;
3065           break;
3066         case MVT::f32:
3067           if (Subtarget.hasP8Vector())
3068             RC = &PPC::VSSRCRegClass;
3069           else
3070             RC = &PPC::F4RCRegClass;
3071           break;
3072         case MVT::f64:
3073           if (Subtarget.hasVSX())
3074             RC = &PPC::VSFRCRegClass;
3075           else
3076             RC = &PPC::F8RCRegClass;
3077           break;
3078         case MVT::v16i8:
3079         case MVT::v8i16:
3080         case MVT::v4i32:
3081           RC = &PPC::VRRCRegClass;
3082           break;
3083         case MVT::v4f32:
3084           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3085           break;
3086         case MVT::v2f64:
3087         case MVT::v2i64:
3088           RC = &PPC::VRRCRegClass;
3089           break;
3090         case MVT::v4f64:
3091           RC = &PPC::QFRCRegClass;
3092           break;
3093         case MVT::v4i1:
3094           RC = &PPC::QBRCRegClass;
3095           break;
3096       }
3097 
3098       // Transform the arguments stored in physical registers into virtual ones.
3099       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3100       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3101                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3102 
3103       if (ValVT == MVT::i1)
3104         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3105 
3106       InVals.push_back(ArgValue);
3107     } else {
3108       // Argument stored in memory.
3109       assert(VA.isMemLoc());
3110 
3111       unsigned ArgSize = VA.getLocVT().getStoreSize();
3112       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3113                                      isImmutable);
3114 
3115       // Create load nodes to retrieve arguments from the stack.
3116       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3117       InVals.push_back(
3118           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3119     }
3120   }
3121 
3122   // Assign locations to all of the incoming aggregate by value arguments.
3123   // Aggregates passed by value are stored in the local variable space of the
3124   // caller's stack frame, right above the parameter list area.
3125   SmallVector<CCValAssign, 16> ByValArgLocs;
3126   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3127                       ByValArgLocs, *DAG.getContext());
3128 
3129   // Reserve stack space for the allocations in CCInfo.
3130   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3131 
3132   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3133 
3134   // Area that is at least reserved in the caller of this function.
3135   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3136   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3137 
3138   // Set the size that is at least reserved in caller of this function.  Tail
3139   // call optimized function's reserved stack space needs to be aligned so that
3140   // taking the difference between two stack areas will result in an aligned
3141   // stack.
3142   MinReservedArea =
3143       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3144   FuncInfo->setMinReservedArea(MinReservedArea);
3145 
3146   SmallVector<SDValue, 8> MemOps;
3147 
3148   // If the function takes variable number of arguments, make a frame index for
3149   // the start of the first vararg value... for expansion of llvm.va_start.
3150   if (isVarArg) {
3151     static const MCPhysReg GPArgRegs[] = {
3152       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3153       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3154     };
3155     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3156 
3157     static const MCPhysReg FPArgRegs[] = {
3158       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3159       PPC::F8
3160     };
3161     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3162 
3163     if (useSoftFloat())
3164        NumFPArgRegs = 0;
3165 
3166     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3167     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3168 
3169     // Make room for NumGPArgRegs and NumFPArgRegs.
3170     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3171                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3172 
3173     FuncInfo->setVarArgsStackOffset(
3174       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3175                             CCInfo.getNextStackOffset(), true));
3176 
3177     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3178     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3179 
3180     // The fixed integer arguments of a variadic function are stored to the
3181     // VarArgsFrameIndex on the stack so that they may be loaded by
3182     // dereferencing the result of va_next.
3183     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3184       // Get an existing live-in vreg, or add a new one.
3185       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3186       if (!VReg)
3187         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3188 
3189       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3190       SDValue Store =
3191           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3192       MemOps.push_back(Store);
3193       // Increment the address by four for the next argument to store
3194       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3195       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3196     }
3197 
3198     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3199     // is set.
3200     // The double arguments are stored to the VarArgsFrameIndex
3201     // on the stack.
3202     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3203       // Get an existing live-in vreg, or add a new one.
3204       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3205       if (!VReg)
3206         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3207 
3208       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3209       SDValue Store =
3210           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3211       MemOps.push_back(Store);
3212       // Increment the address by eight for the next argument to store
3213       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3214                                          PtrVT);
3215       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3216     }
3217   }
3218 
3219   if (!MemOps.empty())
3220     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3221 
3222   return Chain;
3223 }
3224 
3225 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3226 // value to MVT::i64 and then truncate to the correct register size.
3227 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3228                                              EVT ObjectVT, SelectionDAG &DAG,
3229                                              SDValue ArgVal,
3230                                              const SDLoc &dl) const {
3231   if (Flags.isSExt())
3232     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3233                          DAG.getValueType(ObjectVT));
3234   else if (Flags.isZExt())
3235     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3236                          DAG.getValueType(ObjectVT));
3237 
3238   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3239 }
3240 
3241 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3242     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3243     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3244     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3245   // TODO: add description of PPC stack frame format, or at least some docs.
3246   //
3247   bool isELFv2ABI = Subtarget.isELFv2ABI();
3248   bool isLittleEndian = Subtarget.isLittleEndian();
3249   MachineFunction &MF = DAG.getMachineFunction();
3250   MachineFrameInfo &MFI = MF.getFrameInfo();
3251   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3252 
3253   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3254          "fastcc not supported on varargs functions");
3255 
3256   EVT PtrVT = getPointerTy(MF.getDataLayout());
3257   // Potential tail calls could cause overwriting of argument stack slots.
3258   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3259                        (CallConv == CallingConv::Fast));
3260   unsigned PtrByteSize = 8;
3261   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3262 
3263   static const MCPhysReg GPR[] = {
3264     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3265     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3266   };
3267   static const MCPhysReg VR[] = {
3268     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3269     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3270   };
3271 
3272   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3273   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3274   const unsigned Num_VR_Regs  = array_lengthof(VR);
3275   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3276 
3277   // Do a first pass over the arguments to determine whether the ABI
3278   // guarantees that our caller has allocated the parameter save area
3279   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3280   // in the ELFv2 ABI, it is true if this is a vararg function or if
3281   // any parameter is located in a stack slot.
3282 
3283   bool HasParameterArea = !isELFv2ABI || isVarArg;
3284   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3285   unsigned NumBytes = LinkageSize;
3286   unsigned AvailableFPRs = Num_FPR_Regs;
3287   unsigned AvailableVRs = Num_VR_Regs;
3288   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3289     if (Ins[i].Flags.isNest())
3290       continue;
3291 
3292     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3293                                PtrByteSize, LinkageSize, ParamAreaSize,
3294                                NumBytes, AvailableFPRs, AvailableVRs,
3295                                Subtarget.hasQPX()))
3296       HasParameterArea = true;
3297   }
3298 
3299   // Add DAG nodes to load the arguments or copy them out of registers.  On
3300   // entry to a function on PPC, the arguments start after the linkage area,
3301   // although the first ones are often in registers.
3302 
3303   unsigned ArgOffset = LinkageSize;
3304   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3305   unsigned &QFPR_idx = FPR_idx;
3306   SmallVector<SDValue, 8> MemOps;
3307   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3308   unsigned CurArgIdx = 0;
3309   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3310     SDValue ArgVal;
3311     bool needsLoad = false;
3312     EVT ObjectVT = Ins[ArgNo].VT;
3313     EVT OrigVT = Ins[ArgNo].ArgVT;
3314     unsigned ObjSize = ObjectVT.getStoreSize();
3315     unsigned ArgSize = ObjSize;
3316     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3317     if (Ins[ArgNo].isOrigArg()) {
3318       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3319       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3320     }
3321     // We re-align the argument offset for each argument, except when using the
3322     // fast calling convention, when we need to make sure we do that only when
3323     // we'll actually use a stack slot.
3324     unsigned CurArgOffset, Align;
3325     auto ComputeArgOffset = [&]() {
3326       /* Respect alignment of argument on the stack.  */
3327       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3328       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3329       CurArgOffset = ArgOffset;
3330     };
3331 
3332     if (CallConv != CallingConv::Fast) {
3333       ComputeArgOffset();
3334 
3335       /* Compute GPR index associated with argument offset.  */
3336       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3337       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3338     }
3339 
3340     // FIXME the codegen can be much improved in some cases.
3341     // We do not have to keep everything in memory.
3342     if (Flags.isByVal()) {
3343       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3344 
3345       if (CallConv == CallingConv::Fast)
3346         ComputeArgOffset();
3347 
3348       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3349       ObjSize = Flags.getByValSize();
3350       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3351       // Empty aggregate parameters do not take up registers.  Examples:
3352       //   struct { } a;
3353       //   union  { } b;
3354       //   int c[0];
3355       // etc.  However, we have to provide a place-holder in InVals, so
3356       // pretend we have an 8-byte item at the current address for that
3357       // purpose.
3358       if (!ObjSize) {
3359         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3360         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3361         InVals.push_back(FIN);
3362         continue;
3363       }
3364 
3365       // Create a stack object covering all stack doublewords occupied
3366       // by the argument.  If the argument is (fully or partially) on
3367       // the stack, or if the argument is fully in registers but the
3368       // caller has allocated the parameter save anyway, we can refer
3369       // directly to the caller's stack frame.  Otherwise, create a
3370       // local copy in our own frame.
3371       int FI;
3372       if (HasParameterArea ||
3373           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3374         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3375       else
3376         FI = MFI.CreateStackObject(ArgSize, Align, false);
3377       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3378 
3379       // Handle aggregates smaller than 8 bytes.
3380       if (ObjSize < PtrByteSize) {
3381         // The value of the object is its address, which differs from the
3382         // address of the enclosing doubleword on big-endian systems.
3383         SDValue Arg = FIN;
3384         if (!isLittleEndian) {
3385           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3386           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3387         }
3388         InVals.push_back(Arg);
3389 
3390         if (GPR_idx != Num_GPR_Regs) {
3391           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3392           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3393           SDValue Store;
3394 
3395           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3396             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3397                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3398             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3399                                       MachinePointerInfo(&*FuncArg), ObjType);
3400           } else {
3401             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3402             // store the whole register as-is to the parameter save area
3403             // slot.
3404             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3405                                  MachinePointerInfo(&*FuncArg));
3406           }
3407 
3408           MemOps.push_back(Store);
3409         }
3410         // Whether we copied from a register or not, advance the offset
3411         // into the parameter save area by a full doubleword.
3412         ArgOffset += PtrByteSize;
3413         continue;
3414       }
3415 
3416       // The value of the object is its address, which is the address of
3417       // its first stack doubleword.
3418       InVals.push_back(FIN);
3419 
3420       // Store whatever pieces of the object are in registers to memory.
3421       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3422         if (GPR_idx == Num_GPR_Regs)
3423           break;
3424 
3425         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3426         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3427         SDValue Addr = FIN;
3428         if (j) {
3429           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3430           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3431         }
3432         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3433                                      MachinePointerInfo(&*FuncArg, j));
3434         MemOps.push_back(Store);
3435         ++GPR_idx;
3436       }
3437       ArgOffset += ArgSize;
3438       continue;
3439     }
3440 
3441     switch (ObjectVT.getSimpleVT().SimpleTy) {
3442     default: llvm_unreachable("Unhandled argument type!");
3443     case MVT::i1:
3444     case MVT::i32:
3445     case MVT::i64:
3446       if (Flags.isNest()) {
3447         // The 'nest' parameter, if any, is passed in R11.
3448         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3449         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3450 
3451         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3452           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3453 
3454         break;
3455       }
3456 
3457       // These can be scalar arguments or elements of an integer array type
3458       // passed directly.  Clang may use those instead of "byval" aggregate
3459       // types to avoid forcing arguments to memory unnecessarily.
3460       if (GPR_idx != Num_GPR_Regs) {
3461         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3462         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3463 
3464         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3465           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3466           // value to MVT::i64 and then truncate to the correct register size.
3467           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3468       } else {
3469         if (CallConv == CallingConv::Fast)
3470           ComputeArgOffset();
3471 
3472         needsLoad = true;
3473         ArgSize = PtrByteSize;
3474       }
3475       if (CallConv != CallingConv::Fast || needsLoad)
3476         ArgOffset += 8;
3477       break;
3478 
3479     case MVT::f32:
3480     case MVT::f64:
3481       // These can be scalar arguments or elements of a float array type
3482       // passed directly.  The latter are used to implement ELFv2 homogenous
3483       // float aggregates.
3484       if (FPR_idx != Num_FPR_Regs) {
3485         unsigned VReg;
3486 
3487         if (ObjectVT == MVT::f32)
3488           VReg = MF.addLiveIn(FPR[FPR_idx],
3489                               Subtarget.hasP8Vector()
3490                                   ? &PPC::VSSRCRegClass
3491                                   : &PPC::F4RCRegClass);
3492         else
3493           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3494                                                 ? &PPC::VSFRCRegClass
3495                                                 : &PPC::F8RCRegClass);
3496 
3497         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3498         ++FPR_idx;
3499       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3500         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3501         // once we support fp <-> gpr moves.
3502 
3503         // This can only ever happen in the presence of f32 array types,
3504         // since otherwise we never run out of FPRs before running out
3505         // of GPRs.
3506         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3507         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3508 
3509         if (ObjectVT == MVT::f32) {
3510           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3511             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3512                                  DAG.getConstant(32, dl, MVT::i32));
3513           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3514         }
3515 
3516         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3517       } else {
3518         if (CallConv == CallingConv::Fast)
3519           ComputeArgOffset();
3520 
3521         needsLoad = true;
3522       }
3523 
3524       // When passing an array of floats, the array occupies consecutive
3525       // space in the argument area; only round up to the next doubleword
3526       // at the end of the array.  Otherwise, each float takes 8 bytes.
3527       if (CallConv != CallingConv::Fast || needsLoad) {
3528         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3529         ArgOffset += ArgSize;
3530         if (Flags.isInConsecutiveRegsLast())
3531           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3532       }
3533       break;
3534     case MVT::v4f32:
3535     case MVT::v4i32:
3536     case MVT::v8i16:
3537     case MVT::v16i8:
3538     case MVT::v2f64:
3539     case MVT::v2i64:
3540     case MVT::v1i128:
3541       if (!Subtarget.hasQPX()) {
3542       // These can be scalar arguments or elements of a vector array type
3543       // passed directly.  The latter are used to implement ELFv2 homogenous
3544       // vector aggregates.
3545       if (VR_idx != Num_VR_Regs) {
3546         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3547         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3548         ++VR_idx;
3549       } else {
3550         if (CallConv == CallingConv::Fast)
3551           ComputeArgOffset();
3552 
3553         needsLoad = true;
3554       }
3555       if (CallConv != CallingConv::Fast || needsLoad)
3556         ArgOffset += 16;
3557       break;
3558       } // not QPX
3559 
3560       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3561              "Invalid QPX parameter type");
3562       /* fall through */
3563 
3564     case MVT::v4f64:
3565     case MVT::v4i1:
3566       // QPX vectors are treated like their scalar floating-point subregisters
3567       // (except that they're larger).
3568       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3569       if (QFPR_idx != Num_QFPR_Regs) {
3570         const TargetRegisterClass *RC;
3571         switch (ObjectVT.getSimpleVT().SimpleTy) {
3572         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3573         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3574         default:         RC = &PPC::QBRCRegClass; break;
3575         }
3576 
3577         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3578         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3579         ++QFPR_idx;
3580       } else {
3581         if (CallConv == CallingConv::Fast)
3582           ComputeArgOffset();
3583         needsLoad = true;
3584       }
3585       if (CallConv != CallingConv::Fast || needsLoad)
3586         ArgOffset += Sz;
3587       break;
3588     }
3589 
3590     // We need to load the argument to a virtual register if we determined
3591     // above that we ran out of physical registers of the appropriate type.
3592     if (needsLoad) {
3593       if (ObjSize < ArgSize && !isLittleEndian)
3594         CurArgOffset += ArgSize - ObjSize;
3595       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3596       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3597       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3598     }
3599 
3600     InVals.push_back(ArgVal);
3601   }
3602 
3603   // Area that is at least reserved in the caller of this function.
3604   unsigned MinReservedArea;
3605   if (HasParameterArea)
3606     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3607   else
3608     MinReservedArea = LinkageSize;
3609 
3610   // Set the size that is at least reserved in caller of this function.  Tail
3611   // call optimized functions' reserved stack space needs to be aligned so that
3612   // taking the difference between two stack areas will result in an aligned
3613   // stack.
3614   MinReservedArea =
3615       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3616   FuncInfo->setMinReservedArea(MinReservedArea);
3617 
3618   // If the function takes variable number of arguments, make a frame index for
3619   // the start of the first vararg value... for expansion of llvm.va_start.
3620   if (isVarArg) {
3621     int Depth = ArgOffset;
3622 
3623     FuncInfo->setVarArgsFrameIndex(
3624       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3625     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3626 
3627     // If this function is vararg, store any remaining integer argument regs
3628     // to their spots on the stack so that they may be loaded by dereferencing
3629     // the result of va_next.
3630     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3631          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3632       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3633       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3634       SDValue Store =
3635           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3636       MemOps.push_back(Store);
3637       // Increment the address by four for the next argument to store
3638       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3639       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3640     }
3641   }
3642 
3643   if (!MemOps.empty())
3644     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3645 
3646   return Chain;
3647 }
3648 
3649 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3650     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3651     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3652     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3653   // TODO: add description of PPC stack frame format, or at least some docs.
3654   //
3655   MachineFunction &MF = DAG.getMachineFunction();
3656   MachineFrameInfo &MFI = MF.getFrameInfo();
3657   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3658 
3659   EVT PtrVT = getPointerTy(MF.getDataLayout());
3660   bool isPPC64 = PtrVT == MVT::i64;
3661   // Potential tail calls could cause overwriting of argument stack slots.
3662   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3663                        (CallConv == CallingConv::Fast));
3664   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3665   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3666   unsigned ArgOffset = LinkageSize;
3667   // Area that is at least reserved in caller of this function.
3668   unsigned MinReservedArea = ArgOffset;
3669 
3670   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3671     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3672     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3673   };
3674   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3675     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3676     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3677   };
3678   static const MCPhysReg VR[] = {
3679     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3680     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3681   };
3682 
3683   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3684   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3685   const unsigned Num_VR_Regs  = array_lengthof( VR);
3686 
3687   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3688 
3689   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3690 
3691   // In 32-bit non-varargs functions, the stack space for vectors is after the
3692   // stack space for non-vectors.  We do not use this space unless we have
3693   // too many vectors to fit in registers, something that only occurs in
3694   // constructed examples:), but we have to walk the arglist to figure
3695   // that out...for the pathological case, compute VecArgOffset as the
3696   // start of the vector parameter area.  Computing VecArgOffset is the
3697   // entire point of the following loop.
3698   unsigned VecArgOffset = ArgOffset;
3699   if (!isVarArg && !isPPC64) {
3700     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3701          ++ArgNo) {
3702       EVT ObjectVT = Ins[ArgNo].VT;
3703       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3704 
3705       if (Flags.isByVal()) {
3706         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3707         unsigned ObjSize = Flags.getByValSize();
3708         unsigned ArgSize =
3709                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3710         VecArgOffset += ArgSize;
3711         continue;
3712       }
3713 
3714       switch(ObjectVT.getSimpleVT().SimpleTy) {
3715       default: llvm_unreachable("Unhandled argument type!");
3716       case MVT::i1:
3717       case MVT::i32:
3718       case MVT::f32:
3719         VecArgOffset += 4;
3720         break;
3721       case MVT::i64:  // PPC64
3722       case MVT::f64:
3723         // FIXME: We are guaranteed to be !isPPC64 at this point.
3724         // Does MVT::i64 apply?
3725         VecArgOffset += 8;
3726         break;
3727       case MVT::v4f32:
3728       case MVT::v4i32:
3729       case MVT::v8i16:
3730       case MVT::v16i8:
3731         // Nothing to do, we're only looking at Nonvector args here.
3732         break;
3733       }
3734     }
3735   }
3736   // We've found where the vector parameter area in memory is.  Skip the
3737   // first 12 parameters; these don't use that memory.
3738   VecArgOffset = ((VecArgOffset+15)/16)*16;
3739   VecArgOffset += 12*16;
3740 
3741   // Add DAG nodes to load the arguments or copy them out of registers.  On
3742   // entry to a function on PPC, the arguments start after the linkage area,
3743   // although the first ones are often in registers.
3744 
3745   SmallVector<SDValue, 8> MemOps;
3746   unsigned nAltivecParamsAtEnd = 0;
3747   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3748   unsigned CurArgIdx = 0;
3749   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3750     SDValue ArgVal;
3751     bool needsLoad = false;
3752     EVT ObjectVT = Ins[ArgNo].VT;
3753     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3754     unsigned ArgSize = ObjSize;
3755     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3756     if (Ins[ArgNo].isOrigArg()) {
3757       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3758       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3759     }
3760     unsigned CurArgOffset = ArgOffset;
3761 
3762     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3763     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3764         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3765       if (isVarArg || isPPC64) {
3766         MinReservedArea = ((MinReservedArea+15)/16)*16;
3767         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3768                                                   Flags,
3769                                                   PtrByteSize);
3770       } else  nAltivecParamsAtEnd++;
3771     } else
3772       // Calculate min reserved area.
3773       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3774                                                 Flags,
3775                                                 PtrByteSize);
3776 
3777     // FIXME the codegen can be much improved in some cases.
3778     // We do not have to keep everything in memory.
3779     if (Flags.isByVal()) {
3780       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3781 
3782       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3783       ObjSize = Flags.getByValSize();
3784       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3785       // Objects of size 1 and 2 are right justified, everything else is
3786       // left justified.  This means the memory address is adjusted forwards.
3787       if (ObjSize==1 || ObjSize==2) {
3788         CurArgOffset = CurArgOffset + (4 - ObjSize);
3789       }
3790       // The value of the object is its address.
3791       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3792       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3793       InVals.push_back(FIN);
3794       if (ObjSize==1 || ObjSize==2) {
3795         if (GPR_idx != Num_GPR_Regs) {
3796           unsigned VReg;
3797           if (isPPC64)
3798             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3799           else
3800             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3801           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3802           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3803           SDValue Store =
3804               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3805                                 MachinePointerInfo(&*FuncArg), ObjType);
3806           MemOps.push_back(Store);
3807           ++GPR_idx;
3808         }
3809 
3810         ArgOffset += PtrByteSize;
3811 
3812         continue;
3813       }
3814       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3815         // Store whatever pieces of the object are in registers
3816         // to memory.  ArgOffset will be the address of the beginning
3817         // of the object.
3818         if (GPR_idx != Num_GPR_Regs) {
3819           unsigned VReg;
3820           if (isPPC64)
3821             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3822           else
3823             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3824           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3825           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3826           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3827           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3828                                        MachinePointerInfo(&*FuncArg, j));
3829           MemOps.push_back(Store);
3830           ++GPR_idx;
3831           ArgOffset += PtrByteSize;
3832         } else {
3833           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3834           break;
3835         }
3836       }
3837       continue;
3838     }
3839 
3840     switch (ObjectVT.getSimpleVT().SimpleTy) {
3841     default: llvm_unreachable("Unhandled argument type!");
3842     case MVT::i1:
3843     case MVT::i32:
3844       if (!isPPC64) {
3845         if (GPR_idx != Num_GPR_Regs) {
3846           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3847           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3848 
3849           if (ObjectVT == MVT::i1)
3850             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3851 
3852           ++GPR_idx;
3853         } else {
3854           needsLoad = true;
3855           ArgSize = PtrByteSize;
3856         }
3857         // All int arguments reserve stack space in the Darwin ABI.
3858         ArgOffset += PtrByteSize;
3859         break;
3860       }
3861       LLVM_FALLTHROUGH;
3862     case MVT::i64:  // PPC64
3863       if (GPR_idx != Num_GPR_Regs) {
3864         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3865         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3866 
3867         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3868           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3869           // value to MVT::i64 and then truncate to the correct register size.
3870           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3871 
3872         ++GPR_idx;
3873       } else {
3874         needsLoad = true;
3875         ArgSize = PtrByteSize;
3876       }
3877       // All int arguments reserve stack space in the Darwin ABI.
3878       ArgOffset += 8;
3879       break;
3880 
3881     case MVT::f32:
3882     case MVT::f64:
3883       // Every 4 bytes of argument space consumes one of the GPRs available for
3884       // argument passing.
3885       if (GPR_idx != Num_GPR_Regs) {
3886         ++GPR_idx;
3887         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3888           ++GPR_idx;
3889       }
3890       if (FPR_idx != Num_FPR_Regs) {
3891         unsigned VReg;
3892 
3893         if (ObjectVT == MVT::f32)
3894           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3895         else
3896           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3897 
3898         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3899         ++FPR_idx;
3900       } else {
3901         needsLoad = true;
3902       }
3903 
3904       // All FP arguments reserve stack space in the Darwin ABI.
3905       ArgOffset += isPPC64 ? 8 : ObjSize;
3906       break;
3907     case MVT::v4f32:
3908     case MVT::v4i32:
3909     case MVT::v8i16:
3910     case MVT::v16i8:
3911       // Note that vector arguments in registers don't reserve stack space,
3912       // except in varargs functions.
3913       if (VR_idx != Num_VR_Regs) {
3914         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3915         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3916         if (isVarArg) {
3917           while ((ArgOffset % 16) != 0) {
3918             ArgOffset += PtrByteSize;
3919             if (GPR_idx != Num_GPR_Regs)
3920               GPR_idx++;
3921           }
3922           ArgOffset += 16;
3923           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3924         }
3925         ++VR_idx;
3926       } else {
3927         if (!isVarArg && !isPPC64) {
3928           // Vectors go after all the nonvectors.
3929           CurArgOffset = VecArgOffset;
3930           VecArgOffset += 16;
3931         } else {
3932           // Vectors are aligned.
3933           ArgOffset = ((ArgOffset+15)/16)*16;
3934           CurArgOffset = ArgOffset;
3935           ArgOffset += 16;
3936         }
3937         needsLoad = true;
3938       }
3939       break;
3940     }
3941 
3942     // We need to load the argument to a virtual register if we determined above
3943     // that we ran out of physical registers of the appropriate type.
3944     if (needsLoad) {
3945       int FI = MFI.CreateFixedObject(ObjSize,
3946                                      CurArgOffset + (ArgSize - ObjSize),
3947                                      isImmutable);
3948       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3949       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3950     }
3951 
3952     InVals.push_back(ArgVal);
3953   }
3954 
3955   // Allow for Altivec parameters at the end, if needed.
3956   if (nAltivecParamsAtEnd) {
3957     MinReservedArea = ((MinReservedArea+15)/16)*16;
3958     MinReservedArea += 16*nAltivecParamsAtEnd;
3959   }
3960 
3961   // Area that is at least reserved in the caller of this function.
3962   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3963 
3964   // Set the size that is at least reserved in caller of this function.  Tail
3965   // call optimized functions' reserved stack space needs to be aligned so that
3966   // taking the difference between two stack areas will result in an aligned
3967   // stack.
3968   MinReservedArea =
3969       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3970   FuncInfo->setMinReservedArea(MinReservedArea);
3971 
3972   // If the function takes variable number of arguments, make a frame index for
3973   // the start of the first vararg value... for expansion of llvm.va_start.
3974   if (isVarArg) {
3975     int Depth = ArgOffset;
3976 
3977     FuncInfo->setVarArgsFrameIndex(
3978       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3979                             Depth, true));
3980     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3981 
3982     // If this function is vararg, store any remaining integer argument regs
3983     // to their spots on the stack so that they may be loaded by dereferencing
3984     // the result of va_next.
3985     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3986       unsigned VReg;
3987 
3988       if (isPPC64)
3989         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3990       else
3991         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3992 
3993       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3994       SDValue Store =
3995           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3996       MemOps.push_back(Store);
3997       // Increment the address by four for the next argument to store
3998       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3999       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4000     }
4001   }
4002 
4003   if (!MemOps.empty())
4004     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4005 
4006   return Chain;
4007 }
4008 
4009 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4010 /// adjusted to accommodate the arguments for the tailcall.
4011 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4012                                    unsigned ParamSize) {
4013 
4014   if (!isTailCall) return 0;
4015 
4016   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4017   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4018   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4019   // Remember only if the new adjustement is bigger.
4020   if (SPDiff < FI->getTailCallSPDelta())
4021     FI->setTailCallSPDelta(SPDiff);
4022 
4023   return SPDiff;
4024 }
4025 
4026 static bool isFunctionGlobalAddress(SDValue Callee);
4027 
4028 static bool
4029 resideInSameSection(const Function *Caller, SDValue Callee,
4030                     const TargetMachine &TM) {
4031   // If !G, Callee can be an external symbol.
4032   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4033   if (!G)
4034     return false;
4035 
4036   const GlobalValue *GV = G->getGlobal();
4037   if (!GV->isStrongDefinitionForLinker())
4038     return false;
4039 
4040   // Any explicitly-specified sections and section prefixes must also match.
4041   // Also, if we're using -ffunction-sections, then each function is always in
4042   // a different section (the same is true for COMDAT functions).
4043   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4044       GV->getSection() != Caller->getSection())
4045     return false;
4046   if (const auto *F = dyn_cast<Function>(GV)) {
4047     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4048       return false;
4049   }
4050 
4051   // If the callee might be interposed, then we can't assume the ultimate call
4052   // target will be in the same section. Even in cases where we can assume that
4053   // interposition won't happen, in any case where the linker might insert a
4054   // stub to allow for interposition, we must generate code as though
4055   // interposition might occur. To understand why this matters, consider a
4056   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4057   // in the same section, but a is in a different module (i.e. has a different
4058   // TOC base pointer). If the linker allows for interposition between b and c,
4059   // then it will generate a stub for the call edge between b and c which will
4060   // save the TOC pointer into the designated stack slot allocated by b. If we
4061   // return true here, and therefore allow a tail call between b and c, that
4062   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4063   // pointer into the stack slot allocated by a (where the a -> b stub saved
4064   // a's TOC base pointer). If we're not considering a tail call, but rather,
4065   // whether a nop is needed after the call instruction in b, because the linker
4066   // will insert a stub, it might complain about a missing nop if we omit it
4067   // (although many don't complain in this case).
4068   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4069     return false;
4070 
4071   return true;
4072 }
4073 
4074 static bool
4075 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4076                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4077   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4078 
4079   const unsigned PtrByteSize = 8;
4080   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4081 
4082   static const MCPhysReg GPR[] = {
4083     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4084     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4085   };
4086   static const MCPhysReg VR[] = {
4087     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4088     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4089   };
4090 
4091   const unsigned NumGPRs = array_lengthof(GPR);
4092   const unsigned NumFPRs = 13;
4093   const unsigned NumVRs = array_lengthof(VR);
4094   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4095 
4096   unsigned NumBytes = LinkageSize;
4097   unsigned AvailableFPRs = NumFPRs;
4098   unsigned AvailableVRs = NumVRs;
4099 
4100   for (const ISD::OutputArg& Param : Outs) {
4101     if (Param.Flags.isNest()) continue;
4102 
4103     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4104                                PtrByteSize, LinkageSize, ParamAreaSize,
4105                                NumBytes, AvailableFPRs, AvailableVRs,
4106                                Subtarget.hasQPX()))
4107       return true;
4108   }
4109   return false;
4110 }
4111 
4112 static bool
4113 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4114   if (CS->arg_size() != CallerFn->getArgumentList().size())
4115     return false;
4116 
4117   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4118   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4119   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4120 
4121   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4122     const Value* CalleeArg = *CalleeArgIter;
4123     const Value* CallerArg = &(*CallerArgIter);
4124     if (CalleeArg == CallerArg)
4125       continue;
4126 
4127     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4128     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4129     //      }
4130     // 1st argument of callee is undef and has the same type as caller.
4131     if (CalleeArg->getType() == CallerArg->getType() &&
4132         isa<UndefValue>(CalleeArg))
4133       continue;
4134 
4135     return false;
4136   }
4137 
4138   return true;
4139 }
4140 
4141 bool
4142 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4143                                     SDValue Callee,
4144                                     CallingConv::ID CalleeCC,
4145                                     ImmutableCallSite *CS,
4146                                     bool isVarArg,
4147                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4148                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4149                                     SelectionDAG& DAG) const {
4150   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4151 
4152   if (DisableSCO && !TailCallOpt) return false;
4153 
4154   // Variadic argument functions are not supported.
4155   if (isVarArg) return false;
4156 
4157   MachineFunction &MF = DAG.getMachineFunction();
4158   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4159 
4160   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4161   // the same calling convention
4162   if (CallerCC != CalleeCC) return false;
4163 
4164   // SCO support C calling convention
4165   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4166     return false;
4167 
4168   // Caller contains any byval parameter is not supported.
4169   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4170     return false;
4171 
4172   // Callee contains any byval parameter is not supported, too.
4173   // Note: This is a quick work around, because in some cases, e.g.
4174   // caller's stack size > callee's stack size, we are still able to apply
4175   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4176   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4177     return false;
4178 
4179   // No TCO/SCO on indirect call because Caller have to restore its TOC
4180   if (!isFunctionGlobalAddress(Callee) &&
4181       !isa<ExternalSymbolSDNode>(Callee))
4182     return false;
4183 
4184   // Check if Callee resides in the same section, because for now, PPC64 SVR4
4185   // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4186   // section.
4187   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4188   if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4189     return false;
4190 
4191   // TCO allows altering callee ABI, so we don't have to check further.
4192   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4193     return true;
4194 
4195   if (DisableSCO) return false;
4196 
4197   // If callee use the same argument list that caller is using, then we can
4198   // apply SCO on this case. If it is not, then we need to check if callee needs
4199   // stack for passing arguments.
4200   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4201       needStackSlotPassParameters(Subtarget, Outs)) {
4202     return false;
4203   }
4204 
4205   return true;
4206 }
4207 
4208 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4209 /// for tail call optimization. Targets which want to do tail call
4210 /// optimization should implement this function.
4211 bool
4212 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4213                                                      CallingConv::ID CalleeCC,
4214                                                      bool isVarArg,
4215                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4216                                                      SelectionDAG& DAG) const {
4217   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4218     return false;
4219 
4220   // Variable argument functions are not supported.
4221   if (isVarArg)
4222     return false;
4223 
4224   MachineFunction &MF = DAG.getMachineFunction();
4225   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4226   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4227     // Functions containing by val parameters are not supported.
4228     for (unsigned i = 0; i != Ins.size(); i++) {
4229        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4230        if (Flags.isByVal()) return false;
4231     }
4232 
4233     // Non-PIC/GOT tail calls are supported.
4234     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4235       return true;
4236 
4237     // At the moment we can only do local tail calls (in same module, hidden
4238     // or protected) if we are generating PIC.
4239     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4240       return G->getGlobal()->hasHiddenVisibility()
4241           || G->getGlobal()->hasProtectedVisibility();
4242   }
4243 
4244   return false;
4245 }
4246 
4247 /// isCallCompatibleAddress - Return the immediate to use if the specified
4248 /// 32-bit value is representable in the immediate field of a BxA instruction.
4249 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4250   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4251   if (!C) return nullptr;
4252 
4253   int Addr = C->getZExtValue();
4254   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4255       SignExtend32<26>(Addr) != Addr)
4256     return nullptr;  // Top 6 bits have to be sext of immediate.
4257 
4258   return DAG
4259       .getConstant(
4260           (int)C->getZExtValue() >> 2, SDLoc(Op),
4261           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4262       .getNode();
4263 }
4264 
4265 namespace {
4266 
4267 struct TailCallArgumentInfo {
4268   SDValue Arg;
4269   SDValue FrameIdxOp;
4270   int FrameIdx = 0;
4271 
4272   TailCallArgumentInfo() = default;
4273 };
4274 
4275 } // end anonymous namespace
4276 
4277 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4278 static void StoreTailCallArgumentsToStackSlot(
4279     SelectionDAG &DAG, SDValue Chain,
4280     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4281     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4282   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4283     SDValue Arg = TailCallArgs[i].Arg;
4284     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4285     int FI = TailCallArgs[i].FrameIdx;
4286     // Store relative to framepointer.
4287     MemOpChains.push_back(DAG.getStore(
4288         Chain, dl, Arg, FIN,
4289         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4290   }
4291 }
4292 
4293 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4294 /// the appropriate stack slot for the tail call optimized function call.
4295 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4296                                              SDValue OldRetAddr, SDValue OldFP,
4297                                              int SPDiff, const SDLoc &dl) {
4298   if (SPDiff) {
4299     // Calculate the new stack slot for the return address.
4300     MachineFunction &MF = DAG.getMachineFunction();
4301     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4302     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4303     bool isPPC64 = Subtarget.isPPC64();
4304     int SlotSize = isPPC64 ? 8 : 4;
4305     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4306     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4307                                                          NewRetAddrLoc, true);
4308     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4309     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4310     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4311                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4312 
4313     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4314     // slot as the FP is never overwritten.
4315     if (Subtarget.isDarwinABI()) {
4316       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4317       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4318                                                          true);
4319       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4320       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4321                            MachinePointerInfo::getFixedStack(
4322                                DAG.getMachineFunction(), NewFPIdx));
4323     }
4324   }
4325   return Chain;
4326 }
4327 
4328 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4329 /// the position of the argument.
4330 static void
4331 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4332                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4333                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4334   int Offset = ArgOffset + SPDiff;
4335   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4336   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4337   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4338   SDValue FIN = DAG.getFrameIndex(FI, VT);
4339   TailCallArgumentInfo Info;
4340   Info.Arg = Arg;
4341   Info.FrameIdxOp = FIN;
4342   Info.FrameIdx = FI;
4343   TailCallArguments.push_back(Info);
4344 }
4345 
4346 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4347 /// stack slot. Returns the chain as result and the loaded frame pointers in
4348 /// LROpOut/FPOpout. Used when tail calling.
4349 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4350     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4351     SDValue &FPOpOut, const SDLoc &dl) const {
4352   if (SPDiff) {
4353     // Load the LR and FP stack slot for later adjusting.
4354     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4355     LROpOut = getReturnAddrFrameIndex(DAG);
4356     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4357     Chain = SDValue(LROpOut.getNode(), 1);
4358 
4359     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4360     // slot as the FP is never overwritten.
4361     if (Subtarget.isDarwinABI()) {
4362       FPOpOut = getFramePointerFrameIndex(DAG);
4363       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4364       Chain = SDValue(FPOpOut.getNode(), 1);
4365     }
4366   }
4367   return Chain;
4368 }
4369 
4370 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4371 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4372 /// specified by the specific parameter attribute. The copy will be passed as
4373 /// a byval function parameter.
4374 /// Sometimes what we are copying is the end of a larger object, the part that
4375 /// does not fit in registers.
4376 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4377                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4378                                          SelectionDAG &DAG, const SDLoc &dl) {
4379   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4380   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4381                        false, false, false, MachinePointerInfo(),
4382                        MachinePointerInfo());
4383 }
4384 
4385 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4386 /// tail calls.
4387 static void LowerMemOpCallTo(
4388     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4389     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4390     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4391     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4392   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4393   if (!isTailCall) {
4394     if (isVector) {
4395       SDValue StackPtr;
4396       if (isPPC64)
4397         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4398       else
4399         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4400       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4401                            DAG.getConstant(ArgOffset, dl, PtrVT));
4402     }
4403     MemOpChains.push_back(
4404         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4405     // Calculate and remember argument location.
4406   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4407                                   TailCallArguments);
4408 }
4409 
4410 static void
4411 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4412                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4413                 SDValue FPOp,
4414                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4415   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4416   // might overwrite each other in case of tail call optimization.
4417   SmallVector<SDValue, 8> MemOpChains2;
4418   // Do not flag preceding copytoreg stuff together with the following stuff.
4419   InFlag = SDValue();
4420   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4421                                     MemOpChains2, dl);
4422   if (!MemOpChains2.empty())
4423     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4424 
4425   // Store the return address to the appropriate stack slot.
4426   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4427 
4428   // Emit callseq_end just before tailcall node.
4429   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4430                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4431   InFlag = Chain.getValue(1);
4432 }
4433 
4434 // Is this global address that of a function that can be called by name? (as
4435 // opposed to something that must hold a descriptor for an indirect call).
4436 static bool isFunctionGlobalAddress(SDValue Callee) {
4437   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4438     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4439         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4440       return false;
4441 
4442     return G->getGlobal()->getValueType()->isFunctionTy();
4443   }
4444 
4445   return false;
4446 }
4447 
4448 static unsigned
4449 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4450             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4451             bool isPatchPoint, bool hasNest,
4452             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4453             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4454             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4455   bool isPPC64 = Subtarget.isPPC64();
4456   bool isSVR4ABI = Subtarget.isSVR4ABI();
4457   bool isELFv2ABI = Subtarget.isELFv2ABI();
4458 
4459   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4460   NodeTys.push_back(MVT::Other);   // Returns a chain
4461   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4462 
4463   unsigned CallOpc = PPCISD::CALL;
4464 
4465   bool needIndirectCall = true;
4466   if (!isSVR4ABI || !isPPC64)
4467     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4468       // If this is an absolute destination address, use the munged value.
4469       Callee = SDValue(Dest, 0);
4470       needIndirectCall = false;
4471     }
4472 
4473   // PC-relative references to external symbols should go through $stub, unless
4474   // we're building with the leopard linker or later, which automatically
4475   // synthesizes these stubs.
4476   const TargetMachine &TM = DAG.getTarget();
4477   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4478   const GlobalValue *GV = nullptr;
4479   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4480     GV = G->getGlobal();
4481   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4482   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4483 
4484   if (isFunctionGlobalAddress(Callee)) {
4485     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4486     // A call to a TLS address is actually an indirect call to a
4487     // thread-specific pointer.
4488     unsigned OpFlags = 0;
4489     if (UsePlt)
4490       OpFlags = PPCII::MO_PLT;
4491 
4492     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4493     // every direct call is) turn it into a TargetGlobalAddress /
4494     // TargetExternalSymbol node so that legalize doesn't hack it.
4495     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4496                                         Callee.getValueType(), 0, OpFlags);
4497     needIndirectCall = false;
4498   }
4499 
4500   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4501     unsigned char OpFlags = 0;
4502 
4503     if (UsePlt)
4504       OpFlags = PPCII::MO_PLT;
4505 
4506     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4507                                          OpFlags);
4508     needIndirectCall = false;
4509   }
4510 
4511   if (isPatchPoint) {
4512     // We'll form an invalid direct call when lowering a patchpoint; the full
4513     // sequence for an indirect call is complicated, and many of the
4514     // instructions introduced might have side effects (and, thus, can't be
4515     // removed later). The call itself will be removed as soon as the
4516     // argument/return lowering is complete, so the fact that it has the wrong
4517     // kind of operands should not really matter.
4518     needIndirectCall = false;
4519   }
4520 
4521   if (needIndirectCall) {
4522     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4523     // to do the call, we can't use PPCISD::CALL.
4524     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4525 
4526     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4527       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4528       // entry point, but to the function descriptor (the function entry point
4529       // address is part of the function descriptor though).
4530       // The function descriptor is a three doubleword structure with the
4531       // following fields: function entry point, TOC base address and
4532       // environment pointer.
4533       // Thus for a call through a function pointer, the following actions need
4534       // to be performed:
4535       //   1. Save the TOC of the caller in the TOC save area of its stack
4536       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4537       //   2. Load the address of the function entry point from the function
4538       //      descriptor.
4539       //   3. Load the TOC of the callee from the function descriptor into r2.
4540       //   4. Load the environment pointer from the function descriptor into
4541       //      r11.
4542       //   5. Branch to the function entry point address.
4543       //   6. On return of the callee, the TOC of the caller needs to be
4544       //      restored (this is done in FinishCall()).
4545       //
4546       // The loads are scheduled at the beginning of the call sequence, and the
4547       // register copies are flagged together to ensure that no other
4548       // operations can be scheduled in between. E.g. without flagging the
4549       // copies together, a TOC access in the caller could be scheduled between
4550       // the assignment of the callee TOC and the branch to the callee, which
4551       // results in the TOC access going through the TOC of the callee instead
4552       // of going through the TOC of the caller, which leads to incorrect code.
4553 
4554       // Load the address of the function entry point from the function
4555       // descriptor.
4556       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4557       if (LDChain.getValueType() == MVT::Glue)
4558         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4559 
4560       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4561                           ? (MachineMemOperand::MODereferenceable |
4562                              MachineMemOperand::MOInvariant)
4563                           : MachineMemOperand::MONone;
4564 
4565       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4566       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4567                                         /* Alignment = */ 8, MMOFlags);
4568 
4569       // Load environment pointer into r11.
4570       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4571       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4572       SDValue LoadEnvPtr =
4573           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4574                       /* Alignment = */ 8, MMOFlags);
4575 
4576       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4577       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4578       SDValue TOCPtr =
4579           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4580                       /* Alignment = */ 8, MMOFlags);
4581 
4582       setUsesTOCBasePtr(DAG);
4583       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4584                                         InFlag);
4585       Chain = TOCVal.getValue(0);
4586       InFlag = TOCVal.getValue(1);
4587 
4588       // If the function call has an explicit 'nest' parameter, it takes the
4589       // place of the environment pointer.
4590       if (!hasNest) {
4591         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4592                                           InFlag);
4593 
4594         Chain = EnvVal.getValue(0);
4595         InFlag = EnvVal.getValue(1);
4596       }
4597 
4598       MTCTROps[0] = Chain;
4599       MTCTROps[1] = LoadFuncPtr;
4600       MTCTROps[2] = InFlag;
4601     }
4602 
4603     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4604                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4605     InFlag = Chain.getValue(1);
4606 
4607     NodeTys.clear();
4608     NodeTys.push_back(MVT::Other);
4609     NodeTys.push_back(MVT::Glue);
4610     Ops.push_back(Chain);
4611     CallOpc = PPCISD::BCTRL;
4612     Callee.setNode(nullptr);
4613     // Add use of X11 (holding environment pointer)
4614     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4615       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4616     // Add CTR register as callee so a bctr can be emitted later.
4617     if (isTailCall)
4618       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4619   }
4620 
4621   // If this is a direct call, pass the chain and the callee.
4622   if (Callee.getNode()) {
4623     Ops.push_back(Chain);
4624     Ops.push_back(Callee);
4625   }
4626   // If this is a tail call add stack pointer delta.
4627   if (isTailCall)
4628     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4629 
4630   // Add argument registers to the end of the list so that they are known live
4631   // into the call.
4632   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4633     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4634                                   RegsToPass[i].second.getValueType()));
4635 
4636   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4637   // into the call.
4638   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4639     setUsesTOCBasePtr(DAG);
4640     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4641   }
4642 
4643   return CallOpc;
4644 }
4645 
4646 SDValue PPCTargetLowering::LowerCallResult(
4647     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4648     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4649     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4650   SmallVector<CCValAssign, 16> RVLocs;
4651   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4652                     *DAG.getContext());
4653   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4654 
4655   // Copy all of the result registers out of their specified physreg.
4656   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4657     CCValAssign &VA = RVLocs[i];
4658     assert(VA.isRegLoc() && "Can only return in registers!");
4659 
4660     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4661                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4662     Chain = Val.getValue(1);
4663     InFlag = Val.getValue(2);
4664 
4665     switch (VA.getLocInfo()) {
4666     default: llvm_unreachable("Unknown loc info!");
4667     case CCValAssign::Full: break;
4668     case CCValAssign::AExt:
4669       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4670       break;
4671     case CCValAssign::ZExt:
4672       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4673                         DAG.getValueType(VA.getValVT()));
4674       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4675       break;
4676     case CCValAssign::SExt:
4677       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4678                         DAG.getValueType(VA.getValVT()));
4679       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4680       break;
4681     }
4682 
4683     InVals.push_back(Val);
4684   }
4685 
4686   return Chain;
4687 }
4688 
4689 SDValue PPCTargetLowering::FinishCall(
4690     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4691     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4692     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4693     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4694     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4695     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4696   std::vector<EVT> NodeTys;
4697   SmallVector<SDValue, 8> Ops;
4698   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4699                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4700                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4701 
4702   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4703   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4704     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4705 
4706   // When performing tail call optimization the callee pops its arguments off
4707   // the stack. Account for this here so these bytes can be pushed back on in
4708   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4709   int BytesCalleePops =
4710     (CallConv == CallingConv::Fast &&
4711      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4712 
4713   // Add a register mask operand representing the call-preserved registers.
4714   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4715   const uint32_t *Mask =
4716       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4717   assert(Mask && "Missing call preserved mask for calling convention");
4718   Ops.push_back(DAG.getRegisterMask(Mask));
4719 
4720   if (InFlag.getNode())
4721     Ops.push_back(InFlag);
4722 
4723   // Emit tail call.
4724   if (isTailCall) {
4725     assert(((Callee.getOpcode() == ISD::Register &&
4726              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4727             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4728             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4729             isa<ConstantSDNode>(Callee)) &&
4730     "Expecting an global address, external symbol, absolute value or register");
4731 
4732     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4733     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4734   }
4735 
4736   // Add a NOP immediately after the branch instruction when using the 64-bit
4737   // SVR4 ABI. At link time, if caller and callee are in a different module and
4738   // thus have a different TOC, the call will be replaced with a call to a stub
4739   // function which saves the current TOC, loads the TOC of the callee and
4740   // branches to the callee. The NOP will be replaced with a load instruction
4741   // which restores the TOC of the caller from the TOC save slot of the current
4742   // stack frame. If caller and callee belong to the same module (and have the
4743   // same TOC), the NOP will remain unchanged.
4744 
4745   MachineFunction &MF = DAG.getMachineFunction();
4746   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4747       !isPatchPoint) {
4748     if (CallOpc == PPCISD::BCTRL) {
4749       // This is a call through a function pointer.
4750       // Restore the caller TOC from the save area into R2.
4751       // See PrepareCall() for more information about calls through function
4752       // pointers in the 64-bit SVR4 ABI.
4753       // We are using a target-specific load with r2 hard coded, because the
4754       // result of a target-independent load would never go directly into r2,
4755       // since r2 is a reserved register (which prevents the register allocator
4756       // from allocating it), resulting in an additional register being
4757       // allocated and an unnecessary move instruction being generated.
4758       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4759 
4760       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4761       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4762       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4763       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4764       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4765 
4766       // The address needs to go after the chain input but before the flag (or
4767       // any other variadic arguments).
4768       Ops.insert(std::next(Ops.begin()), AddTOC);
4769     } else if (CallOpc == PPCISD::CALL &&
4770       !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4771       // Otherwise insert NOP for non-local calls.
4772       CallOpc = PPCISD::CALL_NOP;
4773     }
4774   }
4775 
4776   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4777   InFlag = Chain.getValue(1);
4778 
4779   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4780                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4781                              InFlag, dl);
4782   if (!Ins.empty())
4783     InFlag = Chain.getValue(1);
4784 
4785   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4786                          Ins, dl, DAG, InVals);
4787 }
4788 
4789 SDValue
4790 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4791                              SmallVectorImpl<SDValue> &InVals) const {
4792   SelectionDAG &DAG                     = CLI.DAG;
4793   SDLoc &dl                             = CLI.DL;
4794   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4795   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4796   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4797   SDValue Chain                         = CLI.Chain;
4798   SDValue Callee                        = CLI.Callee;
4799   bool &isTailCall                      = CLI.IsTailCall;
4800   CallingConv::ID CallConv              = CLI.CallConv;
4801   bool isVarArg                         = CLI.IsVarArg;
4802   bool isPatchPoint                     = CLI.IsPatchPoint;
4803   ImmutableCallSite *CS                 = CLI.CS;
4804 
4805   if (isTailCall) {
4806     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4807       isTailCall = false;
4808     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4809       isTailCall =
4810         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4811                                                  isVarArg, Outs, Ins, DAG);
4812     else
4813       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4814                                                      Ins, DAG);
4815     if (isTailCall) {
4816       ++NumTailCalls;
4817       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4818         ++NumSiblingCalls;
4819 
4820       assert(isa<GlobalAddressSDNode>(Callee) &&
4821              "Callee should be an llvm::Function object.");
4822       DEBUG(
4823         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4824         const unsigned Width = 80 - strlen("TCO caller: ")
4825                                   - strlen(", callee linkage: 0, 0");
4826         dbgs() << "TCO caller: "
4827                << left_justify(DAG.getMachineFunction().getName(), Width)
4828                << ", callee linkage: "
4829                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4830       );
4831     }
4832   }
4833 
4834   if (!isTailCall && CS && CS->isMustTailCall())
4835     report_fatal_error("failed to perform tail call elimination on a call "
4836                        "site marked musttail");
4837 
4838   // When long calls (i.e. indirect calls) are always used, calls are always
4839   // made via function pointer. If we have a function name, first translate it
4840   // into a pointer.
4841   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4842       !isTailCall)
4843     Callee = LowerGlobalAddress(Callee, DAG);
4844 
4845   if (Subtarget.isSVR4ABI()) {
4846     if (Subtarget.isPPC64())
4847       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4848                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4849                               dl, DAG, InVals, CS);
4850     else
4851       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4852                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4853                               dl, DAG, InVals, CS);
4854   }
4855 
4856   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4857                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4858                           dl, DAG, InVals, CS);
4859 }
4860 
4861 SDValue PPCTargetLowering::LowerCall_32SVR4(
4862     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4863     bool isTailCall, bool isPatchPoint,
4864     const SmallVectorImpl<ISD::OutputArg> &Outs,
4865     const SmallVectorImpl<SDValue> &OutVals,
4866     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4867     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4868     ImmutableCallSite *CS) const {
4869   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4870   // of the 32-bit SVR4 ABI stack frame layout.
4871 
4872   assert((CallConv == CallingConv::C ||
4873           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4874 
4875   unsigned PtrByteSize = 4;
4876 
4877   MachineFunction &MF = DAG.getMachineFunction();
4878 
4879   // Mark this function as potentially containing a function that contains a
4880   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4881   // and restoring the callers stack pointer in this functions epilog. This is
4882   // done because by tail calling the called function might overwrite the value
4883   // in this function's (MF) stack pointer stack slot 0(SP).
4884   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4885       CallConv == CallingConv::Fast)
4886     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4887 
4888   // Count how many bytes are to be pushed on the stack, including the linkage
4889   // area, parameter list area and the part of the local variable space which
4890   // contains copies of aggregates which are passed by value.
4891 
4892   // Assign locations to all of the outgoing arguments.
4893   SmallVector<CCValAssign, 16> ArgLocs;
4894   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4895 
4896   // Reserve space for the linkage area on the stack.
4897   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4898                        PtrByteSize);
4899   if (useSoftFloat())
4900     CCInfo.PreAnalyzeCallOperands(Outs);
4901 
4902   if (isVarArg) {
4903     // Handle fixed and variable vector arguments differently.
4904     // Fixed vector arguments go into registers as long as registers are
4905     // available. Variable vector arguments always go into memory.
4906     unsigned NumArgs = Outs.size();
4907 
4908     for (unsigned i = 0; i != NumArgs; ++i) {
4909       MVT ArgVT = Outs[i].VT;
4910       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4911       bool Result;
4912 
4913       if (Outs[i].IsFixed) {
4914         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4915                                CCInfo);
4916       } else {
4917         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4918                                       ArgFlags, CCInfo);
4919       }
4920 
4921       if (Result) {
4922 #ifndef NDEBUG
4923         errs() << "Call operand #" << i << " has unhandled type "
4924              << EVT(ArgVT).getEVTString() << "\n";
4925 #endif
4926         llvm_unreachable(nullptr);
4927       }
4928     }
4929   } else {
4930     // All arguments are treated the same.
4931     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4932   }
4933   CCInfo.clearWasPPCF128();
4934 
4935   // Assign locations to all of the outgoing aggregate by value arguments.
4936   SmallVector<CCValAssign, 16> ByValArgLocs;
4937   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4938 
4939   // Reserve stack space for the allocations in CCInfo.
4940   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4941 
4942   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4943 
4944   // Size of the linkage area, parameter list area and the part of the local
4945   // space variable where copies of aggregates which are passed by value are
4946   // stored.
4947   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4948 
4949   // Calculate by how many bytes the stack has to be adjusted in case of tail
4950   // call optimization.
4951   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4952 
4953   // Adjust the stack pointer for the new arguments...
4954   // These operations are automatically eliminated by the prolog/epilog pass
4955   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4956                                dl);
4957   SDValue CallSeqStart = Chain;
4958 
4959   // Load the return address and frame pointer so it can be moved somewhere else
4960   // later.
4961   SDValue LROp, FPOp;
4962   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4963 
4964   // Set up a copy of the stack pointer for use loading and storing any
4965   // arguments that may not fit in the registers available for argument
4966   // passing.
4967   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4968 
4969   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4970   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4971   SmallVector<SDValue, 8> MemOpChains;
4972 
4973   bool seenFloatArg = false;
4974   // Walk the register/memloc assignments, inserting copies/loads.
4975   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4976        i != e;
4977        ++i) {
4978     CCValAssign &VA = ArgLocs[i];
4979     SDValue Arg = OutVals[i];
4980     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4981 
4982     if (Flags.isByVal()) {
4983       // Argument is an aggregate which is passed by value, thus we need to
4984       // create a copy of it in the local variable space of the current stack
4985       // frame (which is the stack frame of the caller) and pass the address of
4986       // this copy to the callee.
4987       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4988       CCValAssign &ByValVA = ByValArgLocs[j++];
4989       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4990 
4991       // Memory reserved in the local variable space of the callers stack frame.
4992       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4993 
4994       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4995       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4996                            StackPtr, PtrOff);
4997 
4998       // Create a copy of the argument in the local area of the current
4999       // stack frame.
5000       SDValue MemcpyCall =
5001         CreateCopyOfByValArgument(Arg, PtrOff,
5002                                   CallSeqStart.getNode()->getOperand(0),
5003                                   Flags, DAG, dl);
5004 
5005       // This must go outside the CALLSEQ_START..END.
5006       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
5007                            CallSeqStart.getNode()->getOperand(1),
5008                            SDLoc(MemcpyCall));
5009       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5010                              NewCallSeqStart.getNode());
5011       Chain = CallSeqStart = NewCallSeqStart;
5012 
5013       // Pass the address of the aggregate copy on the stack either in a
5014       // physical register or in the parameter list area of the current stack
5015       // frame to the callee.
5016       Arg = PtrOff;
5017     }
5018 
5019     if (VA.isRegLoc()) {
5020       if (Arg.getValueType() == MVT::i1)
5021         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5022 
5023       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5024       // Put argument in a physical register.
5025       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5026     } else {
5027       // Put argument in the parameter list area of the current stack frame.
5028       assert(VA.isMemLoc());
5029       unsigned LocMemOffset = VA.getLocMemOffset();
5030 
5031       if (!isTailCall) {
5032         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5033         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5034                              StackPtr, PtrOff);
5035 
5036         MemOpChains.push_back(
5037             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5038       } else {
5039         // Calculate and remember argument location.
5040         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5041                                  TailCallArguments);
5042       }
5043     }
5044   }
5045 
5046   if (!MemOpChains.empty())
5047     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5048 
5049   // Build a sequence of copy-to-reg nodes chained together with token chain
5050   // and flag operands which copy the outgoing args into the appropriate regs.
5051   SDValue InFlag;
5052   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5053     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5054                              RegsToPass[i].second, InFlag);
5055     InFlag = Chain.getValue(1);
5056   }
5057 
5058   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5059   // registers.
5060   if (isVarArg) {
5061     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5062     SDValue Ops[] = { Chain, InFlag };
5063 
5064     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5065                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5066 
5067     InFlag = Chain.getValue(1);
5068   }
5069 
5070   if (isTailCall)
5071     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5072                     TailCallArguments);
5073 
5074   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5075                     /* unused except on PPC64 ELFv1 */ false, DAG,
5076                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5077                     NumBytes, Ins, InVals, CS);
5078 }
5079 
5080 // Copy an argument into memory, being careful to do this outside the
5081 // call sequence for the call to which the argument belongs.
5082 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5083     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5084     SelectionDAG &DAG, const SDLoc &dl) const {
5085   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5086                         CallSeqStart.getNode()->getOperand(0),
5087                         Flags, DAG, dl);
5088   // The MEMCPY must go outside the CALLSEQ_START..END.
5089   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
5090                              CallSeqStart.getNode()->getOperand(1),
5091                              SDLoc(MemcpyCall));
5092   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5093                          NewCallSeqStart.getNode());
5094   return NewCallSeqStart;
5095 }
5096 
5097 SDValue PPCTargetLowering::LowerCall_64SVR4(
5098     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5099     bool isTailCall, bool isPatchPoint,
5100     const SmallVectorImpl<ISD::OutputArg> &Outs,
5101     const SmallVectorImpl<SDValue> &OutVals,
5102     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5103     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5104     ImmutableCallSite *CS) const {
5105   bool isELFv2ABI = Subtarget.isELFv2ABI();
5106   bool isLittleEndian = Subtarget.isLittleEndian();
5107   unsigned NumOps = Outs.size();
5108   bool hasNest = false;
5109   bool IsSibCall = false;
5110 
5111   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5112   unsigned PtrByteSize = 8;
5113 
5114   MachineFunction &MF = DAG.getMachineFunction();
5115 
5116   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5117     IsSibCall = true;
5118 
5119   // Mark this function as potentially containing a function that contains a
5120   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5121   // and restoring the callers stack pointer in this functions epilog. This is
5122   // done because by tail calling the called function might overwrite the value
5123   // in this function's (MF) stack pointer stack slot 0(SP).
5124   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5125       CallConv == CallingConv::Fast)
5126     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5127 
5128   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5129          "fastcc not supported on varargs functions");
5130 
5131   // Count how many bytes are to be pushed on the stack, including the linkage
5132   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5133   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5134   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5135   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5136   unsigned NumBytes = LinkageSize;
5137   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5138   unsigned &QFPR_idx = FPR_idx;
5139 
5140   static const MCPhysReg GPR[] = {
5141     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5142     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5143   };
5144   static const MCPhysReg VR[] = {
5145     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5146     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5147   };
5148 
5149   const unsigned NumGPRs = array_lengthof(GPR);
5150   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5151   const unsigned NumVRs  = array_lengthof(VR);
5152   const unsigned NumQFPRs = NumFPRs;
5153 
5154   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5155   // can be passed to the callee in registers.
5156   // For the fast calling convention, there is another check below.
5157   // Note: keep consistent with LowerFormalArguments_64SVR4()
5158   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5159   if (!HasParameterArea) {
5160     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5161     unsigned AvailableFPRs = NumFPRs;
5162     unsigned AvailableVRs = NumVRs;
5163     unsigned NumBytesTmp = NumBytes;
5164     for (unsigned i = 0; i != NumOps; ++i) {
5165       if (Outs[i].Flags.isNest()) continue;
5166       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5167                                 PtrByteSize, LinkageSize, ParamAreaSize,
5168                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5169                                 Subtarget.hasQPX()))
5170         HasParameterArea = true;
5171     }
5172   }
5173 
5174   // When using the fast calling convention, we don't provide backing for
5175   // arguments that will be in registers.
5176   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5177 
5178   // Add up all the space actually used.
5179   for (unsigned i = 0; i != NumOps; ++i) {
5180     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5181     EVT ArgVT = Outs[i].VT;
5182     EVT OrigVT = Outs[i].ArgVT;
5183 
5184     if (Flags.isNest())
5185       continue;
5186 
5187     if (CallConv == CallingConv::Fast) {
5188       if (Flags.isByVal())
5189         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5190       else
5191         switch (ArgVT.getSimpleVT().SimpleTy) {
5192         default: llvm_unreachable("Unexpected ValueType for argument!");
5193         case MVT::i1:
5194         case MVT::i32:
5195         case MVT::i64:
5196           if (++NumGPRsUsed <= NumGPRs)
5197             continue;
5198           break;
5199         case MVT::v4i32:
5200         case MVT::v8i16:
5201         case MVT::v16i8:
5202         case MVT::v2f64:
5203         case MVT::v2i64:
5204         case MVT::v1i128:
5205           if (++NumVRsUsed <= NumVRs)
5206             continue;
5207           break;
5208         case MVT::v4f32:
5209           // When using QPX, this is handled like a FP register, otherwise, it
5210           // is an Altivec register.
5211           if (Subtarget.hasQPX()) {
5212             if (++NumFPRsUsed <= NumFPRs)
5213               continue;
5214           } else {
5215             if (++NumVRsUsed <= NumVRs)
5216               continue;
5217           }
5218           break;
5219         case MVT::f32:
5220         case MVT::f64:
5221         case MVT::v4f64: // QPX
5222         case MVT::v4i1:  // QPX
5223           if (++NumFPRsUsed <= NumFPRs)
5224             continue;
5225           break;
5226         }
5227     }
5228 
5229     /* Respect alignment of argument on the stack.  */
5230     unsigned Align =
5231       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5232     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5233 
5234     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5235     if (Flags.isInConsecutiveRegsLast())
5236       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5237   }
5238 
5239   unsigned NumBytesActuallyUsed = NumBytes;
5240 
5241   // In the old ELFv1 ABI,
5242   // the prolog code of the callee may store up to 8 GPR argument registers to
5243   // the stack, allowing va_start to index over them in memory if its varargs.
5244   // Because we cannot tell if this is needed on the caller side, we have to
5245   // conservatively assume that it is needed.  As such, make sure we have at
5246   // least enough stack space for the caller to store the 8 GPRs.
5247   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5248   // really requires memory operands, e.g. a vararg function.
5249   if (HasParameterArea)
5250     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5251   else
5252     NumBytes = LinkageSize;
5253 
5254   // Tail call needs the stack to be aligned.
5255   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5256       CallConv == CallingConv::Fast)
5257     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5258 
5259   int SPDiff = 0;
5260 
5261   // Calculate by how many bytes the stack has to be adjusted in case of tail
5262   // call optimization.
5263   if (!IsSibCall)
5264     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5265 
5266   // To protect arguments on the stack from being clobbered in a tail call,
5267   // force all the loads to happen before doing any other lowering.
5268   if (isTailCall)
5269     Chain = DAG.getStackArgumentTokenFactor(Chain);
5270 
5271   // Adjust the stack pointer for the new arguments...
5272   // These operations are automatically eliminated by the prolog/epilog pass
5273   if (!IsSibCall)
5274     Chain = DAG.getCALLSEQ_START(Chain,
5275                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5276   SDValue CallSeqStart = Chain;
5277 
5278   // Load the return address and frame pointer so it can be move somewhere else
5279   // later.
5280   SDValue LROp, FPOp;
5281   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5282 
5283   // Set up a copy of the stack pointer for use loading and storing any
5284   // arguments that may not fit in the registers available for argument
5285   // passing.
5286   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5287 
5288   // Figure out which arguments are going to go in registers, and which in
5289   // memory.  Also, if this is a vararg function, floating point operations
5290   // must be stored to our stack, and loaded into integer regs as well, if
5291   // any integer regs are available for argument passing.
5292   unsigned ArgOffset = LinkageSize;
5293 
5294   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5295   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5296 
5297   SmallVector<SDValue, 8> MemOpChains;
5298   for (unsigned i = 0; i != NumOps; ++i) {
5299     SDValue Arg = OutVals[i];
5300     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5301     EVT ArgVT = Outs[i].VT;
5302     EVT OrigVT = Outs[i].ArgVT;
5303 
5304     // PtrOff will be used to store the current argument to the stack if a
5305     // register cannot be found for it.
5306     SDValue PtrOff;
5307 
5308     // We re-align the argument offset for each argument, except when using the
5309     // fast calling convention, when we need to make sure we do that only when
5310     // we'll actually use a stack slot.
5311     auto ComputePtrOff = [&]() {
5312       /* Respect alignment of argument on the stack.  */
5313       unsigned Align =
5314         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5315       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5316 
5317       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5318 
5319       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5320     };
5321 
5322     if (CallConv != CallingConv::Fast) {
5323       ComputePtrOff();
5324 
5325       /* Compute GPR index associated with argument offset.  */
5326       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5327       GPR_idx = std::min(GPR_idx, NumGPRs);
5328     }
5329 
5330     // Promote integers to 64-bit values.
5331     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5332       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5333       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5334       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5335     }
5336 
5337     // FIXME memcpy is used way more than necessary.  Correctness first.
5338     // Note: "by value" is code for passing a structure by value, not
5339     // basic types.
5340     if (Flags.isByVal()) {
5341       // Note: Size includes alignment padding, so
5342       //   struct x { short a; char b; }
5343       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5344       // These are the proper values we need for right-justifying the
5345       // aggregate in a parameter register.
5346       unsigned Size = Flags.getByValSize();
5347 
5348       // An empty aggregate parameter takes up no storage and no
5349       // registers.
5350       if (Size == 0)
5351         continue;
5352 
5353       if (CallConv == CallingConv::Fast)
5354         ComputePtrOff();
5355 
5356       // All aggregates smaller than 8 bytes must be passed right-justified.
5357       if (Size==1 || Size==2 || Size==4) {
5358         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5359         if (GPR_idx != NumGPRs) {
5360           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5361                                         MachinePointerInfo(), VT);
5362           MemOpChains.push_back(Load.getValue(1));
5363           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5364 
5365           ArgOffset += PtrByteSize;
5366           continue;
5367         }
5368       }
5369 
5370       if (GPR_idx == NumGPRs && Size < 8) {
5371         SDValue AddPtr = PtrOff;
5372         if (!isLittleEndian) {
5373           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5374                                           PtrOff.getValueType());
5375           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5376         }
5377         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5378                                                           CallSeqStart,
5379                                                           Flags, DAG, dl);
5380         ArgOffset += PtrByteSize;
5381         continue;
5382       }
5383       // Copy entire object into memory.  There are cases where gcc-generated
5384       // code assumes it is there, even if it could be put entirely into
5385       // registers.  (This is not what the doc says.)
5386 
5387       // FIXME: The above statement is likely due to a misunderstanding of the
5388       // documents.  All arguments must be copied into the parameter area BY
5389       // THE CALLEE in the event that the callee takes the address of any
5390       // formal argument.  That has not yet been implemented.  However, it is
5391       // reasonable to use the stack area as a staging area for the register
5392       // load.
5393 
5394       // Skip this for small aggregates, as we will use the same slot for a
5395       // right-justified copy, below.
5396       if (Size >= 8)
5397         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5398                                                           CallSeqStart,
5399                                                           Flags, DAG, dl);
5400 
5401       // When a register is available, pass a small aggregate right-justified.
5402       if (Size < 8 && GPR_idx != NumGPRs) {
5403         // The easiest way to get this right-justified in a register
5404         // is to copy the structure into the rightmost portion of a
5405         // local variable slot, then load the whole slot into the
5406         // register.
5407         // FIXME: The memcpy seems to produce pretty awful code for
5408         // small aggregates, particularly for packed ones.
5409         // FIXME: It would be preferable to use the slot in the
5410         // parameter save area instead of a new local variable.
5411         SDValue AddPtr = PtrOff;
5412         if (!isLittleEndian) {
5413           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5414           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5415         }
5416         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5417                                                           CallSeqStart,
5418                                                           Flags, DAG, dl);
5419 
5420         // Load the slot into the register.
5421         SDValue Load =
5422             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5423         MemOpChains.push_back(Load.getValue(1));
5424         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5425 
5426         // Done with this argument.
5427         ArgOffset += PtrByteSize;
5428         continue;
5429       }
5430 
5431       // For aggregates larger than PtrByteSize, copy the pieces of the
5432       // object that fit into registers from the parameter save area.
5433       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5434         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5435         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5436         if (GPR_idx != NumGPRs) {
5437           SDValue Load =
5438               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5439           MemOpChains.push_back(Load.getValue(1));
5440           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5441           ArgOffset += PtrByteSize;
5442         } else {
5443           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5444           break;
5445         }
5446       }
5447       continue;
5448     }
5449 
5450     switch (Arg.getSimpleValueType().SimpleTy) {
5451     default: llvm_unreachable("Unexpected ValueType for argument!");
5452     case MVT::i1:
5453     case MVT::i32:
5454     case MVT::i64:
5455       if (Flags.isNest()) {
5456         // The 'nest' parameter, if any, is passed in R11.
5457         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5458         hasNest = true;
5459         break;
5460       }
5461 
5462       // These can be scalar arguments or elements of an integer array type
5463       // passed directly.  Clang may use those instead of "byval" aggregate
5464       // types to avoid forcing arguments to memory unnecessarily.
5465       if (GPR_idx != NumGPRs) {
5466         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5467       } else {
5468         if (CallConv == CallingConv::Fast)
5469           ComputePtrOff();
5470 
5471         assert(HasParameterArea &&
5472                "Parameter area must exist to pass an argument in memory.");
5473         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5474                          true, isTailCall, false, MemOpChains,
5475                          TailCallArguments, dl);
5476         if (CallConv == CallingConv::Fast)
5477           ArgOffset += PtrByteSize;
5478       }
5479       if (CallConv != CallingConv::Fast)
5480         ArgOffset += PtrByteSize;
5481       break;
5482     case MVT::f32:
5483     case MVT::f64: {
5484       // These can be scalar arguments or elements of a float array type
5485       // passed directly.  The latter are used to implement ELFv2 homogenous
5486       // float aggregates.
5487 
5488       // Named arguments go into FPRs first, and once they overflow, the
5489       // remaining arguments go into GPRs and then the parameter save area.
5490       // Unnamed arguments for vararg functions always go to GPRs and
5491       // then the parameter save area.  For now, put all arguments to vararg
5492       // routines always in both locations (FPR *and* GPR or stack slot).
5493       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5494       bool NeededLoad = false;
5495 
5496       // First load the argument into the next available FPR.
5497       if (FPR_idx != NumFPRs)
5498         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5499 
5500       // Next, load the argument into GPR or stack slot if needed.
5501       if (!NeedGPROrStack)
5502         ;
5503       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5504         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5505         // once we support fp <-> gpr moves.
5506 
5507         // In the non-vararg case, this can only ever happen in the
5508         // presence of f32 array types, since otherwise we never run
5509         // out of FPRs before running out of GPRs.
5510         SDValue ArgVal;
5511 
5512         // Double values are always passed in a single GPR.
5513         if (Arg.getValueType() != MVT::f32) {
5514           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5515 
5516         // Non-array float values are extended and passed in a GPR.
5517         } else if (!Flags.isInConsecutiveRegs()) {
5518           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5519           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5520 
5521         // If we have an array of floats, we collect every odd element
5522         // together with its predecessor into one GPR.
5523         } else if (ArgOffset % PtrByteSize != 0) {
5524           SDValue Lo, Hi;
5525           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5526           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5527           if (!isLittleEndian)
5528             std::swap(Lo, Hi);
5529           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5530 
5531         // The final element, if even, goes into the first half of a GPR.
5532         } else if (Flags.isInConsecutiveRegsLast()) {
5533           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5534           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5535           if (!isLittleEndian)
5536             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5537                                  DAG.getConstant(32, dl, MVT::i32));
5538 
5539         // Non-final even elements are skipped; they will be handled
5540         // together the with subsequent argument on the next go-around.
5541         } else
5542           ArgVal = SDValue();
5543 
5544         if (ArgVal.getNode())
5545           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5546       } else {
5547         if (CallConv == CallingConv::Fast)
5548           ComputePtrOff();
5549 
5550         // Single-precision floating-point values are mapped to the
5551         // second (rightmost) word of the stack doubleword.
5552         if (Arg.getValueType() == MVT::f32 &&
5553             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5554           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5555           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5556         }
5557 
5558         assert(HasParameterArea &&
5559                "Parameter area must exist to pass an argument in memory.");
5560         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5561                          true, isTailCall, false, MemOpChains,
5562                          TailCallArguments, dl);
5563 
5564         NeededLoad = true;
5565       }
5566       // When passing an array of floats, the array occupies consecutive
5567       // space in the argument area; only round up to the next doubleword
5568       // at the end of the array.  Otherwise, each float takes 8 bytes.
5569       if (CallConv != CallingConv::Fast || NeededLoad) {
5570         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5571                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5572         if (Flags.isInConsecutiveRegsLast())
5573           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5574       }
5575       break;
5576     }
5577     case MVT::v4f32:
5578     case MVT::v4i32:
5579     case MVT::v8i16:
5580     case MVT::v16i8:
5581     case MVT::v2f64:
5582     case MVT::v2i64:
5583     case MVT::v1i128:
5584       if (!Subtarget.hasQPX()) {
5585       // These can be scalar arguments or elements of a vector array type
5586       // passed directly.  The latter are used to implement ELFv2 homogenous
5587       // vector aggregates.
5588 
5589       // For a varargs call, named arguments go into VRs or on the stack as
5590       // usual; unnamed arguments always go to the stack or the corresponding
5591       // GPRs when within range.  For now, we always put the value in both
5592       // locations (or even all three).
5593       if (isVarArg) {
5594         assert(HasParameterArea &&
5595                "Parameter area must exist if we have a varargs call.");
5596         // We could elide this store in the case where the object fits
5597         // entirely in R registers.  Maybe later.
5598         SDValue Store =
5599             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5600         MemOpChains.push_back(Store);
5601         if (VR_idx != NumVRs) {
5602           SDValue Load =
5603               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5604           MemOpChains.push_back(Load.getValue(1));
5605           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5606         }
5607         ArgOffset += 16;
5608         for (unsigned i=0; i<16; i+=PtrByteSize) {
5609           if (GPR_idx == NumGPRs)
5610             break;
5611           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5612                                    DAG.getConstant(i, dl, PtrVT));
5613           SDValue Load =
5614               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5615           MemOpChains.push_back(Load.getValue(1));
5616           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5617         }
5618         break;
5619       }
5620 
5621       // Non-varargs Altivec params go into VRs or on the stack.
5622       if (VR_idx != NumVRs) {
5623         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5624       } else {
5625         if (CallConv == CallingConv::Fast)
5626           ComputePtrOff();
5627 
5628         assert(HasParameterArea &&
5629                "Parameter area must exist to pass an argument in memory.");
5630         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5631                          true, isTailCall, true, MemOpChains,
5632                          TailCallArguments, dl);
5633         if (CallConv == CallingConv::Fast)
5634           ArgOffset += 16;
5635       }
5636 
5637       if (CallConv != CallingConv::Fast)
5638         ArgOffset += 16;
5639       break;
5640       } // not QPX
5641 
5642       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5643              "Invalid QPX parameter type");
5644 
5645       /* fall through */
5646     case MVT::v4f64:
5647     case MVT::v4i1: {
5648       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5649       if (isVarArg) {
5650         assert(HasParameterArea &&
5651                "Parameter area must exist if we have a varargs call.");
5652         // We could elide this store in the case where the object fits
5653         // entirely in R registers.  Maybe later.
5654         SDValue Store =
5655             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5656         MemOpChains.push_back(Store);
5657         if (QFPR_idx != NumQFPRs) {
5658           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5659                                      PtrOff, MachinePointerInfo());
5660           MemOpChains.push_back(Load.getValue(1));
5661           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5662         }
5663         ArgOffset += (IsF32 ? 16 : 32);
5664         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5665           if (GPR_idx == NumGPRs)
5666             break;
5667           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5668                                    DAG.getConstant(i, dl, PtrVT));
5669           SDValue Load =
5670               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5671           MemOpChains.push_back(Load.getValue(1));
5672           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5673         }
5674         break;
5675       }
5676 
5677       // Non-varargs QPX params go into registers or on the stack.
5678       if (QFPR_idx != NumQFPRs) {
5679         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5680       } else {
5681         if (CallConv == CallingConv::Fast)
5682           ComputePtrOff();
5683 
5684         assert(HasParameterArea &&
5685                "Parameter area must exist to pass an argument in memory.");
5686         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5687                          true, isTailCall, true, MemOpChains,
5688                          TailCallArguments, dl);
5689         if (CallConv == CallingConv::Fast)
5690           ArgOffset += (IsF32 ? 16 : 32);
5691       }
5692 
5693       if (CallConv != CallingConv::Fast)
5694         ArgOffset += (IsF32 ? 16 : 32);
5695       break;
5696       }
5697     }
5698   }
5699 
5700   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5701          "mismatch in size of parameter area");
5702   (void)NumBytesActuallyUsed;
5703 
5704   if (!MemOpChains.empty())
5705     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5706 
5707   // Check if this is an indirect call (MTCTR/BCTRL).
5708   // See PrepareCall() for more information about calls through function
5709   // pointers in the 64-bit SVR4 ABI.
5710   if (!isTailCall && !isPatchPoint &&
5711       !isFunctionGlobalAddress(Callee) &&
5712       !isa<ExternalSymbolSDNode>(Callee)) {
5713     // Load r2 into a virtual register and store it to the TOC save area.
5714     setUsesTOCBasePtr(DAG);
5715     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5716     // TOC save area offset.
5717     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5718     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5719     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5720     Chain = DAG.getStore(
5721         Val.getValue(1), dl, Val, AddPtr,
5722         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5723     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5724     // This does not mean the MTCTR instruction must use R12; it's easier
5725     // to model this as an extra parameter, so do that.
5726     if (isELFv2ABI && !isPatchPoint)
5727       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5728   }
5729 
5730   // Build a sequence of copy-to-reg nodes chained together with token chain
5731   // and flag operands which copy the outgoing args into the appropriate regs.
5732   SDValue InFlag;
5733   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5734     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5735                              RegsToPass[i].second, InFlag);
5736     InFlag = Chain.getValue(1);
5737   }
5738 
5739   if (isTailCall && !IsSibCall)
5740     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5741                     TailCallArguments);
5742 
5743   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5744                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5745                     SPDiff, NumBytes, Ins, InVals, CS);
5746 }
5747 
5748 SDValue PPCTargetLowering::LowerCall_Darwin(
5749     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5750     bool isTailCall, bool isPatchPoint,
5751     const SmallVectorImpl<ISD::OutputArg> &Outs,
5752     const SmallVectorImpl<SDValue> &OutVals,
5753     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5754     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5755     ImmutableCallSite *CS) const {
5756   unsigned NumOps = Outs.size();
5757 
5758   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5759   bool isPPC64 = PtrVT == MVT::i64;
5760   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5761 
5762   MachineFunction &MF = DAG.getMachineFunction();
5763 
5764   // Mark this function as potentially containing a function that contains a
5765   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5766   // and restoring the callers stack pointer in this functions epilog. This is
5767   // done because by tail calling the called function might overwrite the value
5768   // in this function's (MF) stack pointer stack slot 0(SP).
5769   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5770       CallConv == CallingConv::Fast)
5771     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5772 
5773   // Count how many bytes are to be pushed on the stack, including the linkage
5774   // area, and parameter passing area.  We start with 24/48 bytes, which is
5775   // prereserved space for [SP][CR][LR][3 x unused].
5776   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5777   unsigned NumBytes = LinkageSize;
5778 
5779   // Add up all the space actually used.
5780   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5781   // they all go in registers, but we must reserve stack space for them for
5782   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5783   // assigned stack space in order, with padding so Altivec parameters are
5784   // 16-byte aligned.
5785   unsigned nAltivecParamsAtEnd = 0;
5786   for (unsigned i = 0; i != NumOps; ++i) {
5787     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5788     EVT ArgVT = Outs[i].VT;
5789     // Varargs Altivec parameters are padded to a 16 byte boundary.
5790     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5791         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5792         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5793       if (!isVarArg && !isPPC64) {
5794         // Non-varargs Altivec parameters go after all the non-Altivec
5795         // parameters; handle those later so we know how much padding we need.
5796         nAltivecParamsAtEnd++;
5797         continue;
5798       }
5799       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5800       NumBytes = ((NumBytes+15)/16)*16;
5801     }
5802     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5803   }
5804 
5805   // Allow for Altivec parameters at the end, if needed.
5806   if (nAltivecParamsAtEnd) {
5807     NumBytes = ((NumBytes+15)/16)*16;
5808     NumBytes += 16*nAltivecParamsAtEnd;
5809   }
5810 
5811   // The prolog code of the callee may store up to 8 GPR argument registers to
5812   // the stack, allowing va_start to index over them in memory if its varargs.
5813   // Because we cannot tell if this is needed on the caller side, we have to
5814   // conservatively assume that it is needed.  As such, make sure we have at
5815   // least enough stack space for the caller to store the 8 GPRs.
5816   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5817 
5818   // Tail call needs the stack to be aligned.
5819   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5820       CallConv == CallingConv::Fast)
5821     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5822 
5823   // Calculate by how many bytes the stack has to be adjusted in case of tail
5824   // call optimization.
5825   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5826 
5827   // To protect arguments on the stack from being clobbered in a tail call,
5828   // force all the loads to happen before doing any other lowering.
5829   if (isTailCall)
5830     Chain = DAG.getStackArgumentTokenFactor(Chain);
5831 
5832   // Adjust the stack pointer for the new arguments...
5833   // These operations are automatically eliminated by the prolog/epilog pass
5834   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5835                                dl);
5836   SDValue CallSeqStart = Chain;
5837 
5838   // Load the return address and frame pointer so it can be move somewhere else
5839   // later.
5840   SDValue LROp, FPOp;
5841   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5842 
5843   // Set up a copy of the stack pointer for use loading and storing any
5844   // arguments that may not fit in the registers available for argument
5845   // passing.
5846   SDValue StackPtr;
5847   if (isPPC64)
5848     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5849   else
5850     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5851 
5852   // Figure out which arguments are going to go in registers, and which in
5853   // memory.  Also, if this is a vararg function, floating point operations
5854   // must be stored to our stack, and loaded into integer regs as well, if
5855   // any integer regs are available for argument passing.
5856   unsigned ArgOffset = LinkageSize;
5857   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5858 
5859   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5860     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5861     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5862   };
5863   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5864     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5865     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5866   };
5867   static const MCPhysReg VR[] = {
5868     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5869     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5870   };
5871   const unsigned NumGPRs = array_lengthof(GPR_32);
5872   const unsigned NumFPRs = 13;
5873   const unsigned NumVRs  = array_lengthof(VR);
5874 
5875   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5876 
5877   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5878   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5879 
5880   SmallVector<SDValue, 8> MemOpChains;
5881   for (unsigned i = 0; i != NumOps; ++i) {
5882     SDValue Arg = OutVals[i];
5883     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5884 
5885     // PtrOff will be used to store the current argument to the stack if a
5886     // register cannot be found for it.
5887     SDValue PtrOff;
5888 
5889     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5890 
5891     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5892 
5893     // On PPC64, promote integers to 64-bit values.
5894     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5895       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5896       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5897       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5898     }
5899 
5900     // FIXME memcpy is used way more than necessary.  Correctness first.
5901     // Note: "by value" is code for passing a structure by value, not
5902     // basic types.
5903     if (Flags.isByVal()) {
5904       unsigned Size = Flags.getByValSize();
5905       // Very small objects are passed right-justified.  Everything else is
5906       // passed left-justified.
5907       if (Size==1 || Size==2) {
5908         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5909         if (GPR_idx != NumGPRs) {
5910           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5911                                         MachinePointerInfo(), VT);
5912           MemOpChains.push_back(Load.getValue(1));
5913           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5914 
5915           ArgOffset += PtrByteSize;
5916         } else {
5917           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5918                                           PtrOff.getValueType());
5919           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5920           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5921                                                             CallSeqStart,
5922                                                             Flags, DAG, dl);
5923           ArgOffset += PtrByteSize;
5924         }
5925         continue;
5926       }
5927       // Copy entire object into memory.  There are cases where gcc-generated
5928       // code assumes it is there, even if it could be put entirely into
5929       // registers.  (This is not what the doc says.)
5930       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5931                                                         CallSeqStart,
5932                                                         Flags, DAG, dl);
5933 
5934       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5935       // copy the pieces of the object that fit into registers from the
5936       // parameter save area.
5937       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5938         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5939         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5940         if (GPR_idx != NumGPRs) {
5941           SDValue Load =
5942               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5943           MemOpChains.push_back(Load.getValue(1));
5944           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5945           ArgOffset += PtrByteSize;
5946         } else {
5947           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5948           break;
5949         }
5950       }
5951       continue;
5952     }
5953 
5954     switch (Arg.getSimpleValueType().SimpleTy) {
5955     default: llvm_unreachable("Unexpected ValueType for argument!");
5956     case MVT::i1:
5957     case MVT::i32:
5958     case MVT::i64:
5959       if (GPR_idx != NumGPRs) {
5960         if (Arg.getValueType() == MVT::i1)
5961           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5962 
5963         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5964       } else {
5965         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5966                          isPPC64, isTailCall, false, MemOpChains,
5967                          TailCallArguments, dl);
5968       }
5969       ArgOffset += PtrByteSize;
5970       break;
5971     case MVT::f32:
5972     case MVT::f64:
5973       if (FPR_idx != NumFPRs) {
5974         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5975 
5976         if (isVarArg) {
5977           SDValue Store =
5978               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5979           MemOpChains.push_back(Store);
5980 
5981           // Float varargs are always shadowed in available integer registers
5982           if (GPR_idx != NumGPRs) {
5983             SDValue Load =
5984                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5985             MemOpChains.push_back(Load.getValue(1));
5986             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5987           }
5988           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5989             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5990             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5991             SDValue Load =
5992                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5993             MemOpChains.push_back(Load.getValue(1));
5994             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5995           }
5996         } else {
5997           // If we have any FPRs remaining, we may also have GPRs remaining.
5998           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5999           // GPRs.
6000           if (GPR_idx != NumGPRs)
6001             ++GPR_idx;
6002           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6003               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6004             ++GPR_idx;
6005         }
6006       } else
6007         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6008                          isPPC64, isTailCall, false, MemOpChains,
6009                          TailCallArguments, dl);
6010       if (isPPC64)
6011         ArgOffset += 8;
6012       else
6013         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6014       break;
6015     case MVT::v4f32:
6016     case MVT::v4i32:
6017     case MVT::v8i16:
6018     case MVT::v16i8:
6019       if (isVarArg) {
6020         // These go aligned on the stack, or in the corresponding R registers
6021         // when within range.  The Darwin PPC ABI doc claims they also go in
6022         // V registers; in fact gcc does this only for arguments that are
6023         // prototyped, not for those that match the ...  We do it for all
6024         // arguments, seems to work.
6025         while (ArgOffset % 16 !=0) {
6026           ArgOffset += PtrByteSize;
6027           if (GPR_idx != NumGPRs)
6028             GPR_idx++;
6029         }
6030         // We could elide this store in the case where the object fits
6031         // entirely in R registers.  Maybe later.
6032         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6033                              DAG.getConstant(ArgOffset, dl, PtrVT));
6034         SDValue Store =
6035             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6036         MemOpChains.push_back(Store);
6037         if (VR_idx != NumVRs) {
6038           SDValue Load =
6039               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6040           MemOpChains.push_back(Load.getValue(1));
6041           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6042         }
6043         ArgOffset += 16;
6044         for (unsigned i=0; i<16; i+=PtrByteSize) {
6045           if (GPR_idx == NumGPRs)
6046             break;
6047           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6048                                    DAG.getConstant(i, dl, PtrVT));
6049           SDValue Load =
6050               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6051           MemOpChains.push_back(Load.getValue(1));
6052           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6053         }
6054         break;
6055       }
6056 
6057       // Non-varargs Altivec params generally go in registers, but have
6058       // stack space allocated at the end.
6059       if (VR_idx != NumVRs) {
6060         // Doesn't have GPR space allocated.
6061         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6062       } else if (nAltivecParamsAtEnd==0) {
6063         // We are emitting Altivec params in order.
6064         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6065                          isPPC64, isTailCall, true, MemOpChains,
6066                          TailCallArguments, dl);
6067         ArgOffset += 16;
6068       }
6069       break;
6070     }
6071   }
6072   // If all Altivec parameters fit in registers, as they usually do,
6073   // they get stack space following the non-Altivec parameters.  We
6074   // don't track this here because nobody below needs it.
6075   // If there are more Altivec parameters than fit in registers emit
6076   // the stores here.
6077   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6078     unsigned j = 0;
6079     // Offset is aligned; skip 1st 12 params which go in V registers.
6080     ArgOffset = ((ArgOffset+15)/16)*16;
6081     ArgOffset += 12*16;
6082     for (unsigned i = 0; i != NumOps; ++i) {
6083       SDValue Arg = OutVals[i];
6084       EVT ArgType = Outs[i].VT;
6085       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6086           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6087         if (++j > NumVRs) {
6088           SDValue PtrOff;
6089           // We are emitting Altivec params in order.
6090           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6091                            isPPC64, isTailCall, true, MemOpChains,
6092                            TailCallArguments, dl);
6093           ArgOffset += 16;
6094         }
6095       }
6096     }
6097   }
6098 
6099   if (!MemOpChains.empty())
6100     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6101 
6102   // On Darwin, R12 must contain the address of an indirect callee.  This does
6103   // not mean the MTCTR instruction must use R12; it's easier to model this as
6104   // an extra parameter, so do that.
6105   if (!isTailCall &&
6106       !isFunctionGlobalAddress(Callee) &&
6107       !isa<ExternalSymbolSDNode>(Callee) &&
6108       !isBLACompatibleAddress(Callee, DAG))
6109     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6110                                                    PPC::R12), Callee));
6111 
6112   // Build a sequence of copy-to-reg nodes chained together with token chain
6113   // and flag operands which copy the outgoing args into the appropriate regs.
6114   SDValue InFlag;
6115   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6116     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6117                              RegsToPass[i].second, InFlag);
6118     InFlag = Chain.getValue(1);
6119   }
6120 
6121   if (isTailCall)
6122     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6123                     TailCallArguments);
6124 
6125   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6126                     /* unused except on PPC64 ELFv1 */ false, DAG,
6127                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6128                     NumBytes, Ins, InVals, CS);
6129 }
6130 
6131 bool
6132 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6133                                   MachineFunction &MF, bool isVarArg,
6134                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6135                                   LLVMContext &Context) const {
6136   SmallVector<CCValAssign, 16> RVLocs;
6137   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6138   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6139 }
6140 
6141 SDValue
6142 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6143                                bool isVarArg,
6144                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6145                                const SmallVectorImpl<SDValue> &OutVals,
6146                                const SDLoc &dl, SelectionDAG &DAG) const {
6147   SmallVector<CCValAssign, 16> RVLocs;
6148   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6149                  *DAG.getContext());
6150   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6151 
6152   SDValue Flag;
6153   SmallVector<SDValue, 4> RetOps(1, Chain);
6154 
6155   // Copy the result values into the output registers.
6156   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6157     CCValAssign &VA = RVLocs[i];
6158     assert(VA.isRegLoc() && "Can only return in registers!");
6159 
6160     SDValue Arg = OutVals[i];
6161 
6162     switch (VA.getLocInfo()) {
6163     default: llvm_unreachable("Unknown loc info!");
6164     case CCValAssign::Full: break;
6165     case CCValAssign::AExt:
6166       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6167       break;
6168     case CCValAssign::ZExt:
6169       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6170       break;
6171     case CCValAssign::SExt:
6172       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6173       break;
6174     }
6175 
6176     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6177     Flag = Chain.getValue(1);
6178     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6179   }
6180 
6181   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6182   const MCPhysReg *I =
6183     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6184   if (I) {
6185     for (; *I; ++I) {
6186 
6187       if (PPC::G8RCRegClass.contains(*I))
6188         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6189       else if (PPC::F8RCRegClass.contains(*I))
6190         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6191       else if (PPC::CRRCRegClass.contains(*I))
6192         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6193       else if (PPC::VRRCRegClass.contains(*I))
6194         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6195       else
6196         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6197     }
6198   }
6199 
6200   RetOps[0] = Chain;  // Update chain.
6201 
6202   // Add the flag if we have it.
6203   if (Flag.getNode())
6204     RetOps.push_back(Flag);
6205 
6206   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6207 }
6208 
6209 SDValue
6210 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6211                                                 SelectionDAG &DAG) const {
6212   SDLoc dl(Op);
6213 
6214   // Get the corect type for integers.
6215   EVT IntVT = Op.getValueType();
6216 
6217   // Get the inputs.
6218   SDValue Chain = Op.getOperand(0);
6219   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6220   // Build a DYNAREAOFFSET node.
6221   SDValue Ops[2] = {Chain, FPSIdx};
6222   SDVTList VTs = DAG.getVTList(IntVT);
6223   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6224 }
6225 
6226 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6227                                              SelectionDAG &DAG) const {
6228   // When we pop the dynamic allocation we need to restore the SP link.
6229   SDLoc dl(Op);
6230 
6231   // Get the corect type for pointers.
6232   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6233 
6234   // Construct the stack pointer operand.
6235   bool isPPC64 = Subtarget.isPPC64();
6236   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6237   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6238 
6239   // Get the operands for the STACKRESTORE.
6240   SDValue Chain = Op.getOperand(0);
6241   SDValue SaveSP = Op.getOperand(1);
6242 
6243   // Load the old link SP.
6244   SDValue LoadLinkSP =
6245       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6246 
6247   // Restore the stack pointer.
6248   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6249 
6250   // Store the old link SP.
6251   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6252 }
6253 
6254 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6255   MachineFunction &MF = DAG.getMachineFunction();
6256   bool isPPC64 = Subtarget.isPPC64();
6257   EVT PtrVT = getPointerTy(MF.getDataLayout());
6258 
6259   // Get current frame pointer save index.  The users of this index will be
6260   // primarily DYNALLOC instructions.
6261   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6262   int RASI = FI->getReturnAddrSaveIndex();
6263 
6264   // If the frame pointer save index hasn't been defined yet.
6265   if (!RASI) {
6266     // Find out what the fix offset of the frame pointer save area.
6267     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6268     // Allocate the frame index for frame pointer save area.
6269     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6270     // Save the result.
6271     FI->setReturnAddrSaveIndex(RASI);
6272   }
6273   return DAG.getFrameIndex(RASI, PtrVT);
6274 }
6275 
6276 SDValue
6277 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6278   MachineFunction &MF = DAG.getMachineFunction();
6279   bool isPPC64 = Subtarget.isPPC64();
6280   EVT PtrVT = getPointerTy(MF.getDataLayout());
6281 
6282   // Get current frame pointer save index.  The users of this index will be
6283   // primarily DYNALLOC instructions.
6284   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6285   int FPSI = FI->getFramePointerSaveIndex();
6286 
6287   // If the frame pointer save index hasn't been defined yet.
6288   if (!FPSI) {
6289     // Find out what the fix offset of the frame pointer save area.
6290     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6291     // Allocate the frame index for frame pointer save area.
6292     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6293     // Save the result.
6294     FI->setFramePointerSaveIndex(FPSI);
6295   }
6296   return DAG.getFrameIndex(FPSI, PtrVT);
6297 }
6298 
6299 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6300                                                    SelectionDAG &DAG) const {
6301   // Get the inputs.
6302   SDValue Chain = Op.getOperand(0);
6303   SDValue Size  = Op.getOperand(1);
6304   SDLoc dl(Op);
6305 
6306   // Get the corect type for pointers.
6307   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6308   // Negate the size.
6309   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6310                                 DAG.getConstant(0, dl, PtrVT), Size);
6311   // Construct a node for the frame pointer save index.
6312   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6313   // Build a DYNALLOC node.
6314   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6315   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6316   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6317 }
6318 
6319 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6320                                                      SelectionDAG &DAG) const {
6321   MachineFunction &MF = DAG.getMachineFunction();
6322 
6323   bool isPPC64 = Subtarget.isPPC64();
6324   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6325 
6326   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6327   return DAG.getFrameIndex(FI, PtrVT);
6328 }
6329 
6330 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6331                                                SelectionDAG &DAG) const {
6332   SDLoc DL(Op);
6333   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6334                      DAG.getVTList(MVT::i32, MVT::Other),
6335                      Op.getOperand(0), Op.getOperand(1));
6336 }
6337 
6338 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6339                                                 SelectionDAG &DAG) const {
6340   SDLoc DL(Op);
6341   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6342                      Op.getOperand(0), Op.getOperand(1));
6343 }
6344 
6345 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6346   if (Op.getValueType().isVector())
6347     return LowerVectorLoad(Op, DAG);
6348 
6349   assert(Op.getValueType() == MVT::i1 &&
6350          "Custom lowering only for i1 loads");
6351 
6352   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6353 
6354   SDLoc dl(Op);
6355   LoadSDNode *LD = cast<LoadSDNode>(Op);
6356 
6357   SDValue Chain = LD->getChain();
6358   SDValue BasePtr = LD->getBasePtr();
6359   MachineMemOperand *MMO = LD->getMemOperand();
6360 
6361   SDValue NewLD =
6362       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6363                      BasePtr, MVT::i8, MMO);
6364   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6365 
6366   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6367   return DAG.getMergeValues(Ops, dl);
6368 }
6369 
6370 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6371   if (Op.getOperand(1).getValueType().isVector())
6372     return LowerVectorStore(Op, DAG);
6373 
6374   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6375          "Custom lowering only for i1 stores");
6376 
6377   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6378 
6379   SDLoc dl(Op);
6380   StoreSDNode *ST = cast<StoreSDNode>(Op);
6381 
6382   SDValue Chain = ST->getChain();
6383   SDValue BasePtr = ST->getBasePtr();
6384   SDValue Value = ST->getValue();
6385   MachineMemOperand *MMO = ST->getMemOperand();
6386 
6387   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6388                       Value);
6389   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6390 }
6391 
6392 // FIXME: Remove this once the ANDI glue bug is fixed:
6393 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6394   assert(Op.getValueType() == MVT::i1 &&
6395          "Custom lowering only for i1 results");
6396 
6397   SDLoc DL(Op);
6398   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6399                      Op.getOperand(0));
6400 }
6401 
6402 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6403 /// possible.
6404 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6405   // Not FP? Not a fsel.
6406   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6407       !Op.getOperand(2).getValueType().isFloatingPoint())
6408     return Op;
6409 
6410   // We might be able to do better than this under some circumstances, but in
6411   // general, fsel-based lowering of select is a finite-math-only optimization.
6412   // For more information, see section F.3 of the 2.06 ISA specification.
6413   if (!DAG.getTarget().Options.NoInfsFPMath ||
6414       !DAG.getTarget().Options.NoNaNsFPMath)
6415     return Op;
6416   // TODO: Propagate flags from the select rather than global settings.
6417   SDNodeFlags Flags;
6418   Flags.setNoInfs(true);
6419   Flags.setNoNaNs(true);
6420 
6421   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6422 
6423   EVT ResVT = Op.getValueType();
6424   EVT CmpVT = Op.getOperand(0).getValueType();
6425   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6426   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6427   SDLoc dl(Op);
6428 
6429   // If the RHS of the comparison is a 0.0, we don't need to do the
6430   // subtraction at all.
6431   SDValue Sel1;
6432   if (isFloatingPointZero(RHS))
6433     switch (CC) {
6434     default: break;       // SETUO etc aren't handled by fsel.
6435     case ISD::SETNE:
6436       std::swap(TV, FV);
6437     case ISD::SETEQ:
6438       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6439         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6440       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6441       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6442         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6443       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6444                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6445     case ISD::SETULT:
6446     case ISD::SETLT:
6447       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6448     case ISD::SETOGE:
6449     case ISD::SETGE:
6450       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6451         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6452       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6453     case ISD::SETUGT:
6454     case ISD::SETGT:
6455       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6456     case ISD::SETOLE:
6457     case ISD::SETLE:
6458       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6459         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6460       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6461                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6462     }
6463 
6464   SDValue Cmp;
6465   switch (CC) {
6466   default: break;       // SETUO etc aren't handled by fsel.
6467   case ISD::SETNE:
6468     std::swap(TV, FV);
6469   case ISD::SETEQ:
6470     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6471     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6472       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6473     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6474     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6475       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6476     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6477                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6478   case ISD::SETULT:
6479   case ISD::SETLT:
6480     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6481     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6482       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6483     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6484   case ISD::SETOGE:
6485   case ISD::SETGE:
6486     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6487     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6488       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6489     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6490   case ISD::SETUGT:
6491   case ISD::SETGT:
6492     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6493     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6494       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6495     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6496   case ISD::SETOLE:
6497   case ISD::SETLE:
6498     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6499     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6500       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6501     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6502   }
6503   return Op;
6504 }
6505 
6506 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6507                                                SelectionDAG &DAG,
6508                                                const SDLoc &dl) const {
6509   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6510   SDValue Src = Op.getOperand(0);
6511   if (Src.getValueType() == MVT::f32)
6512     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6513 
6514   SDValue Tmp;
6515   switch (Op.getSimpleValueType().SimpleTy) {
6516   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6517   case MVT::i32:
6518     Tmp = DAG.getNode(
6519         Op.getOpcode() == ISD::FP_TO_SINT
6520             ? PPCISD::FCTIWZ
6521             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6522         dl, MVT::f64, Src);
6523     break;
6524   case MVT::i64:
6525     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6526            "i64 FP_TO_UINT is supported only with FPCVT");
6527     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6528                                                         PPCISD::FCTIDUZ,
6529                       dl, MVT::f64, Src);
6530     break;
6531   }
6532 
6533   // Convert the FP value to an int value through memory.
6534   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6535     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6536   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6537   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6538   MachinePointerInfo MPI =
6539       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6540 
6541   // Emit a store to the stack slot.
6542   SDValue Chain;
6543   if (i32Stack) {
6544     MachineFunction &MF = DAG.getMachineFunction();
6545     MachineMemOperand *MMO =
6546       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6547     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6548     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6549               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6550   } else
6551     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6552 
6553   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6554   // add in a bias on big endian.
6555   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6556     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6557                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6558     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6559   }
6560 
6561   RLI.Chain = Chain;
6562   RLI.Ptr = FIPtr;
6563   RLI.MPI = MPI;
6564 }
6565 
6566 /// \brief Custom lowers floating point to integer conversions to use
6567 /// the direct move instructions available in ISA 2.07 to avoid the
6568 /// need for load/store combinations.
6569 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6570                                                     SelectionDAG &DAG,
6571                                                     const SDLoc &dl) const {
6572   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6573   SDValue Src = Op.getOperand(0);
6574 
6575   if (Src.getValueType() == MVT::f32)
6576     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6577 
6578   SDValue Tmp;
6579   switch (Op.getSimpleValueType().SimpleTy) {
6580   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6581   case MVT::i32:
6582     Tmp = DAG.getNode(
6583         Op.getOpcode() == ISD::FP_TO_SINT
6584             ? PPCISD::FCTIWZ
6585             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6586         dl, MVT::f64, Src);
6587     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6588     break;
6589   case MVT::i64:
6590     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6591            "i64 FP_TO_UINT is supported only with FPCVT");
6592     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6593                                                         PPCISD::FCTIDUZ,
6594                       dl, MVT::f64, Src);
6595     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6596     break;
6597   }
6598   return Tmp;
6599 }
6600 
6601 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6602                                           const SDLoc &dl) const {
6603   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6604     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6605 
6606   ReuseLoadInfo RLI;
6607   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6608 
6609   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6610                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6611 }
6612 
6613 // We're trying to insert a regular store, S, and then a load, L. If the
6614 // incoming value, O, is a load, we might just be able to have our load use the
6615 // address used by O. However, we don't know if anything else will store to
6616 // that address before we can load from it. To prevent this situation, we need
6617 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6618 // the same chain operand as O, we create a token factor from the chain results
6619 // of O and L, and we replace all uses of O's chain result with that token
6620 // factor (see spliceIntoChain below for this last part).
6621 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6622                                             ReuseLoadInfo &RLI,
6623                                             SelectionDAG &DAG,
6624                                             ISD::LoadExtType ET) const {
6625   SDLoc dl(Op);
6626   if (ET == ISD::NON_EXTLOAD &&
6627       (Op.getOpcode() == ISD::FP_TO_UINT ||
6628        Op.getOpcode() == ISD::FP_TO_SINT) &&
6629       isOperationLegalOrCustom(Op.getOpcode(),
6630                                Op.getOperand(0).getValueType())) {
6631 
6632     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6633     return true;
6634   }
6635 
6636   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6637   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6638       LD->isNonTemporal())
6639     return false;
6640   if (LD->getMemoryVT() != MemVT)
6641     return false;
6642 
6643   RLI.Ptr = LD->getBasePtr();
6644   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6645     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6646            "Non-pre-inc AM on PPC?");
6647     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6648                           LD->getOffset());
6649   }
6650 
6651   RLI.Chain = LD->getChain();
6652   RLI.MPI = LD->getPointerInfo();
6653   RLI.IsDereferenceable = LD->isDereferenceable();
6654   RLI.IsInvariant = LD->isInvariant();
6655   RLI.Alignment = LD->getAlignment();
6656   RLI.AAInfo = LD->getAAInfo();
6657   RLI.Ranges = LD->getRanges();
6658 
6659   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6660   return true;
6661 }
6662 
6663 // Given the head of the old chain, ResChain, insert a token factor containing
6664 // it and NewResChain, and make users of ResChain now be users of that token
6665 // factor.
6666 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6667                                         SDValue NewResChain,
6668                                         SelectionDAG &DAG) const {
6669   if (!ResChain)
6670     return;
6671 
6672   SDLoc dl(NewResChain);
6673 
6674   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6675                            NewResChain, DAG.getUNDEF(MVT::Other));
6676   assert(TF.getNode() != NewResChain.getNode() &&
6677          "A new TF really is required here");
6678 
6679   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6680   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6681 }
6682 
6683 /// \brief Analyze profitability of direct move
6684 /// prefer float load to int load plus direct move
6685 /// when there is no integer use of int load
6686 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6687   SDNode *Origin = Op.getOperand(0).getNode();
6688   if (Origin->getOpcode() != ISD::LOAD)
6689     return true;
6690 
6691   // If there is no LXSIBZX/LXSIHZX, like Power8,
6692   // prefer direct move if the memory size is 1 or 2 bytes.
6693   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6694   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6695     return true;
6696 
6697   for (SDNode::use_iterator UI = Origin->use_begin(),
6698                             UE = Origin->use_end();
6699        UI != UE; ++UI) {
6700 
6701     // Only look at the users of the loaded value.
6702     if (UI.getUse().get().getResNo() != 0)
6703       continue;
6704 
6705     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6706         UI->getOpcode() != ISD::UINT_TO_FP)
6707       return true;
6708   }
6709 
6710   return false;
6711 }
6712 
6713 /// \brief Custom lowers integer to floating point conversions to use
6714 /// the direct move instructions available in ISA 2.07 to avoid the
6715 /// need for load/store combinations.
6716 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6717                                                     SelectionDAG &DAG,
6718                                                     const SDLoc &dl) const {
6719   assert((Op.getValueType() == MVT::f32 ||
6720           Op.getValueType() == MVT::f64) &&
6721          "Invalid floating point type as target of conversion");
6722   assert(Subtarget.hasFPCVT() &&
6723          "Int to FP conversions with direct moves require FPCVT");
6724   SDValue FP;
6725   SDValue Src = Op.getOperand(0);
6726   bool SinglePrec = Op.getValueType() == MVT::f32;
6727   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6728   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6729   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6730                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6731 
6732   if (WordInt) {
6733     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6734                      dl, MVT::f64, Src);
6735     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6736   }
6737   else {
6738     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6739     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6740   }
6741 
6742   return FP;
6743 }
6744 
6745 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6746                                           SelectionDAG &DAG) const {
6747   SDLoc dl(Op);
6748 
6749   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6750     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6751       return SDValue();
6752 
6753     SDValue Value = Op.getOperand(0);
6754     // The values are now known to be -1 (false) or 1 (true). To convert this
6755     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6756     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6757     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6758 
6759     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6760 
6761     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6762 
6763     if (Op.getValueType() != MVT::v4f64)
6764       Value = DAG.getNode(ISD::FP_ROUND, dl,
6765                           Op.getValueType(), Value,
6766                           DAG.getIntPtrConstant(1, dl));
6767     return Value;
6768   }
6769 
6770   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6771   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6772     return SDValue();
6773 
6774   if (Op.getOperand(0).getValueType() == MVT::i1)
6775     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6776                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6777                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6778 
6779   // If we have direct moves, we can do all the conversion, skip the store/load
6780   // however, without FPCVT we can't do most conversions.
6781   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6782       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6783     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6784 
6785   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6786          "UINT_TO_FP is supported only with FPCVT");
6787 
6788   // If we have FCFIDS, then use it when converting to single-precision.
6789   // Otherwise, convert to double-precision and then round.
6790   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6791                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6792                                                             : PPCISD::FCFIDS)
6793                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6794                                                             : PPCISD::FCFID);
6795   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6796                   ? MVT::f32
6797                   : MVT::f64;
6798 
6799   if (Op.getOperand(0).getValueType() == MVT::i64) {
6800     SDValue SINT = Op.getOperand(0);
6801     // When converting to single-precision, we actually need to convert
6802     // to double-precision first and then round to single-precision.
6803     // To avoid double-rounding effects during that operation, we have
6804     // to prepare the input operand.  Bits that might be truncated when
6805     // converting to double-precision are replaced by a bit that won't
6806     // be lost at this stage, but is below the single-precision rounding
6807     // position.
6808     //
6809     // However, if -enable-unsafe-fp-math is in effect, accept double
6810     // rounding to avoid the extra overhead.
6811     if (Op.getValueType() == MVT::f32 &&
6812         !Subtarget.hasFPCVT() &&
6813         !DAG.getTarget().Options.UnsafeFPMath) {
6814 
6815       // Twiddle input to make sure the low 11 bits are zero.  (If this
6816       // is the case, we are guaranteed the value will fit into the 53 bit
6817       // mantissa of an IEEE double-precision value without rounding.)
6818       // If any of those low 11 bits were not zero originally, make sure
6819       // bit 12 (value 2048) is set instead, so that the final rounding
6820       // to single-precision gets the correct result.
6821       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6822                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6823       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6824                           Round, DAG.getConstant(2047, dl, MVT::i64));
6825       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6826       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6827                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6828 
6829       // However, we cannot use that value unconditionally: if the magnitude
6830       // of the input value is small, the bit-twiddling we did above might
6831       // end up visibly changing the output.  Fortunately, in that case, we
6832       // don't need to twiddle bits since the original input will convert
6833       // exactly to double-precision floating-point already.  Therefore,
6834       // construct a conditional to use the original value if the top 11
6835       // bits are all sign-bit copies, and use the rounded value computed
6836       // above otherwise.
6837       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6838                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6839       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6840                          Cond, DAG.getConstant(1, dl, MVT::i64));
6841       Cond = DAG.getSetCC(dl, MVT::i32,
6842                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6843 
6844       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6845     }
6846 
6847     ReuseLoadInfo RLI;
6848     SDValue Bits;
6849 
6850     MachineFunction &MF = DAG.getMachineFunction();
6851     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6852       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6853                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6854       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6855     } else if (Subtarget.hasLFIWAX() &&
6856                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6857       MachineMemOperand *MMO =
6858         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6859                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6860       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6861       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6862                                      DAG.getVTList(MVT::f64, MVT::Other),
6863                                      Ops, MVT::i32, MMO);
6864       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6865     } else if (Subtarget.hasFPCVT() &&
6866                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6867       MachineMemOperand *MMO =
6868         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6869                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6870       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6871       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6872                                      DAG.getVTList(MVT::f64, MVT::Other),
6873                                      Ops, MVT::i32, MMO);
6874       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6875     } else if (((Subtarget.hasLFIWAX() &&
6876                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6877                 (Subtarget.hasFPCVT() &&
6878                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6879                SINT.getOperand(0).getValueType() == MVT::i32) {
6880       MachineFrameInfo &MFI = MF.getFrameInfo();
6881       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6882 
6883       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6884       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6885 
6886       SDValue Store =
6887           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6888                        MachinePointerInfo::getFixedStack(
6889                            DAG.getMachineFunction(), FrameIdx));
6890 
6891       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6892              "Expected an i32 store");
6893 
6894       RLI.Ptr = FIdx;
6895       RLI.Chain = Store;
6896       RLI.MPI =
6897           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6898       RLI.Alignment = 4;
6899 
6900       MachineMemOperand *MMO =
6901         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6902                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6903       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6904       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6905                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6906                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6907                                      Ops, MVT::i32, MMO);
6908     } else
6909       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6910 
6911     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6912 
6913     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6914       FP = DAG.getNode(ISD::FP_ROUND, dl,
6915                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6916     return FP;
6917   }
6918 
6919   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6920          "Unhandled INT_TO_FP type in custom expander!");
6921   // Since we only generate this in 64-bit mode, we can take advantage of
6922   // 64-bit registers.  In particular, sign extend the input value into the
6923   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6924   // then lfd it and fcfid it.
6925   MachineFunction &MF = DAG.getMachineFunction();
6926   MachineFrameInfo &MFI = MF.getFrameInfo();
6927   EVT PtrVT = getPointerTy(MF.getDataLayout());
6928 
6929   SDValue Ld;
6930   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6931     ReuseLoadInfo RLI;
6932     bool ReusingLoad;
6933     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6934                                             DAG))) {
6935       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6936       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6937 
6938       SDValue Store =
6939           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6940                        MachinePointerInfo::getFixedStack(
6941                            DAG.getMachineFunction(), FrameIdx));
6942 
6943       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6944              "Expected an i32 store");
6945 
6946       RLI.Ptr = FIdx;
6947       RLI.Chain = Store;
6948       RLI.MPI =
6949           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6950       RLI.Alignment = 4;
6951     }
6952 
6953     MachineMemOperand *MMO =
6954       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6955                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6956     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6957     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6958                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6959                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6960                                  Ops, MVT::i32, MMO);
6961     if (ReusingLoad)
6962       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6963   } else {
6964     assert(Subtarget.isPPC64() &&
6965            "i32->FP without LFIWAX supported only on PPC64");
6966 
6967     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6968     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6969 
6970     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6971                                 Op.getOperand(0));
6972 
6973     // STD the extended value into the stack slot.
6974     SDValue Store = DAG.getStore(
6975         DAG.getEntryNode(), dl, Ext64, FIdx,
6976         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6977 
6978     // Load the value as a double.
6979     Ld = DAG.getLoad(
6980         MVT::f64, dl, Store, FIdx,
6981         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6982   }
6983 
6984   // FCFID it and return it.
6985   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6986   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6987     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6988                      DAG.getIntPtrConstant(0, dl));
6989   return FP;
6990 }
6991 
6992 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6993                                             SelectionDAG &DAG) const {
6994   SDLoc dl(Op);
6995   /*
6996    The rounding mode is in bits 30:31 of FPSR, and has the following
6997    settings:
6998      00 Round to nearest
6999      01 Round to 0
7000      10 Round to +inf
7001      11 Round to -inf
7002 
7003   FLT_ROUNDS, on the other hand, expects the following:
7004     -1 Undefined
7005      0 Round to 0
7006      1 Round to nearest
7007      2 Round to +inf
7008      3 Round to -inf
7009 
7010   To perform the conversion, we do:
7011     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7012   */
7013 
7014   MachineFunction &MF = DAG.getMachineFunction();
7015   EVT VT = Op.getValueType();
7016   EVT PtrVT = getPointerTy(MF.getDataLayout());
7017 
7018   // Save FP Control Word to register
7019   EVT NodeTys[] = {
7020     MVT::f64,    // return register
7021     MVT::Glue    // unused in this context
7022   };
7023   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7024 
7025   // Save FP register to stack slot
7026   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7027   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7028   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7029                                MachinePointerInfo());
7030 
7031   // Load FP Control Word from low 32 bits of stack slot.
7032   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7033   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7034   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7035 
7036   // Transform as necessary
7037   SDValue CWD1 =
7038     DAG.getNode(ISD::AND, dl, MVT::i32,
7039                 CWD, DAG.getConstant(3, dl, MVT::i32));
7040   SDValue CWD2 =
7041     DAG.getNode(ISD::SRL, dl, MVT::i32,
7042                 DAG.getNode(ISD::AND, dl, MVT::i32,
7043                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7044                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7045                             DAG.getConstant(3, dl, MVT::i32)),
7046                 DAG.getConstant(1, dl, MVT::i32));
7047 
7048   SDValue RetVal =
7049     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7050 
7051   return DAG.getNode((VT.getSizeInBits() < 16 ?
7052                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7053 }
7054 
7055 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7056   EVT VT = Op.getValueType();
7057   unsigned BitWidth = VT.getSizeInBits();
7058   SDLoc dl(Op);
7059   assert(Op.getNumOperands() == 3 &&
7060          VT == Op.getOperand(1).getValueType() &&
7061          "Unexpected SHL!");
7062 
7063   // Expand into a bunch of logical ops.  Note that these ops
7064   // depend on the PPC behavior for oversized shift amounts.
7065   SDValue Lo = Op.getOperand(0);
7066   SDValue Hi = Op.getOperand(1);
7067   SDValue Amt = Op.getOperand(2);
7068   EVT AmtVT = Amt.getValueType();
7069 
7070   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7071                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7072   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7073   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7074   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7075   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7076                              DAG.getConstant(-BitWidth, dl, AmtVT));
7077   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7078   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7079   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7080   SDValue OutOps[] = { OutLo, OutHi };
7081   return DAG.getMergeValues(OutOps, dl);
7082 }
7083 
7084 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7085   EVT VT = Op.getValueType();
7086   SDLoc dl(Op);
7087   unsigned BitWidth = VT.getSizeInBits();
7088   assert(Op.getNumOperands() == 3 &&
7089          VT == Op.getOperand(1).getValueType() &&
7090          "Unexpected SRL!");
7091 
7092   // Expand into a bunch of logical ops.  Note that these ops
7093   // depend on the PPC behavior for oversized shift amounts.
7094   SDValue Lo = Op.getOperand(0);
7095   SDValue Hi = Op.getOperand(1);
7096   SDValue Amt = Op.getOperand(2);
7097   EVT AmtVT = Amt.getValueType();
7098 
7099   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7100                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7101   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7102   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7103   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7104   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7105                              DAG.getConstant(-BitWidth, dl, AmtVT));
7106   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7107   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7108   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7109   SDValue OutOps[] = { OutLo, OutHi };
7110   return DAG.getMergeValues(OutOps, dl);
7111 }
7112 
7113 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7114   SDLoc dl(Op);
7115   EVT VT = Op.getValueType();
7116   unsigned BitWidth = VT.getSizeInBits();
7117   assert(Op.getNumOperands() == 3 &&
7118          VT == Op.getOperand(1).getValueType() &&
7119          "Unexpected SRA!");
7120 
7121   // Expand into a bunch of logical ops, followed by a select_cc.
7122   SDValue Lo = Op.getOperand(0);
7123   SDValue Hi = Op.getOperand(1);
7124   SDValue Amt = Op.getOperand(2);
7125   EVT AmtVT = Amt.getValueType();
7126 
7127   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7128                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7129   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7130   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7131   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7132   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7133                              DAG.getConstant(-BitWidth, dl, AmtVT));
7134   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7135   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7136   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7137                                   Tmp4, Tmp6, ISD::SETLE);
7138   SDValue OutOps[] = { OutLo, OutHi };
7139   return DAG.getMergeValues(OutOps, dl);
7140 }
7141 
7142 //===----------------------------------------------------------------------===//
7143 // Vector related lowering.
7144 //
7145 
7146 /// BuildSplatI - Build a canonical splati of Val with an element size of
7147 /// SplatSize.  Cast the result to VT.
7148 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7149                            SelectionDAG &DAG, const SDLoc &dl) {
7150   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7151 
7152   static const MVT VTys[] = { // canonical VT to use for each size.
7153     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7154   };
7155 
7156   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7157 
7158   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7159   if (Val == -1)
7160     SplatSize = 1;
7161 
7162   EVT CanonicalVT = VTys[SplatSize-1];
7163 
7164   // Build a canonical splat for this value.
7165   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7166 }
7167 
7168 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7169 /// specified intrinsic ID.
7170 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7171                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7172   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7173   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7174                      DAG.getConstant(IID, dl, MVT::i32), Op);
7175 }
7176 
7177 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7178 /// specified intrinsic ID.
7179 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7180                                 SelectionDAG &DAG, const SDLoc &dl,
7181                                 EVT DestVT = MVT::Other) {
7182   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7183   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7184                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7185 }
7186 
7187 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7188 /// specified intrinsic ID.
7189 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7190                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7191                                 EVT DestVT = MVT::Other) {
7192   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7193   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7194                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7195 }
7196 
7197 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7198 /// amount.  The result has the specified value type.
7199 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7200                            SelectionDAG &DAG, const SDLoc &dl) {
7201   // Force LHS/RHS to be the right type.
7202   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7203   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7204 
7205   int Ops[16];
7206   for (unsigned i = 0; i != 16; ++i)
7207     Ops[i] = i + Amt;
7208   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7209   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7210 }
7211 
7212 /// Do we have an efficient pattern in a .td file for this node?
7213 ///
7214 /// \param V - pointer to the BuildVectorSDNode being matched
7215 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7216 ///
7217 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7218 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7219 /// the opposite is true (expansion is beneficial) are:
7220 /// - The node builds a vector out of integers that are not 32 or 64-bits
7221 /// - The node builds a vector out of constants
7222 /// - The node is a "load-and-splat"
7223 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7224 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7225                                             bool HasDirectMove) {
7226   EVT VecVT = V->getValueType(0);
7227   bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7228     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7229   if (!RightType)
7230     return false;
7231 
7232   bool IsSplat = true;
7233   bool IsLoad = false;
7234   SDValue Op0 = V->getOperand(0);
7235 
7236   // This function is called in a block that confirms the node is not a constant
7237   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7238   // different constants.
7239   if (V->isConstant())
7240     return false;
7241   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7242     if (V->getOperand(i).isUndef())
7243       return false;
7244     // We want to expand nodes that represent load-and-splat even if the
7245     // loaded value is a floating point truncation or conversion to int.
7246     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7247         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7248          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7249         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7250          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7251         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7252          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7253       IsLoad = true;
7254     // If the operands are different or the input is not a load and has more
7255     // uses than just this BV node, then it isn't a splat.
7256     if (V->getOperand(i) != Op0 ||
7257         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7258       IsSplat = false;
7259   }
7260   return !(IsSplat && IsLoad);
7261 }
7262 
7263 // If this is a case we can't handle, return null and let the default
7264 // expansion code take care of it.  If we CAN select this case, and if it
7265 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7266 // this case more efficiently than a constant pool load, lower it to the
7267 // sequence of ops that should be used.
7268 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7269                                              SelectionDAG &DAG) const {
7270   SDLoc dl(Op);
7271   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7272   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7273 
7274   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7275     // We first build an i32 vector, load it into a QPX register,
7276     // then convert it to a floating-point vector and compare it
7277     // to a zero vector to get the boolean result.
7278     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7279     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7280     MachinePointerInfo PtrInfo =
7281         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7282     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7283     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7284 
7285     assert(BVN->getNumOperands() == 4 &&
7286       "BUILD_VECTOR for v4i1 does not have 4 operands");
7287 
7288     bool IsConst = true;
7289     for (unsigned i = 0; i < 4; ++i) {
7290       if (BVN->getOperand(i).isUndef()) continue;
7291       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7292         IsConst = false;
7293         break;
7294       }
7295     }
7296 
7297     if (IsConst) {
7298       Constant *One =
7299         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7300       Constant *NegOne =
7301         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7302 
7303       Constant *CV[4];
7304       for (unsigned i = 0; i < 4; ++i) {
7305         if (BVN->getOperand(i).isUndef())
7306           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7307         else if (isNullConstant(BVN->getOperand(i)))
7308           CV[i] = NegOne;
7309         else
7310           CV[i] = One;
7311       }
7312 
7313       Constant *CP = ConstantVector::get(CV);
7314       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7315                                           16 /* alignment */);
7316 
7317       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7318       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7319       return DAG.getMemIntrinsicNode(
7320           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7321           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7322     }
7323 
7324     SmallVector<SDValue, 4> Stores;
7325     for (unsigned i = 0; i < 4; ++i) {
7326       if (BVN->getOperand(i).isUndef()) continue;
7327 
7328       unsigned Offset = 4*i;
7329       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7330       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7331 
7332       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7333       if (StoreSize > 4) {
7334         Stores.push_back(
7335             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7336                               PtrInfo.getWithOffset(Offset), MVT::i32));
7337       } else {
7338         SDValue StoreValue = BVN->getOperand(i);
7339         if (StoreSize < 4)
7340           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7341 
7342         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7343                                       PtrInfo.getWithOffset(Offset)));
7344       }
7345     }
7346 
7347     SDValue StoreChain;
7348     if (!Stores.empty())
7349       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7350     else
7351       StoreChain = DAG.getEntryNode();
7352 
7353     // Now load from v4i32 into the QPX register; this will extend it to
7354     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7355     // is typed as v4f64 because the QPX register integer states are not
7356     // explicitly represented.
7357 
7358     SDValue Ops[] = {StoreChain,
7359                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7360                      FIdx};
7361     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7362 
7363     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7364       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7365     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7366       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7367       LoadedVect);
7368 
7369     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7370 
7371     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7372   }
7373 
7374   // All other QPX vectors are handled by generic code.
7375   if (Subtarget.hasQPX())
7376     return SDValue();
7377 
7378   // Check if this is a splat of a constant value.
7379   APInt APSplatBits, APSplatUndef;
7380   unsigned SplatBitSize;
7381   bool HasAnyUndefs;
7382   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7383                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7384       SplatBitSize > 32) {
7385     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7386     // lowered to VSX instructions under certain conditions.
7387     // Without VSX, there is no pattern more efficient than expanding the node.
7388     if (Subtarget.hasVSX() &&
7389         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7390       return Op;
7391     return SDValue();
7392   }
7393 
7394   unsigned SplatBits = APSplatBits.getZExtValue();
7395   unsigned SplatUndef = APSplatUndef.getZExtValue();
7396   unsigned SplatSize = SplatBitSize / 8;
7397 
7398   // First, handle single instruction cases.
7399 
7400   // All zeros?
7401   if (SplatBits == 0) {
7402     // Canonicalize all zero vectors to be v4i32.
7403     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7404       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7405       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7406     }
7407     return Op;
7408   }
7409 
7410   // We have XXSPLTIB for constant splats one byte wide
7411   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7412     // This is a splat of 1-byte elements with some elements potentially undef.
7413     // Rather than trying to match undef in the SDAG patterns, ensure that all
7414     // elements are the same constant.
7415     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7416       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7417                                                        dl, MVT::i32));
7418       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7419       if (Op.getValueType() != MVT::v16i8)
7420         return DAG.getBitcast(Op.getValueType(), NewBV);
7421       return NewBV;
7422     }
7423     return Op;
7424   }
7425 
7426   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7427   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7428                     (32-SplatBitSize));
7429   if (SextVal >= -16 && SextVal <= 15)
7430     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7431 
7432   // Two instruction sequences.
7433 
7434   // If this value is in the range [-32,30] and is even, use:
7435   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7436   // If this value is in the range [17,31] and is odd, use:
7437   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7438   // If this value is in the range [-31,-17] and is odd, use:
7439   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7440   // Note the last two are three-instruction sequences.
7441   if (SextVal >= -32 && SextVal <= 31) {
7442     // To avoid having these optimizations undone by constant folding,
7443     // we convert to a pseudo that will be expanded later into one of
7444     // the above forms.
7445     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7446     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7447               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7448     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7449     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7450     if (VT == Op.getValueType())
7451       return RetVal;
7452     else
7453       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7454   }
7455 
7456   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7457   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7458   // for fneg/fabs.
7459   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7460     // Make -1 and vspltisw -1:
7461     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7462 
7463     // Make the VSLW intrinsic, computing 0x8000_0000.
7464     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7465                                    OnesV, DAG, dl);
7466 
7467     // xor by OnesV to invert it.
7468     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7469     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7470   }
7471 
7472   // Check to see if this is a wide variety of vsplti*, binop self cases.
7473   static const signed char SplatCsts[] = {
7474     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7475     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7476   };
7477 
7478   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7479     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7480     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7481     int i = SplatCsts[idx];
7482 
7483     // Figure out what shift amount will be used by altivec if shifted by i in
7484     // this splat size.
7485     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7486 
7487     // vsplti + shl self.
7488     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7489       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7490       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7491         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7492         Intrinsic::ppc_altivec_vslw
7493       };
7494       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7495       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7496     }
7497 
7498     // vsplti + srl self.
7499     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7500       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7501       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7502         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7503         Intrinsic::ppc_altivec_vsrw
7504       };
7505       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7506       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7507     }
7508 
7509     // vsplti + sra self.
7510     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7511       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7512       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7513         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7514         Intrinsic::ppc_altivec_vsraw
7515       };
7516       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7517       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7518     }
7519 
7520     // vsplti + rol self.
7521     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7522                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7523       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7524       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7525         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7526         Intrinsic::ppc_altivec_vrlw
7527       };
7528       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7529       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7530     }
7531 
7532     // t = vsplti c, result = vsldoi t, t, 1
7533     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7534       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7535       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7536       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7537     }
7538     // t = vsplti c, result = vsldoi t, t, 2
7539     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7540       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7541       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7542       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7543     }
7544     // t = vsplti c, result = vsldoi t, t, 3
7545     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7546       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7547       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7548       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7549     }
7550   }
7551 
7552   return SDValue();
7553 }
7554 
7555 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7556 /// the specified operations to build the shuffle.
7557 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7558                                       SDValue RHS, SelectionDAG &DAG,
7559                                       const SDLoc &dl) {
7560   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7561   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7562   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7563 
7564   enum {
7565     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7566     OP_VMRGHW,
7567     OP_VMRGLW,
7568     OP_VSPLTISW0,
7569     OP_VSPLTISW1,
7570     OP_VSPLTISW2,
7571     OP_VSPLTISW3,
7572     OP_VSLDOI4,
7573     OP_VSLDOI8,
7574     OP_VSLDOI12
7575   };
7576 
7577   if (OpNum == OP_COPY) {
7578     if (LHSID == (1*9+2)*9+3) return LHS;
7579     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7580     return RHS;
7581   }
7582 
7583   SDValue OpLHS, OpRHS;
7584   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7585   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7586 
7587   int ShufIdxs[16];
7588   switch (OpNum) {
7589   default: llvm_unreachable("Unknown i32 permute!");
7590   case OP_VMRGHW:
7591     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7592     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7593     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7594     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7595     break;
7596   case OP_VMRGLW:
7597     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7598     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7599     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7600     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7601     break;
7602   case OP_VSPLTISW0:
7603     for (unsigned i = 0; i != 16; ++i)
7604       ShufIdxs[i] = (i&3)+0;
7605     break;
7606   case OP_VSPLTISW1:
7607     for (unsigned i = 0; i != 16; ++i)
7608       ShufIdxs[i] = (i&3)+4;
7609     break;
7610   case OP_VSPLTISW2:
7611     for (unsigned i = 0; i != 16; ++i)
7612       ShufIdxs[i] = (i&3)+8;
7613     break;
7614   case OP_VSPLTISW3:
7615     for (unsigned i = 0; i != 16; ++i)
7616       ShufIdxs[i] = (i&3)+12;
7617     break;
7618   case OP_VSLDOI4:
7619     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7620   case OP_VSLDOI8:
7621     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7622   case OP_VSLDOI12:
7623     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7624   }
7625   EVT VT = OpLHS.getValueType();
7626   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7627   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7628   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7629   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7630 }
7631 
7632 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7633 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7634 /// return the code it can be lowered into.  Worst case, it can always be
7635 /// lowered into a vperm.
7636 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7637                                                SelectionDAG &DAG) const {
7638   SDLoc dl(Op);
7639   SDValue V1 = Op.getOperand(0);
7640   SDValue V2 = Op.getOperand(1);
7641   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7642   EVT VT = Op.getValueType();
7643   bool isLittleEndian = Subtarget.isLittleEndian();
7644 
7645   unsigned ShiftElts, InsertAtByte;
7646   bool Swap;
7647   if (Subtarget.hasP9Vector() &&
7648       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7649                            isLittleEndian)) {
7650     if (Swap)
7651       std::swap(V1, V2);
7652     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7653     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7654     if (ShiftElts) {
7655       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7656                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7657       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7658                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7659       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7660     }
7661     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7662                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7663     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7664   }
7665 
7666   if (Subtarget.hasVSX()) {
7667     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7668       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7669 
7670       // If the source for the shuffle is a scalar_to_vector that came from a
7671       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7672       if (Subtarget.hasP9Vector() &&
7673           ((isLittleEndian && SplatIdx == 3) ||
7674            (!isLittleEndian && SplatIdx == 0))) {
7675         SDValue Src = V1.getOperand(0);
7676         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7677             Src.getOperand(0).getOpcode() == ISD::LOAD &&
7678             Src.getOperand(0).hasOneUse())
7679           return V1;
7680       }
7681       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7682       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7683                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7684       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7685     }
7686 
7687     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7688     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7689       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7690       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7691       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7692     }
7693   }
7694 
7695   if (Subtarget.hasQPX()) {
7696     if (VT.getVectorNumElements() != 4)
7697       return SDValue();
7698 
7699     if (V2.isUndef()) V2 = V1;
7700 
7701     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7702     if (AlignIdx != -1) {
7703       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7704                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7705     } else if (SVOp->isSplat()) {
7706       int SplatIdx = SVOp->getSplatIndex();
7707       if (SplatIdx >= 4) {
7708         std::swap(V1, V2);
7709         SplatIdx -= 4;
7710       }
7711 
7712       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7713                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7714     }
7715 
7716     // Lower this into a qvgpci/qvfperm pair.
7717 
7718     // Compute the qvgpci literal
7719     unsigned idx = 0;
7720     for (unsigned i = 0; i < 4; ++i) {
7721       int m = SVOp->getMaskElt(i);
7722       unsigned mm = m >= 0 ? (unsigned) m : i;
7723       idx |= mm << (3-i)*3;
7724     }
7725 
7726     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7727                              DAG.getConstant(idx, dl, MVT::i32));
7728     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7729   }
7730 
7731   // Cases that are handled by instructions that take permute immediates
7732   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7733   // selected by the instruction selector.
7734   if (V2.isUndef()) {
7735     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7736         PPC::isSplatShuffleMask(SVOp, 2) ||
7737         PPC::isSplatShuffleMask(SVOp, 4) ||
7738         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7739         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7740         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7741         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7742         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7743         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7744         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7745         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7746         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7747         (Subtarget.hasP8Altivec() && (
7748          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7749          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7750          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7751       return Op;
7752     }
7753   }
7754 
7755   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7756   // and produce a fixed permutation.  If any of these match, do not lower to
7757   // VPERM.
7758   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7759   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7760       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7761       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7762       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7763       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7764       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7765       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7766       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7767       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7768       (Subtarget.hasP8Altivec() && (
7769        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7770        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7771        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7772     return Op;
7773 
7774   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7775   // perfect shuffle table to emit an optimal matching sequence.
7776   ArrayRef<int> PermMask = SVOp->getMask();
7777 
7778   unsigned PFIndexes[4];
7779   bool isFourElementShuffle = true;
7780   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7781     unsigned EltNo = 8;   // Start out undef.
7782     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7783       if (PermMask[i*4+j] < 0)
7784         continue;   // Undef, ignore it.
7785 
7786       unsigned ByteSource = PermMask[i*4+j];
7787       if ((ByteSource & 3) != j) {
7788         isFourElementShuffle = false;
7789         break;
7790       }
7791 
7792       if (EltNo == 8) {
7793         EltNo = ByteSource/4;
7794       } else if (EltNo != ByteSource/4) {
7795         isFourElementShuffle = false;
7796         break;
7797       }
7798     }
7799     PFIndexes[i] = EltNo;
7800   }
7801 
7802   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7803   // perfect shuffle vector to determine if it is cost effective to do this as
7804   // discrete instructions, or whether we should use a vperm.
7805   // For now, we skip this for little endian until such time as we have a
7806   // little-endian perfect shuffle table.
7807   if (isFourElementShuffle && !isLittleEndian) {
7808     // Compute the index in the perfect shuffle table.
7809     unsigned PFTableIndex =
7810       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7811 
7812     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7813     unsigned Cost  = (PFEntry >> 30);
7814 
7815     // Determining when to avoid vperm is tricky.  Many things affect the cost
7816     // of vperm, particularly how many times the perm mask needs to be computed.
7817     // For example, if the perm mask can be hoisted out of a loop or is already
7818     // used (perhaps because there are multiple permutes with the same shuffle
7819     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7820     // the loop requires an extra register.
7821     //
7822     // As a compromise, we only emit discrete instructions if the shuffle can be
7823     // generated in 3 or fewer operations.  When we have loop information
7824     // available, if this block is within a loop, we should avoid using vperm
7825     // for 3-operation perms and use a constant pool load instead.
7826     if (Cost < 3)
7827       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7828   }
7829 
7830   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7831   // vector that will get spilled to the constant pool.
7832   if (V2.isUndef()) V2 = V1;
7833 
7834   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7835   // that it is in input element units, not in bytes.  Convert now.
7836 
7837   // For little endian, the order of the input vectors is reversed, and
7838   // the permutation mask is complemented with respect to 31.  This is
7839   // necessary to produce proper semantics with the big-endian-biased vperm
7840   // instruction.
7841   EVT EltVT = V1.getValueType().getVectorElementType();
7842   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7843 
7844   SmallVector<SDValue, 16> ResultMask;
7845   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7846     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7847 
7848     for (unsigned j = 0; j != BytesPerElement; ++j)
7849       if (isLittleEndian)
7850         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7851                                              dl, MVT::i32));
7852       else
7853         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7854                                              MVT::i32));
7855   }
7856 
7857   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7858   if (isLittleEndian)
7859     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7860                        V2, V1, VPermMask);
7861   else
7862     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7863                        V1, V2, VPermMask);
7864 }
7865 
7866 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7867 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7868 /// information about the intrinsic.
7869 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7870                                  bool &isDot, const PPCSubtarget &Subtarget) {
7871   unsigned IntrinsicID =
7872       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7873   CompareOpc = -1;
7874   isDot = false;
7875   switch (IntrinsicID) {
7876   default:
7877     return false;
7878   // Comparison predicates.
7879   case Intrinsic::ppc_altivec_vcmpbfp_p:
7880     CompareOpc = 966;
7881     isDot = true;
7882     break;
7883   case Intrinsic::ppc_altivec_vcmpeqfp_p:
7884     CompareOpc = 198;
7885     isDot = true;
7886     break;
7887   case Intrinsic::ppc_altivec_vcmpequb_p:
7888     CompareOpc = 6;
7889     isDot = true;
7890     break;
7891   case Intrinsic::ppc_altivec_vcmpequh_p:
7892     CompareOpc = 70;
7893     isDot = true;
7894     break;
7895   case Intrinsic::ppc_altivec_vcmpequw_p:
7896     CompareOpc = 134;
7897     isDot = true;
7898     break;
7899   case Intrinsic::ppc_altivec_vcmpequd_p:
7900     if (Subtarget.hasP8Altivec()) {
7901       CompareOpc = 199;
7902       isDot = true;
7903     } else
7904       return false;
7905     break;
7906   case Intrinsic::ppc_altivec_vcmpneb_p:
7907   case Intrinsic::ppc_altivec_vcmpneh_p:
7908   case Intrinsic::ppc_altivec_vcmpnew_p:
7909   case Intrinsic::ppc_altivec_vcmpnezb_p:
7910   case Intrinsic::ppc_altivec_vcmpnezh_p:
7911   case Intrinsic::ppc_altivec_vcmpnezw_p:
7912     if (Subtarget.hasP9Altivec()) {
7913       switch (IntrinsicID) {
7914       default:
7915         llvm_unreachable("Unknown comparison intrinsic.");
7916       case Intrinsic::ppc_altivec_vcmpneb_p:
7917         CompareOpc = 7;
7918         break;
7919       case Intrinsic::ppc_altivec_vcmpneh_p:
7920         CompareOpc = 71;
7921         break;
7922       case Intrinsic::ppc_altivec_vcmpnew_p:
7923         CompareOpc = 135;
7924         break;
7925       case Intrinsic::ppc_altivec_vcmpnezb_p:
7926         CompareOpc = 263;
7927         break;
7928       case Intrinsic::ppc_altivec_vcmpnezh_p:
7929         CompareOpc = 327;
7930         break;
7931       case Intrinsic::ppc_altivec_vcmpnezw_p:
7932         CompareOpc = 391;
7933         break;
7934       }
7935       isDot = true;
7936     } else
7937       return false;
7938     break;
7939   case Intrinsic::ppc_altivec_vcmpgefp_p:
7940     CompareOpc = 454;
7941     isDot = true;
7942     break;
7943   case Intrinsic::ppc_altivec_vcmpgtfp_p:
7944     CompareOpc = 710;
7945     isDot = true;
7946     break;
7947   case Intrinsic::ppc_altivec_vcmpgtsb_p:
7948     CompareOpc = 774;
7949     isDot = true;
7950     break;
7951   case Intrinsic::ppc_altivec_vcmpgtsh_p:
7952     CompareOpc = 838;
7953     isDot = true;
7954     break;
7955   case Intrinsic::ppc_altivec_vcmpgtsw_p:
7956     CompareOpc = 902;
7957     isDot = true;
7958     break;
7959   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7960     if (Subtarget.hasP8Altivec()) {
7961       CompareOpc = 967;
7962       isDot = true;
7963     } else
7964       return false;
7965     break;
7966   case Intrinsic::ppc_altivec_vcmpgtub_p:
7967     CompareOpc = 518;
7968     isDot = true;
7969     break;
7970   case Intrinsic::ppc_altivec_vcmpgtuh_p:
7971     CompareOpc = 582;
7972     isDot = true;
7973     break;
7974   case Intrinsic::ppc_altivec_vcmpgtuw_p:
7975     CompareOpc = 646;
7976     isDot = true;
7977     break;
7978   case Intrinsic::ppc_altivec_vcmpgtud_p:
7979     if (Subtarget.hasP8Altivec()) {
7980       CompareOpc = 711;
7981       isDot = true;
7982     } else
7983       return false;
7984     break;
7985 
7986   // VSX predicate comparisons use the same infrastructure
7987   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7988   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7989   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7990   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7991   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7992   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7993     if (Subtarget.hasVSX()) {
7994       switch (IntrinsicID) {
7995       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7996         CompareOpc = 99;
7997         break;
7998       case Intrinsic::ppc_vsx_xvcmpgedp_p:
7999         CompareOpc = 115;
8000         break;
8001       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8002         CompareOpc = 107;
8003         break;
8004       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8005         CompareOpc = 67;
8006         break;
8007       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8008         CompareOpc = 83;
8009         break;
8010       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8011         CompareOpc = 75;
8012         break;
8013       }
8014       isDot = true;
8015     } else
8016       return false;
8017     break;
8018 
8019   // Normal Comparisons.
8020   case Intrinsic::ppc_altivec_vcmpbfp:
8021     CompareOpc = 966;
8022     break;
8023   case Intrinsic::ppc_altivec_vcmpeqfp:
8024     CompareOpc = 198;
8025     break;
8026   case Intrinsic::ppc_altivec_vcmpequb:
8027     CompareOpc = 6;
8028     break;
8029   case Intrinsic::ppc_altivec_vcmpequh:
8030     CompareOpc = 70;
8031     break;
8032   case Intrinsic::ppc_altivec_vcmpequw:
8033     CompareOpc = 134;
8034     break;
8035   case Intrinsic::ppc_altivec_vcmpequd:
8036     if (Subtarget.hasP8Altivec())
8037       CompareOpc = 199;
8038     else
8039       return false;
8040     break;
8041   case Intrinsic::ppc_altivec_vcmpneb:
8042   case Intrinsic::ppc_altivec_vcmpneh:
8043   case Intrinsic::ppc_altivec_vcmpnew:
8044   case Intrinsic::ppc_altivec_vcmpnezb:
8045   case Intrinsic::ppc_altivec_vcmpnezh:
8046   case Intrinsic::ppc_altivec_vcmpnezw:
8047     if (Subtarget.hasP9Altivec())
8048       switch (IntrinsicID) {
8049       default:
8050         llvm_unreachable("Unknown comparison intrinsic.");
8051       case Intrinsic::ppc_altivec_vcmpneb:
8052         CompareOpc = 7;
8053         break;
8054       case Intrinsic::ppc_altivec_vcmpneh:
8055         CompareOpc = 71;
8056         break;
8057       case Intrinsic::ppc_altivec_vcmpnew:
8058         CompareOpc = 135;
8059         break;
8060       case Intrinsic::ppc_altivec_vcmpnezb:
8061         CompareOpc = 263;
8062         break;
8063       case Intrinsic::ppc_altivec_vcmpnezh:
8064         CompareOpc = 327;
8065         break;
8066       case Intrinsic::ppc_altivec_vcmpnezw:
8067         CompareOpc = 391;
8068         break;
8069       }
8070     else
8071       return false;
8072     break;
8073   case Intrinsic::ppc_altivec_vcmpgefp:
8074     CompareOpc = 454;
8075     break;
8076   case Intrinsic::ppc_altivec_vcmpgtfp:
8077     CompareOpc = 710;
8078     break;
8079   case Intrinsic::ppc_altivec_vcmpgtsb:
8080     CompareOpc = 774;
8081     break;
8082   case Intrinsic::ppc_altivec_vcmpgtsh:
8083     CompareOpc = 838;
8084     break;
8085   case Intrinsic::ppc_altivec_vcmpgtsw:
8086     CompareOpc = 902;
8087     break;
8088   case Intrinsic::ppc_altivec_vcmpgtsd:
8089     if (Subtarget.hasP8Altivec())
8090       CompareOpc = 967;
8091     else
8092       return false;
8093     break;
8094   case Intrinsic::ppc_altivec_vcmpgtub:
8095     CompareOpc = 518;
8096     break;
8097   case Intrinsic::ppc_altivec_vcmpgtuh:
8098     CompareOpc = 582;
8099     break;
8100   case Intrinsic::ppc_altivec_vcmpgtuw:
8101     CompareOpc = 646;
8102     break;
8103   case Intrinsic::ppc_altivec_vcmpgtud:
8104     if (Subtarget.hasP8Altivec())
8105       CompareOpc = 711;
8106     else
8107       return false;
8108     break;
8109   }
8110   return true;
8111 }
8112 
8113 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8114 /// lower, do it, otherwise return null.
8115 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8116                                                    SelectionDAG &DAG) const {
8117   unsigned IntrinsicID =
8118     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8119 
8120   if (IntrinsicID == Intrinsic::thread_pointer) {
8121     // Reads the thread pointer register, used for __builtin_thread_pointer.
8122     bool is64bit = Subtarget.isPPC64();
8123     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8124                            is64bit ? MVT::i64 : MVT::i32);
8125   }
8126 
8127   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8128   // opcode number of the comparison.
8129   SDLoc dl(Op);
8130   int CompareOpc;
8131   bool isDot;
8132   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8133     return SDValue();    // Don't custom lower most intrinsics.
8134 
8135   // If this is a non-dot comparison, make the VCMP node and we are done.
8136   if (!isDot) {
8137     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8138                               Op.getOperand(1), Op.getOperand(2),
8139                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8140     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8141   }
8142 
8143   // Create the PPCISD altivec 'dot' comparison node.
8144   SDValue Ops[] = {
8145     Op.getOperand(2),  // LHS
8146     Op.getOperand(3),  // RHS
8147     DAG.getConstant(CompareOpc, dl, MVT::i32)
8148   };
8149   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8150   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8151 
8152   // Now that we have the comparison, emit a copy from the CR to a GPR.
8153   // This is flagged to the above dot comparison.
8154   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8155                                 DAG.getRegister(PPC::CR6, MVT::i32),
8156                                 CompNode.getValue(1));
8157 
8158   // Unpack the result based on how the target uses it.
8159   unsigned BitNo;   // Bit # of CR6.
8160   bool InvertBit;   // Invert result?
8161   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8162   default:  // Can't happen, don't crash on invalid number though.
8163   case 0:   // Return the value of the EQ bit of CR6.
8164     BitNo = 0; InvertBit = false;
8165     break;
8166   case 1:   // Return the inverted value of the EQ bit of CR6.
8167     BitNo = 0; InvertBit = true;
8168     break;
8169   case 2:   // Return the value of the LT bit of CR6.
8170     BitNo = 2; InvertBit = false;
8171     break;
8172   case 3:   // Return the inverted value of the LT bit of CR6.
8173     BitNo = 2; InvertBit = true;
8174     break;
8175   }
8176 
8177   // Shift the bit into the low position.
8178   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8179                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8180   // Isolate the bit.
8181   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8182                       DAG.getConstant(1, dl, MVT::i32));
8183 
8184   // If we are supposed to, toggle the bit.
8185   if (InvertBit)
8186     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8187                         DAG.getConstant(1, dl, MVT::i32));
8188   return Flags;
8189 }
8190 
8191 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8192                                                   SelectionDAG &DAG) const {
8193   SDLoc dl(Op);
8194   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8195   // instructions), but for smaller types, we need to first extend up to v2i32
8196   // before doing going farther.
8197   if (Op.getValueType() == MVT::v2i64) {
8198     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8199     if (ExtVT != MVT::v2i32) {
8200       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8201       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8202                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8203                                         ExtVT.getVectorElementType(), 4)));
8204       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8205       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8206                        DAG.getValueType(MVT::v2i32));
8207     }
8208 
8209     return Op;
8210   }
8211 
8212   return SDValue();
8213 }
8214 
8215 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8216                                                  SelectionDAG &DAG) const {
8217   SDLoc dl(Op);
8218   // Create a stack slot that is 16-byte aligned.
8219   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8220   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8221   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8222   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8223 
8224   // Store the input value into Value#0 of the stack slot.
8225   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8226                                MachinePointerInfo());
8227   // Load it out.
8228   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8229 }
8230 
8231 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8232                                                   SelectionDAG &DAG) const {
8233   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8234          "Should only be called for ISD::INSERT_VECTOR_ELT");
8235   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8236   // We have legal lowering for constant indices but not for variable ones.
8237   if (C)
8238     return Op;
8239   return SDValue();
8240 }
8241 
8242 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8243                                                    SelectionDAG &DAG) const {
8244   SDLoc dl(Op);
8245   SDNode *N = Op.getNode();
8246 
8247   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8248          "Unknown extract_vector_elt type");
8249 
8250   SDValue Value = N->getOperand(0);
8251 
8252   // The first part of this is like the store lowering except that we don't
8253   // need to track the chain.
8254 
8255   // The values are now known to be -1 (false) or 1 (true). To convert this
8256   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8257   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8258   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8259 
8260   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8261   // understand how to form the extending load.
8262   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8263 
8264   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8265 
8266   // Now convert to an integer and store.
8267   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8268     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8269     Value);
8270 
8271   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8272   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8273   MachinePointerInfo PtrInfo =
8274       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8275   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8276   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8277 
8278   SDValue StoreChain = DAG.getEntryNode();
8279   SDValue Ops[] = {StoreChain,
8280                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8281                    Value, FIdx};
8282   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8283 
8284   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8285     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8286 
8287   // Extract the value requested.
8288   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8289   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8290   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8291 
8292   SDValue IntVal =
8293       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8294 
8295   if (!Subtarget.useCRBits())
8296     return IntVal;
8297 
8298   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8299 }
8300 
8301 /// Lowering for QPX v4i1 loads
8302 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8303                                            SelectionDAG &DAG) const {
8304   SDLoc dl(Op);
8305   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8306   SDValue LoadChain = LN->getChain();
8307   SDValue BasePtr = LN->getBasePtr();
8308 
8309   if (Op.getValueType() == MVT::v4f64 ||
8310       Op.getValueType() == MVT::v4f32) {
8311     EVT MemVT = LN->getMemoryVT();
8312     unsigned Alignment = LN->getAlignment();
8313 
8314     // If this load is properly aligned, then it is legal.
8315     if (Alignment >= MemVT.getStoreSize())
8316       return Op;
8317 
8318     EVT ScalarVT = Op.getValueType().getScalarType(),
8319         ScalarMemVT = MemVT.getScalarType();
8320     unsigned Stride = ScalarMemVT.getStoreSize();
8321 
8322     SDValue Vals[4], LoadChains[4];
8323     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8324       SDValue Load;
8325       if (ScalarVT != ScalarMemVT)
8326         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8327                               BasePtr,
8328                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8329                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8330                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8331       else
8332         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8333                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8334                            MinAlign(Alignment, Idx * Stride),
8335                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8336 
8337       if (Idx == 0 && LN->isIndexed()) {
8338         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8339                "Unknown addressing mode on vector load");
8340         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8341                                   LN->getAddressingMode());
8342       }
8343 
8344       Vals[Idx] = Load;
8345       LoadChains[Idx] = Load.getValue(1);
8346 
8347       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8348                             DAG.getConstant(Stride, dl,
8349                                             BasePtr.getValueType()));
8350     }
8351 
8352     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8353     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8354 
8355     if (LN->isIndexed()) {
8356       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8357       return DAG.getMergeValues(RetOps, dl);
8358     }
8359 
8360     SDValue RetOps[] = { Value, TF };
8361     return DAG.getMergeValues(RetOps, dl);
8362   }
8363 
8364   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8365   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8366 
8367   // To lower v4i1 from a byte array, we load the byte elements of the
8368   // vector and then reuse the BUILD_VECTOR logic.
8369 
8370   SDValue VectElmts[4], VectElmtChains[4];
8371   for (unsigned i = 0; i < 4; ++i) {
8372     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8373     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8374 
8375     VectElmts[i] = DAG.getExtLoad(
8376         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8377         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8378         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8379     VectElmtChains[i] = VectElmts[i].getValue(1);
8380   }
8381 
8382   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8383   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8384 
8385   SDValue RVals[] = { Value, LoadChain };
8386   return DAG.getMergeValues(RVals, dl);
8387 }
8388 
8389 /// Lowering for QPX v4i1 stores
8390 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8391                                             SelectionDAG &DAG) const {
8392   SDLoc dl(Op);
8393   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8394   SDValue StoreChain = SN->getChain();
8395   SDValue BasePtr = SN->getBasePtr();
8396   SDValue Value = SN->getValue();
8397 
8398   if (Value.getValueType() == MVT::v4f64 ||
8399       Value.getValueType() == MVT::v4f32) {
8400     EVT MemVT = SN->getMemoryVT();
8401     unsigned Alignment = SN->getAlignment();
8402 
8403     // If this store is properly aligned, then it is legal.
8404     if (Alignment >= MemVT.getStoreSize())
8405       return Op;
8406 
8407     EVT ScalarVT = Value.getValueType().getScalarType(),
8408         ScalarMemVT = MemVT.getScalarType();
8409     unsigned Stride = ScalarMemVT.getStoreSize();
8410 
8411     SDValue Stores[4];
8412     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8413       SDValue Ex = DAG.getNode(
8414           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8415           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8416       SDValue Store;
8417       if (ScalarVT != ScalarMemVT)
8418         Store =
8419             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8420                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8421                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8422                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8423       else
8424         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8425                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8426                              MinAlign(Alignment, Idx * Stride),
8427                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8428 
8429       if (Idx == 0 && SN->isIndexed()) {
8430         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8431                "Unknown addressing mode on vector store");
8432         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8433                                     SN->getAddressingMode());
8434       }
8435 
8436       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8437                             DAG.getConstant(Stride, dl,
8438                                             BasePtr.getValueType()));
8439       Stores[Idx] = Store;
8440     }
8441 
8442     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8443 
8444     if (SN->isIndexed()) {
8445       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8446       return DAG.getMergeValues(RetOps, dl);
8447     }
8448 
8449     return TF;
8450   }
8451 
8452   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8453   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8454 
8455   // The values are now known to be -1 (false) or 1 (true). To convert this
8456   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8457   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8458   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8459 
8460   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8461   // understand how to form the extending load.
8462   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8463 
8464   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8465 
8466   // Now convert to an integer and store.
8467   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8468     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8469     Value);
8470 
8471   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8472   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8473   MachinePointerInfo PtrInfo =
8474       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8475   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8476   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8477 
8478   SDValue Ops[] = {StoreChain,
8479                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8480                    Value, FIdx};
8481   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8482 
8483   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8484     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8485 
8486   // Move data into the byte array.
8487   SDValue Loads[4], LoadChains[4];
8488   for (unsigned i = 0; i < 4; ++i) {
8489     unsigned Offset = 4*i;
8490     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8491     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8492 
8493     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8494                            PtrInfo.getWithOffset(Offset));
8495     LoadChains[i] = Loads[i].getValue(1);
8496   }
8497 
8498   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8499 
8500   SDValue Stores[4];
8501   for (unsigned i = 0; i < 4; ++i) {
8502     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8503     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8504 
8505     Stores[i] = DAG.getTruncStore(
8506         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8507         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8508         SN->getAAInfo());
8509   }
8510 
8511   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8512 
8513   return StoreChain;
8514 }
8515 
8516 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8517   SDLoc dl(Op);
8518   if (Op.getValueType() == MVT::v4i32) {
8519     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8520 
8521     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8522     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8523 
8524     SDValue RHSSwap =   // = vrlw RHS, 16
8525       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8526 
8527     // Shrinkify inputs to v8i16.
8528     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8529     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8530     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8531 
8532     // Low parts multiplied together, generating 32-bit results (we ignore the
8533     // top parts).
8534     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8535                                         LHS, RHS, DAG, dl, MVT::v4i32);
8536 
8537     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8538                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8539     // Shift the high parts up 16 bits.
8540     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8541                               Neg16, DAG, dl);
8542     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8543   } else if (Op.getValueType() == MVT::v8i16) {
8544     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8545 
8546     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8547 
8548     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8549                             LHS, RHS, Zero, DAG, dl);
8550   } else if (Op.getValueType() == MVT::v16i8) {
8551     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8552     bool isLittleEndian = Subtarget.isLittleEndian();
8553 
8554     // Multiply the even 8-bit parts, producing 16-bit sums.
8555     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8556                                            LHS, RHS, DAG, dl, MVT::v8i16);
8557     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8558 
8559     // Multiply the odd 8-bit parts, producing 16-bit sums.
8560     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8561                                           LHS, RHS, DAG, dl, MVT::v8i16);
8562     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8563 
8564     // Merge the results together.  Because vmuleub and vmuloub are
8565     // instructions with a big-endian bias, we must reverse the
8566     // element numbering and reverse the meaning of "odd" and "even"
8567     // when generating little endian code.
8568     int Ops[16];
8569     for (unsigned i = 0; i != 8; ++i) {
8570       if (isLittleEndian) {
8571         Ops[i*2  ] = 2*i;
8572         Ops[i*2+1] = 2*i+16;
8573       } else {
8574         Ops[i*2  ] = 2*i+1;
8575         Ops[i*2+1] = 2*i+1+16;
8576       }
8577     }
8578     if (isLittleEndian)
8579       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8580     else
8581       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8582   } else {
8583     llvm_unreachable("Unknown mul to lower!");
8584   }
8585 }
8586 
8587 /// LowerOperation - Provide custom lowering hooks for some operations.
8588 ///
8589 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8590   switch (Op.getOpcode()) {
8591   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8592   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8593   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8594   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8595   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8596   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8597   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8598   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8599   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8600   case ISD::VASTART:
8601     return LowerVASTART(Op, DAG);
8602 
8603   case ISD::VAARG:
8604     return LowerVAARG(Op, DAG);
8605 
8606   case ISD::VACOPY:
8607     return LowerVACOPY(Op, DAG);
8608 
8609   case ISD::STACKRESTORE:
8610     return LowerSTACKRESTORE(Op, DAG);
8611 
8612   case ISD::DYNAMIC_STACKALLOC:
8613     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8614 
8615   case ISD::GET_DYNAMIC_AREA_OFFSET:
8616     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8617 
8618   case ISD::EH_DWARF_CFA:
8619     return LowerEH_DWARF_CFA(Op, DAG);
8620 
8621   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8622   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8623 
8624   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8625   case ISD::STORE:              return LowerSTORE(Op, DAG);
8626   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8627   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8628   case ISD::FP_TO_UINT:
8629   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8630                                                       SDLoc(Op));
8631   case ISD::UINT_TO_FP:
8632   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8633   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8634 
8635   // Lower 64-bit shifts.
8636   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8637   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8638   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8639 
8640   // Vector-related lowering.
8641   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8642   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8643   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8644   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8645   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8646   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8647   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8648   case ISD::MUL:                return LowerMUL(Op, DAG);
8649 
8650   // For counter-based loop handling.
8651   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8652 
8653   // Frame & Return address.
8654   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8655   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8656   }
8657 }
8658 
8659 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8660                                            SmallVectorImpl<SDValue>&Results,
8661                                            SelectionDAG &DAG) const {
8662   SDLoc dl(N);
8663   switch (N->getOpcode()) {
8664   default:
8665     llvm_unreachable("Do not know how to custom type legalize this operation!");
8666   case ISD::READCYCLECOUNTER: {
8667     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8668     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8669 
8670     Results.push_back(RTB);
8671     Results.push_back(RTB.getValue(1));
8672     Results.push_back(RTB.getValue(2));
8673     break;
8674   }
8675   case ISD::INTRINSIC_W_CHAIN: {
8676     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8677         Intrinsic::ppc_is_decremented_ctr_nonzero)
8678       break;
8679 
8680     assert(N->getValueType(0) == MVT::i1 &&
8681            "Unexpected result type for CTR decrement intrinsic");
8682     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8683                                  N->getValueType(0));
8684     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8685     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8686                                  N->getOperand(1));
8687 
8688     Results.push_back(NewInt);
8689     Results.push_back(NewInt.getValue(1));
8690     break;
8691   }
8692   case ISD::VAARG: {
8693     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8694       return;
8695 
8696     EVT VT = N->getValueType(0);
8697 
8698     if (VT == MVT::i64) {
8699       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8700 
8701       Results.push_back(NewNode);
8702       Results.push_back(NewNode.getValue(1));
8703     }
8704     return;
8705   }
8706   case ISD::FP_ROUND_INREG: {
8707     assert(N->getValueType(0) == MVT::ppcf128);
8708     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8709     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8710                              MVT::f64, N->getOperand(0),
8711                              DAG.getIntPtrConstant(0, dl));
8712     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8713                              MVT::f64, N->getOperand(0),
8714                              DAG.getIntPtrConstant(1, dl));
8715 
8716     // Add the two halves of the long double in round-to-zero mode.
8717     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8718 
8719     // We know the low half is about to be thrown away, so just use something
8720     // convenient.
8721     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8722                                 FPreg, FPreg));
8723     return;
8724   }
8725   case ISD::FP_TO_SINT:
8726   case ISD::FP_TO_UINT:
8727     // LowerFP_TO_INT() can only handle f32 and f64.
8728     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8729       return;
8730     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8731     return;
8732   }
8733 }
8734 
8735 //===----------------------------------------------------------------------===//
8736 //  Other Lowering Code
8737 //===----------------------------------------------------------------------===//
8738 
8739 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8740   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8741   Function *Func = Intrinsic::getDeclaration(M, Id);
8742   return Builder.CreateCall(Func, {});
8743 }
8744 
8745 // The mappings for emitLeading/TrailingFence is taken from
8746 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8747 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8748                                          AtomicOrdering Ord, bool IsStore,
8749                                          bool IsLoad) const {
8750   if (Ord == AtomicOrdering::SequentiallyConsistent)
8751     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8752   if (isReleaseOrStronger(Ord))
8753     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8754   return nullptr;
8755 }
8756 
8757 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8758                                           AtomicOrdering Ord, bool IsStore,
8759                                           bool IsLoad) const {
8760   if (IsLoad && isAcquireOrStronger(Ord))
8761     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8762   // FIXME: this is too conservative, a dependent branch + isync is enough.
8763   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8764   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8765   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8766   return nullptr;
8767 }
8768 
8769 MachineBasicBlock *
8770 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8771                                     unsigned AtomicSize,
8772                                     unsigned BinOpcode,
8773                                     unsigned CmpOpcode,
8774                                     unsigned CmpPred) const {
8775   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8776   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8777 
8778   auto LoadMnemonic = PPC::LDARX;
8779   auto StoreMnemonic = PPC::STDCX;
8780   switch (AtomicSize) {
8781   default:
8782     llvm_unreachable("Unexpected size of atomic entity");
8783   case 1:
8784     LoadMnemonic = PPC::LBARX;
8785     StoreMnemonic = PPC::STBCX;
8786     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8787     break;
8788   case 2:
8789     LoadMnemonic = PPC::LHARX;
8790     StoreMnemonic = PPC::STHCX;
8791     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8792     break;
8793   case 4:
8794     LoadMnemonic = PPC::LWARX;
8795     StoreMnemonic = PPC::STWCX;
8796     break;
8797   case 8:
8798     LoadMnemonic = PPC::LDARX;
8799     StoreMnemonic = PPC::STDCX;
8800     break;
8801   }
8802 
8803   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8804   MachineFunction *F = BB->getParent();
8805   MachineFunction::iterator It = ++BB->getIterator();
8806 
8807   unsigned dest = MI.getOperand(0).getReg();
8808   unsigned ptrA = MI.getOperand(1).getReg();
8809   unsigned ptrB = MI.getOperand(2).getReg();
8810   unsigned incr = MI.getOperand(3).getReg();
8811   DebugLoc dl = MI.getDebugLoc();
8812 
8813   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8814   MachineBasicBlock *loop2MBB =
8815     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8816   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8817   F->insert(It, loopMBB);
8818   if (CmpOpcode)
8819     F->insert(It, loop2MBB);
8820   F->insert(It, exitMBB);
8821   exitMBB->splice(exitMBB->begin(), BB,
8822                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8823   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8824 
8825   MachineRegisterInfo &RegInfo = F->getRegInfo();
8826   unsigned TmpReg = (!BinOpcode) ? incr :
8827     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8828                                            : &PPC::GPRCRegClass);
8829 
8830   //  thisMBB:
8831   //   ...
8832   //   fallthrough --> loopMBB
8833   BB->addSuccessor(loopMBB);
8834 
8835   //  loopMBB:
8836   //   l[wd]arx dest, ptr
8837   //   add r0, dest, incr
8838   //   st[wd]cx. r0, ptr
8839   //   bne- loopMBB
8840   //   fallthrough --> exitMBB
8841 
8842   // For max/min...
8843   //  loopMBB:
8844   //   l[wd]arx dest, ptr
8845   //   cmpl?[wd] incr, dest
8846   //   bgt exitMBB
8847   //  loop2MBB:
8848   //   st[wd]cx. dest, ptr
8849   //   bne- loopMBB
8850   //   fallthrough --> exitMBB
8851 
8852   BB = loopMBB;
8853   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8854     .addReg(ptrA).addReg(ptrB);
8855   if (BinOpcode)
8856     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8857   if (CmpOpcode) {
8858     // Signed comparisons of byte or halfword values must be sign-extended.
8859     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8860       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8861       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8862               ExtReg).addReg(dest);
8863       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8864         .addReg(incr).addReg(ExtReg);
8865     } else
8866       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8867         .addReg(incr).addReg(dest);
8868 
8869     BuildMI(BB, dl, TII->get(PPC::BCC))
8870       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8871     BB->addSuccessor(loop2MBB);
8872     BB->addSuccessor(exitMBB);
8873     BB = loop2MBB;
8874   }
8875   BuildMI(BB, dl, TII->get(StoreMnemonic))
8876     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8877   BuildMI(BB, dl, TII->get(PPC::BCC))
8878     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8879   BB->addSuccessor(loopMBB);
8880   BB->addSuccessor(exitMBB);
8881 
8882   //  exitMBB:
8883   //   ...
8884   BB = exitMBB;
8885   return BB;
8886 }
8887 
8888 MachineBasicBlock *
8889 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8890                                             MachineBasicBlock *BB,
8891                                             bool is8bit, // operation
8892                                             unsigned BinOpcode,
8893                                             unsigned CmpOpcode,
8894                                             unsigned CmpPred) const {
8895   // If we support part-word atomic mnemonics, just use them
8896   if (Subtarget.hasPartwordAtomics())
8897     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8898                             CmpOpcode, CmpPred);
8899 
8900   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8901   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8902   // In 64 bit mode we have to use 64 bits for addresses, even though the
8903   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8904   // registers without caring whether they're 32 or 64, but here we're
8905   // doing actual arithmetic on the addresses.
8906   bool is64bit = Subtarget.isPPC64();
8907   bool isLittleEndian = Subtarget.isLittleEndian();
8908   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8909 
8910   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8911   MachineFunction *F = BB->getParent();
8912   MachineFunction::iterator It = ++BB->getIterator();
8913 
8914   unsigned dest = MI.getOperand(0).getReg();
8915   unsigned ptrA = MI.getOperand(1).getReg();
8916   unsigned ptrB = MI.getOperand(2).getReg();
8917   unsigned incr = MI.getOperand(3).getReg();
8918   DebugLoc dl = MI.getDebugLoc();
8919 
8920   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8921   MachineBasicBlock *loop2MBB =
8922     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8923   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8924   F->insert(It, loopMBB);
8925   if (CmpOpcode)
8926     F->insert(It, loop2MBB);
8927   F->insert(It, exitMBB);
8928   exitMBB->splice(exitMBB->begin(), BB,
8929                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8930   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8931 
8932   MachineRegisterInfo &RegInfo = F->getRegInfo();
8933   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8934                                           : &PPC::GPRCRegClass;
8935   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8936   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8937   unsigned ShiftReg =
8938     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8939   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8940   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8941   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8942   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8943   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8944   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8945   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8946   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8947   unsigned Ptr1Reg;
8948   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8949 
8950   //  thisMBB:
8951   //   ...
8952   //   fallthrough --> loopMBB
8953   BB->addSuccessor(loopMBB);
8954 
8955   // The 4-byte load must be aligned, while a char or short may be
8956   // anywhere in the word.  Hence all this nasty bookkeeping code.
8957   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8958   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8959   //   xori shift, shift1, 24 [16]
8960   //   rlwinm ptr, ptr1, 0, 0, 29
8961   //   slw incr2, incr, shift
8962   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8963   //   slw mask, mask2, shift
8964   //  loopMBB:
8965   //   lwarx tmpDest, ptr
8966   //   add tmp, tmpDest, incr2
8967   //   andc tmp2, tmpDest, mask
8968   //   and tmp3, tmp, mask
8969   //   or tmp4, tmp3, tmp2
8970   //   stwcx. tmp4, ptr
8971   //   bne- loopMBB
8972   //   fallthrough --> exitMBB
8973   //   srw dest, tmpDest, shift
8974   if (ptrA != ZeroReg) {
8975     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8976     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8977       .addReg(ptrA).addReg(ptrB);
8978   } else {
8979     Ptr1Reg = ptrB;
8980   }
8981   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8982       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8983   if (!isLittleEndian)
8984     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8985         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8986   if (is64bit)
8987     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8988       .addReg(Ptr1Reg).addImm(0).addImm(61);
8989   else
8990     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8991       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8992   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8993       .addReg(incr).addReg(ShiftReg);
8994   if (is8bit)
8995     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8996   else {
8997     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8998     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8999   }
9000   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9001       .addReg(Mask2Reg).addReg(ShiftReg);
9002 
9003   BB = loopMBB;
9004   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9005     .addReg(ZeroReg).addReg(PtrReg);
9006   if (BinOpcode)
9007     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9008       .addReg(Incr2Reg).addReg(TmpDestReg);
9009   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9010     .addReg(TmpDestReg).addReg(MaskReg);
9011   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9012     .addReg(TmpReg).addReg(MaskReg);
9013   if (CmpOpcode) {
9014     // For unsigned comparisons, we can directly compare the shifted values.
9015     // For signed comparisons we shift and sign extend.
9016     unsigned SReg = RegInfo.createVirtualRegister(RC);
9017     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9018       .addReg(TmpDestReg).addReg(MaskReg);
9019     unsigned ValueReg = SReg;
9020     unsigned CmpReg = Incr2Reg;
9021     if (CmpOpcode == PPC::CMPW) {
9022       ValueReg = RegInfo.createVirtualRegister(RC);
9023       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9024         .addReg(SReg).addReg(ShiftReg);
9025       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9026       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9027         .addReg(ValueReg);
9028       ValueReg = ValueSReg;
9029       CmpReg = incr;
9030     }
9031     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9032       .addReg(CmpReg).addReg(ValueReg);
9033     BuildMI(BB, dl, TII->get(PPC::BCC))
9034       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9035     BB->addSuccessor(loop2MBB);
9036     BB->addSuccessor(exitMBB);
9037     BB = loop2MBB;
9038   }
9039   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9040     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9041   BuildMI(BB, dl, TII->get(PPC::STWCX))
9042     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9043   BuildMI(BB, dl, TII->get(PPC::BCC))
9044     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9045   BB->addSuccessor(loopMBB);
9046   BB->addSuccessor(exitMBB);
9047 
9048   //  exitMBB:
9049   //   ...
9050   BB = exitMBB;
9051   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9052     .addReg(ShiftReg);
9053   return BB;
9054 }
9055 
9056 llvm::MachineBasicBlock *
9057 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9058                                     MachineBasicBlock *MBB) const {
9059   DebugLoc DL = MI.getDebugLoc();
9060   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9061 
9062   MachineFunction *MF = MBB->getParent();
9063   MachineRegisterInfo &MRI = MF->getRegInfo();
9064 
9065   const BasicBlock *BB = MBB->getBasicBlock();
9066   MachineFunction::iterator I = ++MBB->getIterator();
9067 
9068   // Memory Reference
9069   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9070   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9071 
9072   unsigned DstReg = MI.getOperand(0).getReg();
9073   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9074   assert(RC->hasType(MVT::i32) && "Invalid destination!");
9075   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9076   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9077 
9078   MVT PVT = getPointerTy(MF->getDataLayout());
9079   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9080          "Invalid Pointer Size!");
9081   // For v = setjmp(buf), we generate
9082   //
9083   // thisMBB:
9084   //  SjLjSetup mainMBB
9085   //  bl mainMBB
9086   //  v_restore = 1
9087   //  b sinkMBB
9088   //
9089   // mainMBB:
9090   //  buf[LabelOffset] = LR
9091   //  v_main = 0
9092   //
9093   // sinkMBB:
9094   //  v = phi(main, restore)
9095   //
9096 
9097   MachineBasicBlock *thisMBB = MBB;
9098   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9099   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9100   MF->insert(I, mainMBB);
9101   MF->insert(I, sinkMBB);
9102 
9103   MachineInstrBuilder MIB;
9104 
9105   // Transfer the remainder of BB and its successor edges to sinkMBB.
9106   sinkMBB->splice(sinkMBB->begin(), MBB,
9107                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9108   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9109 
9110   // Note that the structure of the jmp_buf used here is not compatible
9111   // with that used by libc, and is not designed to be. Specifically, it
9112   // stores only those 'reserved' registers that LLVM does not otherwise
9113   // understand how to spill. Also, by convention, by the time this
9114   // intrinsic is called, Clang has already stored the frame address in the
9115   // first slot of the buffer and stack address in the third. Following the
9116   // X86 target code, we'll store the jump address in the second slot. We also
9117   // need to save the TOC pointer (R2) to handle jumps between shared
9118   // libraries, and that will be stored in the fourth slot. The thread
9119   // identifier (R13) is not affected.
9120 
9121   // thisMBB:
9122   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9123   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9124   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9125 
9126   // Prepare IP either in reg.
9127   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9128   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9129   unsigned BufReg = MI.getOperand(1).getReg();
9130 
9131   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9132     setUsesTOCBasePtr(*MBB->getParent());
9133     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9134             .addReg(PPC::X2)
9135             .addImm(TOCOffset)
9136             .addReg(BufReg);
9137     MIB.setMemRefs(MMOBegin, MMOEnd);
9138   }
9139 
9140   // Naked functions never have a base pointer, and so we use r1. For all
9141   // other functions, this decision must be delayed until during PEI.
9142   unsigned BaseReg;
9143   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9144     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9145   else
9146     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9147 
9148   MIB = BuildMI(*thisMBB, MI, DL,
9149                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9150             .addReg(BaseReg)
9151             .addImm(BPOffset)
9152             .addReg(BufReg);
9153   MIB.setMemRefs(MMOBegin, MMOEnd);
9154 
9155   // Setup
9156   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9157   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9158   MIB.addRegMask(TRI->getNoPreservedMask());
9159 
9160   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9161 
9162   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9163           .addMBB(mainMBB);
9164   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9165 
9166   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9167   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9168 
9169   // mainMBB:
9170   //  mainDstReg = 0
9171   MIB =
9172       BuildMI(mainMBB, DL,
9173               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9174 
9175   // Store IP
9176   if (Subtarget.isPPC64()) {
9177     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9178             .addReg(LabelReg)
9179             .addImm(LabelOffset)
9180             .addReg(BufReg);
9181   } else {
9182     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9183             .addReg(LabelReg)
9184             .addImm(LabelOffset)
9185             .addReg(BufReg);
9186   }
9187 
9188   MIB.setMemRefs(MMOBegin, MMOEnd);
9189 
9190   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9191   mainMBB->addSuccessor(sinkMBB);
9192 
9193   // sinkMBB:
9194   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9195           TII->get(PPC::PHI), DstReg)
9196     .addReg(mainDstReg).addMBB(mainMBB)
9197     .addReg(restoreDstReg).addMBB(thisMBB);
9198 
9199   MI.eraseFromParent();
9200   return sinkMBB;
9201 }
9202 
9203 MachineBasicBlock *
9204 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9205                                      MachineBasicBlock *MBB) const {
9206   DebugLoc DL = MI.getDebugLoc();
9207   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9208 
9209   MachineFunction *MF = MBB->getParent();
9210   MachineRegisterInfo &MRI = MF->getRegInfo();
9211 
9212   // Memory Reference
9213   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9214   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9215 
9216   MVT PVT = getPointerTy(MF->getDataLayout());
9217   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9218          "Invalid Pointer Size!");
9219 
9220   const TargetRegisterClass *RC =
9221     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9222   unsigned Tmp = MRI.createVirtualRegister(RC);
9223   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9224   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9225   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9226   unsigned BP =
9227       (PVT == MVT::i64)
9228           ? PPC::X30
9229           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9230                                                               : PPC::R30);
9231 
9232   MachineInstrBuilder MIB;
9233 
9234   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9235   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9236   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9237   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9238 
9239   unsigned BufReg = MI.getOperand(0).getReg();
9240 
9241   // Reload FP (the jumped-to function may not have had a
9242   // frame pointer, and if so, then its r31 will be restored
9243   // as necessary).
9244   if (PVT == MVT::i64) {
9245     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9246             .addImm(0)
9247             .addReg(BufReg);
9248   } else {
9249     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9250             .addImm(0)
9251             .addReg(BufReg);
9252   }
9253   MIB.setMemRefs(MMOBegin, MMOEnd);
9254 
9255   // Reload IP
9256   if (PVT == MVT::i64) {
9257     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9258             .addImm(LabelOffset)
9259             .addReg(BufReg);
9260   } else {
9261     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9262             .addImm(LabelOffset)
9263             .addReg(BufReg);
9264   }
9265   MIB.setMemRefs(MMOBegin, MMOEnd);
9266 
9267   // Reload SP
9268   if (PVT == MVT::i64) {
9269     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9270             .addImm(SPOffset)
9271             .addReg(BufReg);
9272   } else {
9273     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9274             .addImm(SPOffset)
9275             .addReg(BufReg);
9276   }
9277   MIB.setMemRefs(MMOBegin, MMOEnd);
9278 
9279   // Reload BP
9280   if (PVT == MVT::i64) {
9281     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9282             .addImm(BPOffset)
9283             .addReg(BufReg);
9284   } else {
9285     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9286             .addImm(BPOffset)
9287             .addReg(BufReg);
9288   }
9289   MIB.setMemRefs(MMOBegin, MMOEnd);
9290 
9291   // Reload TOC
9292   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9293     setUsesTOCBasePtr(*MBB->getParent());
9294     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9295             .addImm(TOCOffset)
9296             .addReg(BufReg);
9297 
9298     MIB.setMemRefs(MMOBegin, MMOEnd);
9299   }
9300 
9301   // Jump
9302   BuildMI(*MBB, MI, DL,
9303           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9304   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9305 
9306   MI.eraseFromParent();
9307   return MBB;
9308 }
9309 
9310 MachineBasicBlock *
9311 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9312                                                MachineBasicBlock *BB) const {
9313   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9314       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9315     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9316         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9317       // Call lowering should have added an r2 operand to indicate a dependence
9318       // on the TOC base pointer value. It can't however, because there is no
9319       // way to mark the dependence as implicit there, and so the stackmap code
9320       // will confuse it with a regular operand. Instead, add the dependence
9321       // here.
9322       setUsesTOCBasePtr(*BB->getParent());
9323       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9324     }
9325 
9326     return emitPatchPoint(MI, BB);
9327   }
9328 
9329   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9330       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9331     return emitEHSjLjSetJmp(MI, BB);
9332   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9333              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9334     return emitEHSjLjLongJmp(MI, BB);
9335   }
9336 
9337   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9338 
9339   // To "insert" these instructions we actually have to insert their
9340   // control-flow patterns.
9341   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9342   MachineFunction::iterator It = ++BB->getIterator();
9343 
9344   MachineFunction *F = BB->getParent();
9345 
9346   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9347        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9348        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9349     SmallVector<MachineOperand, 2> Cond;
9350     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9351         MI.getOpcode() == PPC::SELECT_CC_I8)
9352       Cond.push_back(MI.getOperand(4));
9353     else
9354       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9355     Cond.push_back(MI.getOperand(1));
9356 
9357     DebugLoc dl = MI.getDebugLoc();
9358     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9359                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9360   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9361              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9362              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9363              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9364              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9365              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9366              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9367              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9368              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9369              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9370              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9371              MI.getOpcode() == PPC::SELECT_I4 ||
9372              MI.getOpcode() == PPC::SELECT_I8 ||
9373              MI.getOpcode() == PPC::SELECT_F4 ||
9374              MI.getOpcode() == PPC::SELECT_F8 ||
9375              MI.getOpcode() == PPC::SELECT_QFRC ||
9376              MI.getOpcode() == PPC::SELECT_QSRC ||
9377              MI.getOpcode() == PPC::SELECT_QBRC ||
9378              MI.getOpcode() == PPC::SELECT_VRRC ||
9379              MI.getOpcode() == PPC::SELECT_VSFRC ||
9380              MI.getOpcode() == PPC::SELECT_VSSRC ||
9381              MI.getOpcode() == PPC::SELECT_VSRC) {
9382     // The incoming instruction knows the destination vreg to set, the
9383     // condition code register to branch on, the true/false values to
9384     // select between, and a branch opcode to use.
9385 
9386     //  thisMBB:
9387     //  ...
9388     //   TrueVal = ...
9389     //   cmpTY ccX, r1, r2
9390     //   bCC copy1MBB
9391     //   fallthrough --> copy0MBB
9392     MachineBasicBlock *thisMBB = BB;
9393     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9394     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9395     DebugLoc dl = MI.getDebugLoc();
9396     F->insert(It, copy0MBB);
9397     F->insert(It, sinkMBB);
9398 
9399     // Transfer the remainder of BB and its successor edges to sinkMBB.
9400     sinkMBB->splice(sinkMBB->begin(), BB,
9401                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9402     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9403 
9404     // Next, add the true and fallthrough blocks as its successors.
9405     BB->addSuccessor(copy0MBB);
9406     BB->addSuccessor(sinkMBB);
9407 
9408     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9409         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9410         MI.getOpcode() == PPC::SELECT_QFRC ||
9411         MI.getOpcode() == PPC::SELECT_QSRC ||
9412         MI.getOpcode() == PPC::SELECT_QBRC ||
9413         MI.getOpcode() == PPC::SELECT_VRRC ||
9414         MI.getOpcode() == PPC::SELECT_VSFRC ||
9415         MI.getOpcode() == PPC::SELECT_VSSRC ||
9416         MI.getOpcode() == PPC::SELECT_VSRC) {
9417       BuildMI(BB, dl, TII->get(PPC::BC))
9418           .addReg(MI.getOperand(1).getReg())
9419           .addMBB(sinkMBB);
9420     } else {
9421       unsigned SelectPred = MI.getOperand(4).getImm();
9422       BuildMI(BB, dl, TII->get(PPC::BCC))
9423           .addImm(SelectPred)
9424           .addReg(MI.getOperand(1).getReg())
9425           .addMBB(sinkMBB);
9426     }
9427 
9428     //  copy0MBB:
9429     //   %FalseValue = ...
9430     //   # fallthrough to sinkMBB
9431     BB = copy0MBB;
9432 
9433     // Update machine-CFG edges
9434     BB->addSuccessor(sinkMBB);
9435 
9436     //  sinkMBB:
9437     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9438     //  ...
9439     BB = sinkMBB;
9440     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9441         .addReg(MI.getOperand(3).getReg())
9442         .addMBB(copy0MBB)
9443         .addReg(MI.getOperand(2).getReg())
9444         .addMBB(thisMBB);
9445   } else if (MI.getOpcode() == PPC::ReadTB) {
9446     // To read the 64-bit time-base register on a 32-bit target, we read the
9447     // two halves. Should the counter have wrapped while it was being read, we
9448     // need to try again.
9449     // ...
9450     // readLoop:
9451     // mfspr Rx,TBU # load from TBU
9452     // mfspr Ry,TB  # load from TB
9453     // mfspr Rz,TBU # load from TBU
9454     // cmpw crX,Rx,Rz # check if 'old'='new'
9455     // bne readLoop   # branch if they're not equal
9456     // ...
9457 
9458     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9459     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9460     DebugLoc dl = MI.getDebugLoc();
9461     F->insert(It, readMBB);
9462     F->insert(It, sinkMBB);
9463 
9464     // Transfer the remainder of BB and its successor edges to sinkMBB.
9465     sinkMBB->splice(sinkMBB->begin(), BB,
9466                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9467     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9468 
9469     BB->addSuccessor(readMBB);
9470     BB = readMBB;
9471 
9472     MachineRegisterInfo &RegInfo = F->getRegInfo();
9473     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9474     unsigned LoReg = MI.getOperand(0).getReg();
9475     unsigned HiReg = MI.getOperand(1).getReg();
9476 
9477     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9478     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9479     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9480 
9481     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9482 
9483     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9484       .addReg(HiReg).addReg(ReadAgainReg);
9485     BuildMI(BB, dl, TII->get(PPC::BCC))
9486       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9487 
9488     BB->addSuccessor(readMBB);
9489     BB->addSuccessor(sinkMBB);
9490   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9491     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9492   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9493     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9494   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9495     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9496   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9497     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9498 
9499   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9500     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9501   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9502     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9503   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9504     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9505   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9506     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9507 
9508   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9509     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9510   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9511     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9512   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9513     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9514   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9515     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9516 
9517   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9518     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9519   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9520     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9521   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9522     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9523   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9524     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9525 
9526   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9527     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9528   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9529     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9530   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9531     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9532   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9533     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9534 
9535   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9536     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9537   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9538     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9539   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9540     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9541   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9542     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9543 
9544   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9545     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9546   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9547     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9548   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9549     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9550   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9551     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9552 
9553   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9554     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9555   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9556     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9557   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9558     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9559   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9560     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9561 
9562   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9563     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9564   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9565     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9566   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9567     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9568   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9569     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9570 
9571   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9572     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9573   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9574     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9575   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9576     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9577   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9578     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9579 
9580   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9581     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9582   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9583     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9584   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9585     BB = EmitAtomicBinary(MI, BB, 4, 0);
9586   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9587     BB = EmitAtomicBinary(MI, BB, 8, 0);
9588   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9589            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9590            (Subtarget.hasPartwordAtomics() &&
9591             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9592            (Subtarget.hasPartwordAtomics() &&
9593             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9594     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9595 
9596     auto LoadMnemonic = PPC::LDARX;
9597     auto StoreMnemonic = PPC::STDCX;
9598     switch (MI.getOpcode()) {
9599     default:
9600       llvm_unreachable("Compare and swap of unknown size");
9601     case PPC::ATOMIC_CMP_SWAP_I8:
9602       LoadMnemonic = PPC::LBARX;
9603       StoreMnemonic = PPC::STBCX;
9604       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9605       break;
9606     case PPC::ATOMIC_CMP_SWAP_I16:
9607       LoadMnemonic = PPC::LHARX;
9608       StoreMnemonic = PPC::STHCX;
9609       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9610       break;
9611     case PPC::ATOMIC_CMP_SWAP_I32:
9612       LoadMnemonic = PPC::LWARX;
9613       StoreMnemonic = PPC::STWCX;
9614       break;
9615     case PPC::ATOMIC_CMP_SWAP_I64:
9616       LoadMnemonic = PPC::LDARX;
9617       StoreMnemonic = PPC::STDCX;
9618       break;
9619     }
9620     unsigned dest = MI.getOperand(0).getReg();
9621     unsigned ptrA = MI.getOperand(1).getReg();
9622     unsigned ptrB = MI.getOperand(2).getReg();
9623     unsigned oldval = MI.getOperand(3).getReg();
9624     unsigned newval = MI.getOperand(4).getReg();
9625     DebugLoc dl = MI.getDebugLoc();
9626 
9627     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9628     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9629     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9630     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9631     F->insert(It, loop1MBB);
9632     F->insert(It, loop2MBB);
9633     F->insert(It, midMBB);
9634     F->insert(It, exitMBB);
9635     exitMBB->splice(exitMBB->begin(), BB,
9636                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9637     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9638 
9639     //  thisMBB:
9640     //   ...
9641     //   fallthrough --> loopMBB
9642     BB->addSuccessor(loop1MBB);
9643 
9644     // loop1MBB:
9645     //   l[bhwd]arx dest, ptr
9646     //   cmp[wd] dest, oldval
9647     //   bne- midMBB
9648     // loop2MBB:
9649     //   st[bhwd]cx. newval, ptr
9650     //   bne- loopMBB
9651     //   b exitBB
9652     // midMBB:
9653     //   st[bhwd]cx. dest, ptr
9654     // exitBB:
9655     BB = loop1MBB;
9656     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9657       .addReg(ptrA).addReg(ptrB);
9658     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9659       .addReg(oldval).addReg(dest);
9660     BuildMI(BB, dl, TII->get(PPC::BCC))
9661       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9662     BB->addSuccessor(loop2MBB);
9663     BB->addSuccessor(midMBB);
9664 
9665     BB = loop2MBB;
9666     BuildMI(BB, dl, TII->get(StoreMnemonic))
9667       .addReg(newval).addReg(ptrA).addReg(ptrB);
9668     BuildMI(BB, dl, TII->get(PPC::BCC))
9669       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9670     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9671     BB->addSuccessor(loop1MBB);
9672     BB->addSuccessor(exitMBB);
9673 
9674     BB = midMBB;
9675     BuildMI(BB, dl, TII->get(StoreMnemonic))
9676       .addReg(dest).addReg(ptrA).addReg(ptrB);
9677     BB->addSuccessor(exitMBB);
9678 
9679     //  exitMBB:
9680     //   ...
9681     BB = exitMBB;
9682   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9683              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9684     // We must use 64-bit registers for addresses when targeting 64-bit,
9685     // since we're actually doing arithmetic on them.  Other registers
9686     // can be 32-bit.
9687     bool is64bit = Subtarget.isPPC64();
9688     bool isLittleEndian = Subtarget.isLittleEndian();
9689     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9690 
9691     unsigned dest = MI.getOperand(0).getReg();
9692     unsigned ptrA = MI.getOperand(1).getReg();
9693     unsigned ptrB = MI.getOperand(2).getReg();
9694     unsigned oldval = MI.getOperand(3).getReg();
9695     unsigned newval = MI.getOperand(4).getReg();
9696     DebugLoc dl = MI.getDebugLoc();
9697 
9698     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9699     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9700     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9701     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9702     F->insert(It, loop1MBB);
9703     F->insert(It, loop2MBB);
9704     F->insert(It, midMBB);
9705     F->insert(It, exitMBB);
9706     exitMBB->splice(exitMBB->begin(), BB,
9707                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9708     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9709 
9710     MachineRegisterInfo &RegInfo = F->getRegInfo();
9711     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9712                                             : &PPC::GPRCRegClass;
9713     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9714     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9715     unsigned ShiftReg =
9716       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9717     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9718     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9719     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9720     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9721     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9722     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9723     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9724     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9725     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9726     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9727     unsigned Ptr1Reg;
9728     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9729     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9730     //  thisMBB:
9731     //   ...
9732     //   fallthrough --> loopMBB
9733     BB->addSuccessor(loop1MBB);
9734 
9735     // The 4-byte load must be aligned, while a char or short may be
9736     // anywhere in the word.  Hence all this nasty bookkeeping code.
9737     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9738     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9739     //   xori shift, shift1, 24 [16]
9740     //   rlwinm ptr, ptr1, 0, 0, 29
9741     //   slw newval2, newval, shift
9742     //   slw oldval2, oldval,shift
9743     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9744     //   slw mask, mask2, shift
9745     //   and newval3, newval2, mask
9746     //   and oldval3, oldval2, mask
9747     // loop1MBB:
9748     //   lwarx tmpDest, ptr
9749     //   and tmp, tmpDest, mask
9750     //   cmpw tmp, oldval3
9751     //   bne- midMBB
9752     // loop2MBB:
9753     //   andc tmp2, tmpDest, mask
9754     //   or tmp4, tmp2, newval3
9755     //   stwcx. tmp4, ptr
9756     //   bne- loop1MBB
9757     //   b exitBB
9758     // midMBB:
9759     //   stwcx. tmpDest, ptr
9760     // exitBB:
9761     //   srw dest, tmpDest, shift
9762     if (ptrA != ZeroReg) {
9763       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9764       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9765         .addReg(ptrA).addReg(ptrB);
9766     } else {
9767       Ptr1Reg = ptrB;
9768     }
9769     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9770         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9771     if (!isLittleEndian)
9772       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9773           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9774     if (is64bit)
9775       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9776         .addReg(Ptr1Reg).addImm(0).addImm(61);
9777     else
9778       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9779         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9780     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9781         .addReg(newval).addReg(ShiftReg);
9782     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9783         .addReg(oldval).addReg(ShiftReg);
9784     if (is8bit)
9785       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9786     else {
9787       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9788       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9789         .addReg(Mask3Reg).addImm(65535);
9790     }
9791     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9792         .addReg(Mask2Reg).addReg(ShiftReg);
9793     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9794         .addReg(NewVal2Reg).addReg(MaskReg);
9795     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9796         .addReg(OldVal2Reg).addReg(MaskReg);
9797 
9798     BB = loop1MBB;
9799     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9800         .addReg(ZeroReg).addReg(PtrReg);
9801     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9802         .addReg(TmpDestReg).addReg(MaskReg);
9803     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9804         .addReg(TmpReg).addReg(OldVal3Reg);
9805     BuildMI(BB, dl, TII->get(PPC::BCC))
9806         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9807     BB->addSuccessor(loop2MBB);
9808     BB->addSuccessor(midMBB);
9809 
9810     BB = loop2MBB;
9811     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9812         .addReg(TmpDestReg).addReg(MaskReg);
9813     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9814         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9815     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9816         .addReg(ZeroReg).addReg(PtrReg);
9817     BuildMI(BB, dl, TII->get(PPC::BCC))
9818       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9819     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9820     BB->addSuccessor(loop1MBB);
9821     BB->addSuccessor(exitMBB);
9822 
9823     BB = midMBB;
9824     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9825       .addReg(ZeroReg).addReg(PtrReg);
9826     BB->addSuccessor(exitMBB);
9827 
9828     //  exitMBB:
9829     //   ...
9830     BB = exitMBB;
9831     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9832       .addReg(ShiftReg);
9833   } else if (MI.getOpcode() == PPC::FADDrtz) {
9834     // This pseudo performs an FADD with rounding mode temporarily forced
9835     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9836     // is not modeled at the SelectionDAG level.
9837     unsigned Dest = MI.getOperand(0).getReg();
9838     unsigned Src1 = MI.getOperand(1).getReg();
9839     unsigned Src2 = MI.getOperand(2).getReg();
9840     DebugLoc dl = MI.getDebugLoc();
9841 
9842     MachineRegisterInfo &RegInfo = F->getRegInfo();
9843     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9844 
9845     // Save FPSCR value.
9846     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9847 
9848     // Set rounding mode to round-to-zero.
9849     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9850     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9851 
9852     // Perform addition.
9853     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9854 
9855     // Restore FPSCR value.
9856     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9857   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9858              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9859              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9860              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9861     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9862                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9863                           ? PPC::ANDIo8
9864                           : PPC::ANDIo;
9865     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9866                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9867 
9868     MachineRegisterInfo &RegInfo = F->getRegInfo();
9869     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9870                                                   &PPC::GPRCRegClass :
9871                                                   &PPC::G8RCRegClass);
9872 
9873     DebugLoc dl = MI.getDebugLoc();
9874     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9875         .addReg(MI.getOperand(1).getReg())
9876         .addImm(1);
9877     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9878             MI.getOperand(0).getReg())
9879         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9880   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9881     DebugLoc Dl = MI.getDebugLoc();
9882     MachineRegisterInfo &RegInfo = F->getRegInfo();
9883     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9884     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9885     return BB;
9886   } else {
9887     llvm_unreachable("Unexpected instr type to insert");
9888   }
9889 
9890   MI.eraseFromParent(); // The pseudo instruction is gone now.
9891   return BB;
9892 }
9893 
9894 //===----------------------------------------------------------------------===//
9895 // Target Optimization Hooks
9896 //===----------------------------------------------------------------------===//
9897 
9898 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9899   // For the estimates, convergence is quadratic, so we essentially double the
9900   // number of digits correct after every iteration. For both FRE and FRSQRTE,
9901   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9902   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9903   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9904   if (VT.getScalarType() == MVT::f64)
9905     RefinementSteps++;
9906   return RefinementSteps;
9907 }
9908 
9909 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9910                                            int Enabled, int &RefinementSteps,
9911                                            bool &UseOneConstNR,
9912                                            bool Reciprocal) const {
9913   EVT VT = Operand.getValueType();
9914   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9915       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9916       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9917       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9918       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9919       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9920     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9921       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9922 
9923     UseOneConstNR = true;
9924     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9925   }
9926   return SDValue();
9927 }
9928 
9929 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9930                                             int Enabled,
9931                                             int &RefinementSteps) const {
9932   EVT VT = Operand.getValueType();
9933   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9934       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9935       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9936       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9937       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9938       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9939     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9940       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9941     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9942   }
9943   return SDValue();
9944 }
9945 
9946 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9947   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9948   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9949   // enabled for division), this functionality is redundant with the default
9950   // combiner logic (once the division -> reciprocal/multiply transformation
9951   // has taken place). As a result, this matters more for older cores than for
9952   // newer ones.
9953 
9954   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9955   // reciprocal if there are two or more FDIVs (for embedded cores with only
9956   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9957   switch (Subtarget.getDarwinDirective()) {
9958   default:
9959     return 3;
9960   case PPC::DIR_440:
9961   case PPC::DIR_A2:
9962   case PPC::DIR_E500mc:
9963   case PPC::DIR_E5500:
9964     return 2;
9965   }
9966 }
9967 
9968 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9969 // collapsed, and so we need to look through chains of them.
9970 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9971                                      int64_t& Offset, SelectionDAG &DAG) {
9972   if (DAG.isBaseWithConstantOffset(Loc)) {
9973     Base = Loc.getOperand(0);
9974     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9975 
9976     // The base might itself be a base plus an offset, and if so, accumulate
9977     // that as well.
9978     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9979   }
9980 }
9981 
9982 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9983                             unsigned Bytes, int Dist,
9984                             SelectionDAG &DAG) {
9985   if (VT.getSizeInBits() / 8 != Bytes)
9986     return false;
9987 
9988   SDValue BaseLoc = Base->getBasePtr();
9989   if (Loc.getOpcode() == ISD::FrameIndex) {
9990     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9991       return false;
9992     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9993     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9994     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9995     int FS  = MFI.getObjectSize(FI);
9996     int BFS = MFI.getObjectSize(BFI);
9997     if (FS != BFS || FS != (int)Bytes) return false;
9998     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
9999   }
10000 
10001   SDValue Base1 = Loc, Base2 = BaseLoc;
10002   int64_t Offset1 = 0, Offset2 = 0;
10003   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10004   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10005   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10006     return true;
10007 
10008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10009   const GlobalValue *GV1 = nullptr;
10010   const GlobalValue *GV2 = nullptr;
10011   Offset1 = 0;
10012   Offset2 = 0;
10013   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10014   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10015   if (isGA1 && isGA2 && GV1 == GV2)
10016     return Offset1 == (Offset2 + Dist*Bytes);
10017   return false;
10018 }
10019 
10020 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10021 // not enforce equality of the chain operands.
10022 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10023                             unsigned Bytes, int Dist,
10024                             SelectionDAG &DAG) {
10025   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10026     EVT VT = LS->getMemoryVT();
10027     SDValue Loc = LS->getBasePtr();
10028     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10029   }
10030 
10031   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10032     EVT VT;
10033     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10034     default: return false;
10035     case Intrinsic::ppc_qpx_qvlfd:
10036     case Intrinsic::ppc_qpx_qvlfda:
10037       VT = MVT::v4f64;
10038       break;
10039     case Intrinsic::ppc_qpx_qvlfs:
10040     case Intrinsic::ppc_qpx_qvlfsa:
10041       VT = MVT::v4f32;
10042       break;
10043     case Intrinsic::ppc_qpx_qvlfcd:
10044     case Intrinsic::ppc_qpx_qvlfcda:
10045       VT = MVT::v2f64;
10046       break;
10047     case Intrinsic::ppc_qpx_qvlfcs:
10048     case Intrinsic::ppc_qpx_qvlfcsa:
10049       VT = MVT::v2f32;
10050       break;
10051     case Intrinsic::ppc_qpx_qvlfiwa:
10052     case Intrinsic::ppc_qpx_qvlfiwz:
10053     case Intrinsic::ppc_altivec_lvx:
10054     case Intrinsic::ppc_altivec_lvxl:
10055     case Intrinsic::ppc_vsx_lxvw4x:
10056     case Intrinsic::ppc_vsx_lxvw4x_be:
10057       VT = MVT::v4i32;
10058       break;
10059     case Intrinsic::ppc_vsx_lxvd2x:
10060     case Intrinsic::ppc_vsx_lxvd2x_be:
10061       VT = MVT::v2f64;
10062       break;
10063     case Intrinsic::ppc_altivec_lvebx:
10064       VT = MVT::i8;
10065       break;
10066     case Intrinsic::ppc_altivec_lvehx:
10067       VT = MVT::i16;
10068       break;
10069     case Intrinsic::ppc_altivec_lvewx:
10070       VT = MVT::i32;
10071       break;
10072     }
10073 
10074     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10075   }
10076 
10077   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10078     EVT VT;
10079     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10080     default: return false;
10081     case Intrinsic::ppc_qpx_qvstfd:
10082     case Intrinsic::ppc_qpx_qvstfda:
10083       VT = MVT::v4f64;
10084       break;
10085     case Intrinsic::ppc_qpx_qvstfs:
10086     case Intrinsic::ppc_qpx_qvstfsa:
10087       VT = MVT::v4f32;
10088       break;
10089     case Intrinsic::ppc_qpx_qvstfcd:
10090     case Intrinsic::ppc_qpx_qvstfcda:
10091       VT = MVT::v2f64;
10092       break;
10093     case Intrinsic::ppc_qpx_qvstfcs:
10094     case Intrinsic::ppc_qpx_qvstfcsa:
10095       VT = MVT::v2f32;
10096       break;
10097     case Intrinsic::ppc_qpx_qvstfiw:
10098     case Intrinsic::ppc_qpx_qvstfiwa:
10099     case Intrinsic::ppc_altivec_stvx:
10100     case Intrinsic::ppc_altivec_stvxl:
10101     case Intrinsic::ppc_vsx_stxvw4x:
10102       VT = MVT::v4i32;
10103       break;
10104     case Intrinsic::ppc_vsx_stxvd2x:
10105       VT = MVT::v2f64;
10106       break;
10107     case Intrinsic::ppc_vsx_stxvw4x_be:
10108       VT = MVT::v4i32;
10109       break;
10110     case Intrinsic::ppc_vsx_stxvd2x_be:
10111       VT = MVT::v2f64;
10112       break;
10113     case Intrinsic::ppc_altivec_stvebx:
10114       VT = MVT::i8;
10115       break;
10116     case Intrinsic::ppc_altivec_stvehx:
10117       VT = MVT::i16;
10118       break;
10119     case Intrinsic::ppc_altivec_stvewx:
10120       VT = MVT::i32;
10121       break;
10122     }
10123 
10124     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10125   }
10126 
10127   return false;
10128 }
10129 
10130 // Return true is there is a nearyby consecutive load to the one provided
10131 // (regardless of alignment). We search up and down the chain, looking though
10132 // token factors and other loads (but nothing else). As a result, a true result
10133 // indicates that it is safe to create a new consecutive load adjacent to the
10134 // load provided.
10135 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10136   SDValue Chain = LD->getChain();
10137   EVT VT = LD->getMemoryVT();
10138 
10139   SmallSet<SDNode *, 16> LoadRoots;
10140   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10141   SmallSet<SDNode *, 16> Visited;
10142 
10143   // First, search up the chain, branching to follow all token-factor operands.
10144   // If we find a consecutive load, then we're done, otherwise, record all
10145   // nodes just above the top-level loads and token factors.
10146   while (!Queue.empty()) {
10147     SDNode *ChainNext = Queue.pop_back_val();
10148     if (!Visited.insert(ChainNext).second)
10149       continue;
10150 
10151     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10152       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10153         return true;
10154 
10155       if (!Visited.count(ChainLD->getChain().getNode()))
10156         Queue.push_back(ChainLD->getChain().getNode());
10157     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10158       for (const SDUse &O : ChainNext->ops())
10159         if (!Visited.count(O.getNode()))
10160           Queue.push_back(O.getNode());
10161     } else
10162       LoadRoots.insert(ChainNext);
10163   }
10164 
10165   // Second, search down the chain, starting from the top-level nodes recorded
10166   // in the first phase. These top-level nodes are the nodes just above all
10167   // loads and token factors. Starting with their uses, recursively look though
10168   // all loads (just the chain uses) and token factors to find a consecutive
10169   // load.
10170   Visited.clear();
10171   Queue.clear();
10172 
10173   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10174        IE = LoadRoots.end(); I != IE; ++I) {
10175     Queue.push_back(*I);
10176 
10177     while (!Queue.empty()) {
10178       SDNode *LoadRoot = Queue.pop_back_val();
10179       if (!Visited.insert(LoadRoot).second)
10180         continue;
10181 
10182       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10183         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10184           return true;
10185 
10186       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10187            UE = LoadRoot->use_end(); UI != UE; ++UI)
10188         if (((isa<MemSDNode>(*UI) &&
10189             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10190             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10191           Queue.push_back(*UI);
10192     }
10193   }
10194 
10195   return false;
10196 }
10197 
10198 /// This function is called when we have proved that a SETCC node can be replaced
10199 /// by subtraction (and other supporting instructions) so that the result of
10200 /// comparison is kept in a GPR instead of CR. This function is purely for
10201 /// codegen purposes and has some flags to guide the codegen process.
10202 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10203                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10204   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10205 
10206   // Zero extend the operands to the largest legal integer. Originally, they
10207   // must be of a strictly smaller size.
10208   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10209                          DAG.getConstant(Size, DL, MVT::i32));
10210   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10211                          DAG.getConstant(Size, DL, MVT::i32));
10212 
10213   // Swap if needed. Depends on the condition code.
10214   if (Swap)
10215     std::swap(Op0, Op1);
10216 
10217   // Subtract extended integers.
10218   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10219 
10220   // Move the sign bit to the least significant position and zero out the rest.
10221   // Now the least significant bit carries the result of original comparison.
10222   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10223                              DAG.getConstant(Size - 1, DL, MVT::i32));
10224   auto Final = Shifted;
10225 
10226   // Complement the result if needed. Based on the condition code.
10227   if (Complement)
10228     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10229                         DAG.getConstant(1, DL, MVT::i64));
10230 
10231   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10232 }
10233 
10234 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10235                                                   DAGCombinerInfo &DCI) const {
10236   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10237 
10238   SelectionDAG &DAG = DCI.DAG;
10239   SDLoc DL(N);
10240 
10241   // Size of integers being compared has a critical role in the following
10242   // analysis, so we prefer to do this when all types are legal.
10243   if (!DCI.isAfterLegalizeVectorOps())
10244     return SDValue();
10245 
10246   // If all users of SETCC extend its value to a legal integer type
10247   // then we replace SETCC with a subtraction
10248   for (SDNode::use_iterator UI = N->use_begin(),
10249        UE = N->use_end(); UI != UE; ++UI) {
10250     if (UI->getOpcode() != ISD::ZERO_EXTEND)
10251       return SDValue();
10252   }
10253 
10254   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10255   auto OpSize = N->getOperand(0).getValueSizeInBits();
10256 
10257   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10258 
10259   if (OpSize < Size) {
10260     switch (CC) {
10261     default: break;
10262     case ISD::SETULT:
10263       return generateEquivalentSub(N, Size, false, false, DL, DAG);
10264     case ISD::SETULE:
10265       return generateEquivalentSub(N, Size, true, true, DL, DAG);
10266     case ISD::SETUGT:
10267       return generateEquivalentSub(N, Size, false, true, DL, DAG);
10268     case ISD::SETUGE:
10269       return generateEquivalentSub(N, Size, true, false, DL, DAG);
10270     }
10271   }
10272 
10273   return SDValue();
10274 }
10275 
10276 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10277                                                   DAGCombinerInfo &DCI) const {
10278   SelectionDAG &DAG = DCI.DAG;
10279   SDLoc dl(N);
10280 
10281   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10282   // If we're tracking CR bits, we need to be careful that we don't have:
10283   //   trunc(binary-ops(zext(x), zext(y)))
10284   // or
10285   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10286   // such that we're unnecessarily moving things into GPRs when it would be
10287   // better to keep them in CR bits.
10288 
10289   // Note that trunc here can be an actual i1 trunc, or can be the effective
10290   // truncation that comes from a setcc or select_cc.
10291   if (N->getOpcode() == ISD::TRUNCATE &&
10292       N->getValueType(0) != MVT::i1)
10293     return SDValue();
10294 
10295   if (N->getOperand(0).getValueType() != MVT::i32 &&
10296       N->getOperand(0).getValueType() != MVT::i64)
10297     return SDValue();
10298 
10299   if (N->getOpcode() == ISD::SETCC ||
10300       N->getOpcode() == ISD::SELECT_CC) {
10301     // If we're looking at a comparison, then we need to make sure that the
10302     // high bits (all except for the first) don't matter the result.
10303     ISD::CondCode CC =
10304       cast<CondCodeSDNode>(N->getOperand(
10305         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10306     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10307 
10308     if (ISD::isSignedIntSetCC(CC)) {
10309       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10310           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10311         return SDValue();
10312     } else if (ISD::isUnsignedIntSetCC(CC)) {
10313       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10314                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10315           !DAG.MaskedValueIsZero(N->getOperand(1),
10316                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10317         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10318                                              : SDValue());
10319     } else {
10320       // This is neither a signed nor an unsigned comparison, just make sure
10321       // that the high bits are equal.
10322       APInt Op1Zero, Op1One;
10323       APInt Op2Zero, Op2One;
10324       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
10325       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
10326 
10327       // We don't really care about what is known about the first bit (if
10328       // anything), so clear it in all masks prior to comparing them.
10329       Op1Zero.clearBit(0); Op1One.clearBit(0);
10330       Op2Zero.clearBit(0); Op2One.clearBit(0);
10331 
10332       if (Op1Zero != Op2Zero || Op1One != Op2One)
10333         return SDValue();
10334     }
10335   }
10336 
10337   // We now know that the higher-order bits are irrelevant, we just need to
10338   // make sure that all of the intermediate operations are bit operations, and
10339   // all inputs are extensions.
10340   if (N->getOperand(0).getOpcode() != ISD::AND &&
10341       N->getOperand(0).getOpcode() != ISD::OR  &&
10342       N->getOperand(0).getOpcode() != ISD::XOR &&
10343       N->getOperand(0).getOpcode() != ISD::SELECT &&
10344       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10345       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10346       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10347       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10348       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10349     return SDValue();
10350 
10351   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10352       N->getOperand(1).getOpcode() != ISD::AND &&
10353       N->getOperand(1).getOpcode() != ISD::OR  &&
10354       N->getOperand(1).getOpcode() != ISD::XOR &&
10355       N->getOperand(1).getOpcode() != ISD::SELECT &&
10356       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10357       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10358       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10359       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10360       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10361     return SDValue();
10362 
10363   SmallVector<SDValue, 4> Inputs;
10364   SmallVector<SDValue, 8> BinOps, PromOps;
10365   SmallPtrSet<SDNode *, 16> Visited;
10366 
10367   for (unsigned i = 0; i < 2; ++i) {
10368     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10369           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10370           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10371           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10372         isa<ConstantSDNode>(N->getOperand(i)))
10373       Inputs.push_back(N->getOperand(i));
10374     else
10375       BinOps.push_back(N->getOperand(i));
10376 
10377     if (N->getOpcode() == ISD::TRUNCATE)
10378       break;
10379   }
10380 
10381   // Visit all inputs, collect all binary operations (and, or, xor and
10382   // select) that are all fed by extensions.
10383   while (!BinOps.empty()) {
10384     SDValue BinOp = BinOps.back();
10385     BinOps.pop_back();
10386 
10387     if (!Visited.insert(BinOp.getNode()).second)
10388       continue;
10389 
10390     PromOps.push_back(BinOp);
10391 
10392     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10393       // The condition of the select is not promoted.
10394       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10395         continue;
10396       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10397         continue;
10398 
10399       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10400             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10401             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10402            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10403           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10404         Inputs.push_back(BinOp.getOperand(i));
10405       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10406                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10407                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10408                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10409                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10410                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10411                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10412                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10413                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10414         BinOps.push_back(BinOp.getOperand(i));
10415       } else {
10416         // We have an input that is not an extension or another binary
10417         // operation; we'll abort this transformation.
10418         return SDValue();
10419       }
10420     }
10421   }
10422 
10423   // Make sure that this is a self-contained cluster of operations (which
10424   // is not quite the same thing as saying that everything has only one
10425   // use).
10426   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10427     if (isa<ConstantSDNode>(Inputs[i]))
10428       continue;
10429 
10430     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10431                               UE = Inputs[i].getNode()->use_end();
10432          UI != UE; ++UI) {
10433       SDNode *User = *UI;
10434       if (User != N && !Visited.count(User))
10435         return SDValue();
10436 
10437       // Make sure that we're not going to promote the non-output-value
10438       // operand(s) or SELECT or SELECT_CC.
10439       // FIXME: Although we could sometimes handle this, and it does occur in
10440       // practice that one of the condition inputs to the select is also one of
10441       // the outputs, we currently can't deal with this.
10442       if (User->getOpcode() == ISD::SELECT) {
10443         if (User->getOperand(0) == Inputs[i])
10444           return SDValue();
10445       } else if (User->getOpcode() == ISD::SELECT_CC) {
10446         if (User->getOperand(0) == Inputs[i] ||
10447             User->getOperand(1) == Inputs[i])
10448           return SDValue();
10449       }
10450     }
10451   }
10452 
10453   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10454     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10455                               UE = PromOps[i].getNode()->use_end();
10456          UI != UE; ++UI) {
10457       SDNode *User = *UI;
10458       if (User != N && !Visited.count(User))
10459         return SDValue();
10460 
10461       // Make sure that we're not going to promote the non-output-value
10462       // operand(s) or SELECT or SELECT_CC.
10463       // FIXME: Although we could sometimes handle this, and it does occur in
10464       // practice that one of the condition inputs to the select is also one of
10465       // the outputs, we currently can't deal with this.
10466       if (User->getOpcode() == ISD::SELECT) {
10467         if (User->getOperand(0) == PromOps[i])
10468           return SDValue();
10469       } else if (User->getOpcode() == ISD::SELECT_CC) {
10470         if (User->getOperand(0) == PromOps[i] ||
10471             User->getOperand(1) == PromOps[i])
10472           return SDValue();
10473       }
10474     }
10475   }
10476 
10477   // Replace all inputs with the extension operand.
10478   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10479     // Constants may have users outside the cluster of to-be-promoted nodes,
10480     // and so we need to replace those as we do the promotions.
10481     if (isa<ConstantSDNode>(Inputs[i]))
10482       continue;
10483     else
10484       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10485   }
10486 
10487   std::list<HandleSDNode> PromOpHandles;
10488   for (auto &PromOp : PromOps)
10489     PromOpHandles.emplace_back(PromOp);
10490 
10491   // Replace all operations (these are all the same, but have a different
10492   // (i1) return type). DAG.getNode will validate that the types of
10493   // a binary operator match, so go through the list in reverse so that
10494   // we've likely promoted both operands first. Any intermediate truncations or
10495   // extensions disappear.
10496   while (!PromOpHandles.empty()) {
10497     SDValue PromOp = PromOpHandles.back().getValue();
10498     PromOpHandles.pop_back();
10499 
10500     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10501         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10502         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10503         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10504       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10505           PromOp.getOperand(0).getValueType() != MVT::i1) {
10506         // The operand is not yet ready (see comment below).
10507         PromOpHandles.emplace_front(PromOp);
10508         continue;
10509       }
10510 
10511       SDValue RepValue = PromOp.getOperand(0);
10512       if (isa<ConstantSDNode>(RepValue))
10513         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10514 
10515       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10516       continue;
10517     }
10518 
10519     unsigned C;
10520     switch (PromOp.getOpcode()) {
10521     default:             C = 0; break;
10522     case ISD::SELECT:    C = 1; break;
10523     case ISD::SELECT_CC: C = 2; break;
10524     }
10525 
10526     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10527          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10528         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10529          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10530       // The to-be-promoted operands of this node have not yet been
10531       // promoted (this should be rare because we're going through the
10532       // list backward, but if one of the operands has several users in
10533       // this cluster of to-be-promoted nodes, it is possible).
10534       PromOpHandles.emplace_front(PromOp);
10535       continue;
10536     }
10537 
10538     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10539                                 PromOp.getNode()->op_end());
10540 
10541     // If there are any constant inputs, make sure they're replaced now.
10542     for (unsigned i = 0; i < 2; ++i)
10543       if (isa<ConstantSDNode>(Ops[C+i]))
10544         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10545 
10546     DAG.ReplaceAllUsesOfValueWith(PromOp,
10547       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10548   }
10549 
10550   // Now we're left with the initial truncation itself.
10551   if (N->getOpcode() == ISD::TRUNCATE)
10552     return N->getOperand(0);
10553 
10554   // Otherwise, this is a comparison. The operands to be compared have just
10555   // changed type (to i1), but everything else is the same.
10556   return SDValue(N, 0);
10557 }
10558 
10559 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10560                                                   DAGCombinerInfo &DCI) const {
10561   SelectionDAG &DAG = DCI.DAG;
10562   SDLoc dl(N);
10563 
10564   // If we're tracking CR bits, we need to be careful that we don't have:
10565   //   zext(binary-ops(trunc(x), trunc(y)))
10566   // or
10567   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10568   // such that we're unnecessarily moving things into CR bits that can more
10569   // efficiently stay in GPRs. Note that if we're not certain that the high
10570   // bits are set as required by the final extension, we still may need to do
10571   // some masking to get the proper behavior.
10572 
10573   // This same functionality is important on PPC64 when dealing with
10574   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10575   // the return values of functions. Because it is so similar, it is handled
10576   // here as well.
10577 
10578   if (N->getValueType(0) != MVT::i32 &&
10579       N->getValueType(0) != MVT::i64)
10580     return SDValue();
10581 
10582   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10583         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10584     return SDValue();
10585 
10586   if (N->getOperand(0).getOpcode() != ISD::AND &&
10587       N->getOperand(0).getOpcode() != ISD::OR  &&
10588       N->getOperand(0).getOpcode() != ISD::XOR &&
10589       N->getOperand(0).getOpcode() != ISD::SELECT &&
10590       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10591     return SDValue();
10592 
10593   SmallVector<SDValue, 4> Inputs;
10594   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10595   SmallPtrSet<SDNode *, 16> Visited;
10596 
10597   // Visit all inputs, collect all binary operations (and, or, xor and
10598   // select) that are all fed by truncations.
10599   while (!BinOps.empty()) {
10600     SDValue BinOp = BinOps.back();
10601     BinOps.pop_back();
10602 
10603     if (!Visited.insert(BinOp.getNode()).second)
10604       continue;
10605 
10606     PromOps.push_back(BinOp);
10607 
10608     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10609       // The condition of the select is not promoted.
10610       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10611         continue;
10612       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10613         continue;
10614 
10615       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10616           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10617         Inputs.push_back(BinOp.getOperand(i));
10618       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10619                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10620                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10621                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10622                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10623         BinOps.push_back(BinOp.getOperand(i));
10624       } else {
10625         // We have an input that is not a truncation or another binary
10626         // operation; we'll abort this transformation.
10627         return SDValue();
10628       }
10629     }
10630   }
10631 
10632   // The operands of a select that must be truncated when the select is
10633   // promoted because the operand is actually part of the to-be-promoted set.
10634   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10635 
10636   // Make sure that this is a self-contained cluster of operations (which
10637   // is not quite the same thing as saying that everything has only one
10638   // use).
10639   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10640     if (isa<ConstantSDNode>(Inputs[i]))
10641       continue;
10642 
10643     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10644                               UE = Inputs[i].getNode()->use_end();
10645          UI != UE; ++UI) {
10646       SDNode *User = *UI;
10647       if (User != N && !Visited.count(User))
10648         return SDValue();
10649 
10650       // If we're going to promote the non-output-value operand(s) or SELECT or
10651       // SELECT_CC, record them for truncation.
10652       if (User->getOpcode() == ISD::SELECT) {
10653         if (User->getOperand(0) == Inputs[i])
10654           SelectTruncOp[0].insert(std::make_pair(User,
10655                                     User->getOperand(0).getValueType()));
10656       } else if (User->getOpcode() == ISD::SELECT_CC) {
10657         if (User->getOperand(0) == Inputs[i])
10658           SelectTruncOp[0].insert(std::make_pair(User,
10659                                     User->getOperand(0).getValueType()));
10660         if (User->getOperand(1) == Inputs[i])
10661           SelectTruncOp[1].insert(std::make_pair(User,
10662                                     User->getOperand(1).getValueType()));
10663       }
10664     }
10665   }
10666 
10667   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10668     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10669                               UE = PromOps[i].getNode()->use_end();
10670          UI != UE; ++UI) {
10671       SDNode *User = *UI;
10672       if (User != N && !Visited.count(User))
10673         return SDValue();
10674 
10675       // If we're going to promote the non-output-value operand(s) or SELECT or
10676       // SELECT_CC, record them for truncation.
10677       if (User->getOpcode() == ISD::SELECT) {
10678         if (User->getOperand(0) == PromOps[i])
10679           SelectTruncOp[0].insert(std::make_pair(User,
10680                                     User->getOperand(0).getValueType()));
10681       } else if (User->getOpcode() == ISD::SELECT_CC) {
10682         if (User->getOperand(0) == PromOps[i])
10683           SelectTruncOp[0].insert(std::make_pair(User,
10684                                     User->getOperand(0).getValueType()));
10685         if (User->getOperand(1) == PromOps[i])
10686           SelectTruncOp[1].insert(std::make_pair(User,
10687                                     User->getOperand(1).getValueType()));
10688       }
10689     }
10690   }
10691 
10692   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10693   bool ReallyNeedsExt = false;
10694   if (N->getOpcode() != ISD::ANY_EXTEND) {
10695     // If all of the inputs are not already sign/zero extended, then
10696     // we'll still need to do that at the end.
10697     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10698       if (isa<ConstantSDNode>(Inputs[i]))
10699         continue;
10700 
10701       unsigned OpBits =
10702         Inputs[i].getOperand(0).getValueSizeInBits();
10703       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10704 
10705       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10706            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10707                                   APInt::getHighBitsSet(OpBits,
10708                                                         OpBits-PromBits))) ||
10709           (N->getOpcode() == ISD::SIGN_EXTEND &&
10710            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10711              (OpBits-(PromBits-1)))) {
10712         ReallyNeedsExt = true;
10713         break;
10714       }
10715     }
10716   }
10717 
10718   // Replace all inputs, either with the truncation operand, or a
10719   // truncation or extension to the final output type.
10720   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10721     // Constant inputs need to be replaced with the to-be-promoted nodes that
10722     // use them because they might have users outside of the cluster of
10723     // promoted nodes.
10724     if (isa<ConstantSDNode>(Inputs[i]))
10725       continue;
10726 
10727     SDValue InSrc = Inputs[i].getOperand(0);
10728     if (Inputs[i].getValueType() == N->getValueType(0))
10729       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10730     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10731       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10732         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10733     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10734       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10735         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10736     else
10737       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10738         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10739   }
10740 
10741   std::list<HandleSDNode> PromOpHandles;
10742   for (auto &PromOp : PromOps)
10743     PromOpHandles.emplace_back(PromOp);
10744 
10745   // Replace all operations (these are all the same, but have a different
10746   // (promoted) return type). DAG.getNode will validate that the types of
10747   // a binary operator match, so go through the list in reverse so that
10748   // we've likely promoted both operands first.
10749   while (!PromOpHandles.empty()) {
10750     SDValue PromOp = PromOpHandles.back().getValue();
10751     PromOpHandles.pop_back();
10752 
10753     unsigned C;
10754     switch (PromOp.getOpcode()) {
10755     default:             C = 0; break;
10756     case ISD::SELECT:    C = 1; break;
10757     case ISD::SELECT_CC: C = 2; break;
10758     }
10759 
10760     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10761          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10762         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10763          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10764       // The to-be-promoted operands of this node have not yet been
10765       // promoted (this should be rare because we're going through the
10766       // list backward, but if one of the operands has several users in
10767       // this cluster of to-be-promoted nodes, it is possible).
10768       PromOpHandles.emplace_front(PromOp);
10769       continue;
10770     }
10771 
10772     // For SELECT and SELECT_CC nodes, we do a similar check for any
10773     // to-be-promoted comparison inputs.
10774     if (PromOp.getOpcode() == ISD::SELECT ||
10775         PromOp.getOpcode() == ISD::SELECT_CC) {
10776       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10777            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10778           (SelectTruncOp[1].count(PromOp.getNode()) &&
10779            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10780         PromOpHandles.emplace_front(PromOp);
10781         continue;
10782       }
10783     }
10784 
10785     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10786                                 PromOp.getNode()->op_end());
10787 
10788     // If this node has constant inputs, then they'll need to be promoted here.
10789     for (unsigned i = 0; i < 2; ++i) {
10790       if (!isa<ConstantSDNode>(Ops[C+i]))
10791         continue;
10792       if (Ops[C+i].getValueType() == N->getValueType(0))
10793         continue;
10794 
10795       if (N->getOpcode() == ISD::SIGN_EXTEND)
10796         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10797       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10798         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10799       else
10800         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10801     }
10802 
10803     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10804     // truncate them again to the original value type.
10805     if (PromOp.getOpcode() == ISD::SELECT ||
10806         PromOp.getOpcode() == ISD::SELECT_CC) {
10807       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10808       if (SI0 != SelectTruncOp[0].end())
10809         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10810       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10811       if (SI1 != SelectTruncOp[1].end())
10812         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10813     }
10814 
10815     DAG.ReplaceAllUsesOfValueWith(PromOp,
10816       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10817   }
10818 
10819   // Now we're left with the initial extension itself.
10820   if (!ReallyNeedsExt)
10821     return N->getOperand(0);
10822 
10823   // To zero extend, just mask off everything except for the first bit (in the
10824   // i1 case).
10825   if (N->getOpcode() == ISD::ZERO_EXTEND)
10826     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10827                        DAG.getConstant(APInt::getLowBitsSet(
10828                                          N->getValueSizeInBits(0), PromBits),
10829                                        dl, N->getValueType(0)));
10830 
10831   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10832          "Invalid extension type");
10833   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10834   SDValue ShiftCst =
10835       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10836   return DAG.getNode(
10837       ISD::SRA, dl, N->getValueType(0),
10838       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10839       ShiftCst);
10840 }
10841 
10842 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10843 ///
10844 /// If this vector is built out of floating to integer conversions,
10845 /// transform it to a vector built out of floating point values followed by a
10846 /// single floating to integer conversion of the vector.
10847 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
10848 /// becomes (fptosi (build_vector ($A, $B, ...)))
10849 SDValue PPCTargetLowering::
10850 combineElementTruncationToVectorTruncation(SDNode *N,
10851                                            DAGCombinerInfo &DCI) const {
10852   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10853          "Should be called with a BUILD_VECTOR node");
10854 
10855   SelectionDAG &DAG = DCI.DAG;
10856   SDLoc dl(N);
10857 
10858   SDValue FirstInput = N->getOperand(0);
10859   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10860          "The input operand must be an fp-to-int conversion.");
10861 
10862   // This combine happens after legalization so the fp_to_[su]i nodes are
10863   // already converted to PPCSISD nodes.
10864   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10865   if (FirstConversion == PPCISD::FCTIDZ ||
10866       FirstConversion == PPCISD::FCTIDUZ ||
10867       FirstConversion == PPCISD::FCTIWZ ||
10868       FirstConversion == PPCISD::FCTIWUZ) {
10869     bool IsSplat = true;
10870     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10871       FirstConversion == PPCISD::FCTIWUZ;
10872     EVT SrcVT = FirstInput.getOperand(0).getValueType();
10873     SmallVector<SDValue, 4> Ops;
10874     EVT TargetVT = N->getValueType(0);
10875     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10876       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
10877         return SDValue();
10878       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
10879       if (NextConversion != FirstConversion)
10880         return SDValue();
10881       if (N->getOperand(i) != FirstInput)
10882         IsSplat = false;
10883     }
10884 
10885     // If this is a splat, we leave it as-is since there will be only a single
10886     // fp-to-int conversion followed by a splat of the integer. This is better
10887     // for 32-bit and smaller ints and neutral for 64-bit ints.
10888     if (IsSplat)
10889       return SDValue();
10890 
10891     // Now that we know we have the right type of node, get its operands
10892     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10893       SDValue In = N->getOperand(i).getOperand(0);
10894       // For 32-bit values, we need to add an FP_ROUND node.
10895       if (Is32Bit) {
10896         if (In.isUndef())
10897           Ops.push_back(DAG.getUNDEF(SrcVT));
10898         else {
10899           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
10900                                       MVT::f32, In.getOperand(0),
10901                                       DAG.getIntPtrConstant(1, dl));
10902           Ops.push_back(Trunc);
10903         }
10904       } else
10905         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
10906     }
10907 
10908     unsigned Opcode;
10909     if (FirstConversion == PPCISD::FCTIDZ ||
10910         FirstConversion == PPCISD::FCTIWZ)
10911       Opcode = ISD::FP_TO_SINT;
10912     else
10913       Opcode = ISD::FP_TO_UINT;
10914 
10915     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
10916     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
10917     return DAG.getNode(Opcode, dl, TargetVT, BV);
10918   }
10919   return SDValue();
10920 }
10921 
10922 /// \brief Reduce the number of loads when building a vector.
10923 ///
10924 /// Building a vector out of multiple loads can be converted to a load
10925 /// of the vector type if the loads are consecutive. If the loads are
10926 /// consecutive but in descending order, a shuffle is added at the end
10927 /// to reorder the vector.
10928 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
10929   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10930          "Should be called with a BUILD_VECTOR node");
10931 
10932   SDLoc dl(N);
10933   bool InputsAreConsecutiveLoads = true;
10934   bool InputsAreReverseConsecutive = true;
10935   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
10936   SDValue FirstInput = N->getOperand(0);
10937   bool IsRoundOfExtLoad = false;
10938 
10939   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
10940       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
10941     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
10942     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
10943   }
10944   // Not a build vector of (possibly fp_rounded) loads.
10945   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
10946     return SDValue();
10947 
10948   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
10949     // If any inputs are fp_round(extload), they all must be.
10950     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
10951       return SDValue();
10952 
10953     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
10954       N->getOperand(i);
10955     if (NextInput.getOpcode() != ISD::LOAD)
10956       return SDValue();
10957 
10958     SDValue PreviousInput =
10959       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
10960     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
10961     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
10962 
10963     // If any inputs are fp_round(extload), they all must be.
10964     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
10965       return SDValue();
10966 
10967     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
10968       InputsAreConsecutiveLoads = false;
10969     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
10970       InputsAreReverseConsecutive = false;
10971 
10972     // Exit early if the loads are neither consecutive nor reverse consecutive.
10973     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
10974       return SDValue();
10975   }
10976 
10977   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
10978          "The loads cannot be both consecutive and reverse consecutive.");
10979 
10980   SDValue FirstLoadOp =
10981     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
10982   SDValue LastLoadOp =
10983     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
10984                        N->getOperand(N->getNumOperands()-1);
10985 
10986   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
10987   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
10988   if (InputsAreConsecutiveLoads) {
10989     assert(LD1 && "Input needs to be a LoadSDNode.");
10990     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
10991                        LD1->getBasePtr(), LD1->getPointerInfo(),
10992                        LD1->getAlignment());
10993   }
10994   if (InputsAreReverseConsecutive) {
10995     assert(LDL && "Input needs to be a LoadSDNode.");
10996     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
10997                                LDL->getBasePtr(), LDL->getPointerInfo(),
10998                                LDL->getAlignment());
10999     SmallVector<int, 16> Ops;
11000     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11001       Ops.push_back(i);
11002 
11003     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11004                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11005   }
11006   return SDValue();
11007 }
11008 
11009 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11010                                                  DAGCombinerInfo &DCI) const {
11011   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11012          "Should be called with a BUILD_VECTOR node");
11013 
11014   SelectionDAG &DAG = DCI.DAG;
11015   SDLoc dl(N);
11016 
11017   if (!Subtarget.hasVSX())
11018     return SDValue();
11019 
11020   // The target independent DAG combiner will leave a build_vector of
11021   // float-to-int conversions intact. We can generate MUCH better code for
11022   // a float-to-int conversion of a vector of floats.
11023   SDValue FirstInput = N->getOperand(0);
11024   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11025     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11026     if (Reduced)
11027       return Reduced;
11028   }
11029 
11030   // If we're building a vector out of consecutive loads, just load that
11031   // vector type.
11032   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11033   if (Reduced)
11034     return Reduced;
11035 
11036   if (N->getValueType(0) != MVT::v2f64)
11037     return SDValue();
11038 
11039   // Looking for:
11040   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11041   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11042       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11043     return SDValue();
11044   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11045       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11046     return SDValue();
11047   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11048     return SDValue();
11049 
11050   SDValue Ext1 = FirstInput.getOperand(0);
11051   SDValue Ext2 = N->getOperand(1).getOperand(0);
11052   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11053      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11054     return SDValue();
11055 
11056   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11057   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11058   if (!Ext1Op || !Ext2Op)
11059     return SDValue();
11060   if (Ext1.getValueType() != MVT::i32 ||
11061       Ext2.getValueType() != MVT::i32)
11062   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11063     return SDValue();
11064 
11065   int FirstElem = Ext1Op->getZExtValue();
11066   int SecondElem = Ext2Op->getZExtValue();
11067   int SubvecIdx;
11068   if (FirstElem == 0 && SecondElem == 1)
11069     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11070   else if (FirstElem == 2 && SecondElem == 3)
11071     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11072   else
11073     return SDValue();
11074 
11075   SDValue SrcVec = Ext1.getOperand(0);
11076   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11077     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11078   return DAG.getNode(NodeType, dl, MVT::v2f64,
11079                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11080 }
11081 
11082 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11083                                               DAGCombinerInfo &DCI) const {
11084   assert((N->getOpcode() == ISD::SINT_TO_FP ||
11085           N->getOpcode() == ISD::UINT_TO_FP) &&
11086          "Need an int -> FP conversion node here");
11087 
11088   if (useSoftFloat() || !Subtarget.has64BitSupport())
11089     return SDValue();
11090 
11091   SelectionDAG &DAG = DCI.DAG;
11092   SDLoc dl(N);
11093   SDValue Op(N, 0);
11094 
11095   SDValue FirstOperand(Op.getOperand(0));
11096   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11097     (FirstOperand.getValueType() == MVT::i8 ||
11098      FirstOperand.getValueType() == MVT::i16);
11099   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11100     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11101     bool DstDouble = Op.getValueType() == MVT::f64;
11102     unsigned ConvOp = Signed ?
11103       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
11104       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11105     SDValue WidthConst =
11106       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11107                             dl, false);
11108     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11109     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11110     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11111                                          DAG.getVTList(MVT::f64, MVT::Other),
11112                                          Ops, MVT::i8, LDN->getMemOperand());
11113 
11114     // For signed conversion, we need to sign-extend the value in the VSR
11115     if (Signed) {
11116       SDValue ExtOps[] = { Ld, WidthConst };
11117       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11118       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11119     } else
11120       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11121   }
11122 
11123   // Don't handle ppc_fp128 here or i1 conversions.
11124   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11125     return SDValue();
11126   if (Op.getOperand(0).getValueType() == MVT::i1)
11127     return SDValue();
11128 
11129   // For i32 intermediate values, unfortunately, the conversion functions
11130   // leave the upper 32 bits of the value are undefined. Within the set of
11131   // scalar instructions, we have no method for zero- or sign-extending the
11132   // value. Thus, we cannot handle i32 intermediate values here.
11133   if (Op.getOperand(0).getValueType() == MVT::i32)
11134     return SDValue();
11135 
11136   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11137          "UINT_TO_FP is supported only with FPCVT");
11138 
11139   // If we have FCFIDS, then use it when converting to single-precision.
11140   // Otherwise, convert to double-precision and then round.
11141   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11142                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11143                                                             : PPCISD::FCFIDS)
11144                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11145                                                             : PPCISD::FCFID);
11146   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11147                   ? MVT::f32
11148                   : MVT::f64;
11149 
11150   // If we're converting from a float, to an int, and back to a float again,
11151   // then we don't need the store/load pair at all.
11152   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11153        Subtarget.hasFPCVT()) ||
11154       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11155     SDValue Src = Op.getOperand(0).getOperand(0);
11156     if (Src.getValueType() == MVT::f32) {
11157       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11158       DCI.AddToWorklist(Src.getNode());
11159     } else if (Src.getValueType() != MVT::f64) {
11160       // Make sure that we don't pick up a ppc_fp128 source value.
11161       return SDValue();
11162     }
11163 
11164     unsigned FCTOp =
11165       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11166                                                         PPCISD::FCTIDUZ;
11167 
11168     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11169     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11170 
11171     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11172       FP = DAG.getNode(ISD::FP_ROUND, dl,
11173                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11174       DCI.AddToWorklist(FP.getNode());
11175     }
11176 
11177     return FP;
11178   }
11179 
11180   return SDValue();
11181 }
11182 
11183 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11184 // builtins) into loads with swaps.
11185 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11186                                               DAGCombinerInfo &DCI) const {
11187   SelectionDAG &DAG = DCI.DAG;
11188   SDLoc dl(N);
11189   SDValue Chain;
11190   SDValue Base;
11191   MachineMemOperand *MMO;
11192 
11193   switch (N->getOpcode()) {
11194   default:
11195     llvm_unreachable("Unexpected opcode for little endian VSX load");
11196   case ISD::LOAD: {
11197     LoadSDNode *LD = cast<LoadSDNode>(N);
11198     Chain = LD->getChain();
11199     Base = LD->getBasePtr();
11200     MMO = LD->getMemOperand();
11201     // If the MMO suggests this isn't a load of a full vector, leave
11202     // things alone.  For a built-in, we have to make the change for
11203     // correctness, so if there is a size problem that will be a bug.
11204     if (MMO->getSize() < 16)
11205       return SDValue();
11206     break;
11207   }
11208   case ISD::INTRINSIC_W_CHAIN: {
11209     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11210     Chain = Intrin->getChain();
11211     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11212     // us what we want. Get operand 2 instead.
11213     Base = Intrin->getOperand(2);
11214     MMO = Intrin->getMemOperand();
11215     break;
11216   }
11217   }
11218 
11219   MVT VecTy = N->getValueType(0).getSimpleVT();
11220   SDValue LoadOps[] = { Chain, Base };
11221   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11222                                          DAG.getVTList(MVT::v2f64, MVT::Other),
11223                                          LoadOps, MVT::v2f64, MMO);
11224 
11225   DCI.AddToWorklist(Load.getNode());
11226   Chain = Load.getValue(1);
11227   SDValue Swap = DAG.getNode(
11228       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11229   DCI.AddToWorklist(Swap.getNode());
11230 
11231   // Add a bitcast if the resulting load type doesn't match v2f64.
11232   if (VecTy != MVT::v2f64) {
11233     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11234     DCI.AddToWorklist(N.getNode());
11235     // Package {bitcast value, swap's chain} to match Load's shape.
11236     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11237                        N, Swap.getValue(1));
11238   }
11239 
11240   return Swap;
11241 }
11242 
11243 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11244 // builtins) into stores with swaps.
11245 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11246                                                DAGCombinerInfo &DCI) const {
11247   SelectionDAG &DAG = DCI.DAG;
11248   SDLoc dl(N);
11249   SDValue Chain;
11250   SDValue Base;
11251   unsigned SrcOpnd;
11252   MachineMemOperand *MMO;
11253 
11254   switch (N->getOpcode()) {
11255   default:
11256     llvm_unreachable("Unexpected opcode for little endian VSX store");
11257   case ISD::STORE: {
11258     StoreSDNode *ST = cast<StoreSDNode>(N);
11259     Chain = ST->getChain();
11260     Base = ST->getBasePtr();
11261     MMO = ST->getMemOperand();
11262     SrcOpnd = 1;
11263     // If the MMO suggests this isn't a store of a full vector, leave
11264     // things alone.  For a built-in, we have to make the change for
11265     // correctness, so if there is a size problem that will be a bug.
11266     if (MMO->getSize() < 16)
11267       return SDValue();
11268     break;
11269   }
11270   case ISD::INTRINSIC_VOID: {
11271     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11272     Chain = Intrin->getChain();
11273     // Intrin->getBasePtr() oddly does not get what we want.
11274     Base = Intrin->getOperand(3);
11275     MMO = Intrin->getMemOperand();
11276     SrcOpnd = 2;
11277     break;
11278   }
11279   }
11280 
11281   SDValue Src = N->getOperand(SrcOpnd);
11282   MVT VecTy = Src.getValueType().getSimpleVT();
11283 
11284   // All stores are done as v2f64 and possible bit cast.
11285   if (VecTy != MVT::v2f64) {
11286     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11287     DCI.AddToWorklist(Src.getNode());
11288   }
11289 
11290   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11291                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11292   DCI.AddToWorklist(Swap.getNode());
11293   Chain = Swap.getValue(1);
11294   SDValue StoreOps[] = { Chain, Swap, Base };
11295   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11296                                           DAG.getVTList(MVT::Other),
11297                                           StoreOps, VecTy, MMO);
11298   DCI.AddToWorklist(Store.getNode());
11299   return Store;
11300 }
11301 
11302 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11303                                              DAGCombinerInfo &DCI) const {
11304   SelectionDAG &DAG = DCI.DAG;
11305   SDLoc dl(N);
11306   switch (N->getOpcode()) {
11307   default: break;
11308   case PPCISD::SHL:
11309     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11310         return N->getOperand(0);
11311     break;
11312   case PPCISD::SRL:
11313     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11314         return N->getOperand(0);
11315     break;
11316   case PPCISD::SRA:
11317     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11318       if (C->isNullValue() ||   //  0 >>s V -> 0.
11319           C->isAllOnesValue())    // -1 >>s V -> -1.
11320         return N->getOperand(0);
11321     }
11322     break;
11323   case ISD::SIGN_EXTEND:
11324   case ISD::ZERO_EXTEND:
11325   case ISD::ANY_EXTEND:
11326     return DAGCombineExtBoolTrunc(N, DCI);
11327   case ISD::TRUNCATE:
11328   case ISD::SETCC:
11329   case ISD::SELECT_CC:
11330     return DAGCombineTruncBoolExt(N, DCI);
11331   case ISD::SINT_TO_FP:
11332   case ISD::UINT_TO_FP:
11333     return combineFPToIntToFP(N, DCI);
11334   case ISD::STORE: {
11335     EVT Op1VT = N->getOperand(1).getValueType();
11336     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11337       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11338 
11339     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11340     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11341         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11342         ValidTypeForStoreFltAsInt &&
11343         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11344       SDValue Val = N->getOperand(1).getOperand(0);
11345       if (Val.getValueType() == MVT::f32) {
11346         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11347         DCI.AddToWorklist(Val.getNode());
11348       }
11349       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11350       DCI.AddToWorklist(Val.getNode());
11351 
11352       if (Op1VT == MVT::i32) {
11353         SDValue Ops[] = {
11354           N->getOperand(0), Val, N->getOperand(2),
11355           DAG.getValueType(N->getOperand(1).getValueType())
11356         };
11357 
11358         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11359                 DAG.getVTList(MVT::Other), Ops,
11360                 cast<StoreSDNode>(N)->getMemoryVT(),
11361                 cast<StoreSDNode>(N)->getMemOperand());
11362       } else {
11363         unsigned WidthInBytes =
11364           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11365         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11366 
11367         SDValue Ops[] = {
11368           N->getOperand(0), Val, N->getOperand(2), WidthConst,
11369           DAG.getValueType(N->getOperand(1).getValueType())
11370         };
11371         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11372                                       DAG.getVTList(MVT::Other), Ops,
11373                                       cast<StoreSDNode>(N)->getMemoryVT(),
11374                                       cast<StoreSDNode>(N)->getMemOperand());
11375       }
11376 
11377       DCI.AddToWorklist(Val.getNode());
11378       return Val;
11379     }
11380 
11381     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11382     if (cast<StoreSDNode>(N)->isUnindexed() &&
11383         N->getOperand(1).getOpcode() == ISD::BSWAP &&
11384         N->getOperand(1).getNode()->hasOneUse() &&
11385         (N->getOperand(1).getValueType() == MVT::i32 ||
11386          N->getOperand(1).getValueType() == MVT::i16 ||
11387          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11388           N->getOperand(1).getValueType() == MVT::i64))) {
11389       SDValue BSwapOp = N->getOperand(1).getOperand(0);
11390       // Do an any-extend to 32-bits if this is a half-word input.
11391       if (BSwapOp.getValueType() == MVT::i16)
11392         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11393 
11394       // If the type of BSWAP operand is wider than stored memory width
11395       // it need to be shifted to the right side before STBRX.
11396       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11397       if (Op1VT.bitsGT(mVT)) {
11398         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11399         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11400                               DAG.getConstant(Shift, dl, MVT::i32));
11401         // Need to truncate if this is a bswap of i64 stored as i32/i16.
11402         if (Op1VT == MVT::i64)
11403           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11404       }
11405 
11406       SDValue Ops[] = {
11407         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11408       };
11409       return
11410         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11411                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11412                                 cast<StoreSDNode>(N)->getMemOperand());
11413     }
11414 
11415     // For little endian, VSX stores require generating xxswapd/lxvd2x.
11416     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11417     EVT VT = N->getOperand(1).getValueType();
11418     if (VT.isSimple()) {
11419       MVT StoreVT = VT.getSimpleVT();
11420       if (Subtarget.needsSwapsForVSXMemOps() &&
11421           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11422            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11423         return expandVSXStoreForLE(N, DCI);
11424     }
11425     break;
11426   }
11427   case ISD::LOAD: {
11428     LoadSDNode *LD = cast<LoadSDNode>(N);
11429     EVT VT = LD->getValueType(0);
11430 
11431     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11432     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11433     if (VT.isSimple()) {
11434       MVT LoadVT = VT.getSimpleVT();
11435       if (Subtarget.needsSwapsForVSXMemOps() &&
11436           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11437            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11438         return expandVSXLoadForLE(N, DCI);
11439     }
11440 
11441     // We sometimes end up with a 64-bit integer load, from which we extract
11442     // two single-precision floating-point numbers. This happens with
11443     // std::complex<float>, and other similar structures, because of the way we
11444     // canonicalize structure copies. However, if we lack direct moves,
11445     // then the final bitcasts from the extracted integer values to the
11446     // floating-point numbers turn into store/load pairs. Even with direct moves,
11447     // just loading the two floating-point numbers is likely better.
11448     auto ReplaceTwoFloatLoad = [&]() {
11449       if (VT != MVT::i64)
11450         return false;
11451 
11452       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11453           LD->isVolatile())
11454         return false;
11455 
11456       //  We're looking for a sequence like this:
11457       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11458       //      t16: i64 = srl t13, Constant:i32<32>
11459       //    t17: i32 = truncate t16
11460       //  t18: f32 = bitcast t17
11461       //    t19: i32 = truncate t13
11462       //  t20: f32 = bitcast t19
11463 
11464       if (!LD->hasNUsesOfValue(2, 0))
11465         return false;
11466 
11467       auto UI = LD->use_begin();
11468       while (UI.getUse().getResNo() != 0) ++UI;
11469       SDNode *Trunc = *UI++;
11470       while (UI.getUse().getResNo() != 0) ++UI;
11471       SDNode *RightShift = *UI;
11472       if (Trunc->getOpcode() != ISD::TRUNCATE)
11473         std::swap(Trunc, RightShift);
11474 
11475       if (Trunc->getOpcode() != ISD::TRUNCATE ||
11476           Trunc->getValueType(0) != MVT::i32 ||
11477           !Trunc->hasOneUse())
11478         return false;
11479       if (RightShift->getOpcode() != ISD::SRL ||
11480           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11481           RightShift->getConstantOperandVal(1) != 32 ||
11482           !RightShift->hasOneUse())
11483         return false;
11484 
11485       SDNode *Trunc2 = *RightShift->use_begin();
11486       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11487           Trunc2->getValueType(0) != MVT::i32 ||
11488           !Trunc2->hasOneUse())
11489         return false;
11490 
11491       SDNode *Bitcast = *Trunc->use_begin();
11492       SDNode *Bitcast2 = *Trunc2->use_begin();
11493 
11494       if (Bitcast->getOpcode() != ISD::BITCAST ||
11495           Bitcast->getValueType(0) != MVT::f32)
11496         return false;
11497       if (Bitcast2->getOpcode() != ISD::BITCAST ||
11498           Bitcast2->getValueType(0) != MVT::f32)
11499         return false;
11500 
11501       if (Subtarget.isLittleEndian())
11502         std::swap(Bitcast, Bitcast2);
11503 
11504       // Bitcast has the second float (in memory-layout order) and Bitcast2
11505       // has the first one.
11506 
11507       SDValue BasePtr = LD->getBasePtr();
11508       if (LD->isIndexed()) {
11509         assert(LD->getAddressingMode() == ISD::PRE_INC &&
11510                "Non-pre-inc AM on PPC?");
11511         BasePtr =
11512           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11513                       LD->getOffset());
11514       }
11515 
11516       auto MMOFlags =
11517           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11518       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11519                                       LD->getPointerInfo(), LD->getAlignment(),
11520                                       MMOFlags, LD->getAAInfo());
11521       SDValue AddPtr =
11522         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11523                     BasePtr, DAG.getIntPtrConstant(4, dl));
11524       SDValue FloatLoad2 = DAG.getLoad(
11525           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11526           LD->getPointerInfo().getWithOffset(4),
11527           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11528 
11529       if (LD->isIndexed()) {
11530         // Note that DAGCombine should re-form any pre-increment load(s) from
11531         // what is produced here if that makes sense.
11532         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11533       }
11534 
11535       DCI.CombineTo(Bitcast2, FloatLoad);
11536       DCI.CombineTo(Bitcast, FloatLoad2);
11537 
11538       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11539                                     SDValue(FloatLoad2.getNode(), 1));
11540       return true;
11541     };
11542 
11543     if (ReplaceTwoFloatLoad())
11544       return SDValue(N, 0);
11545 
11546     EVT MemVT = LD->getMemoryVT();
11547     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11548     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11549     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11550     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11551     if (LD->isUnindexed() && VT.isVector() &&
11552         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11553           // P8 and later hardware should just use LOAD.
11554           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11555                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11556          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11557           LD->getAlignment() >= ScalarABIAlignment)) &&
11558         LD->getAlignment() < ABIAlignment) {
11559       // This is a type-legal unaligned Altivec or QPX load.
11560       SDValue Chain = LD->getChain();
11561       SDValue Ptr = LD->getBasePtr();
11562       bool isLittleEndian = Subtarget.isLittleEndian();
11563 
11564       // This implements the loading of unaligned vectors as described in
11565       // the venerable Apple Velocity Engine overview. Specifically:
11566       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11567       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11568       //
11569       // The general idea is to expand a sequence of one or more unaligned
11570       // loads into an alignment-based permutation-control instruction (lvsl
11571       // or lvsr), a series of regular vector loads (which always truncate
11572       // their input address to an aligned address), and a series of
11573       // permutations.  The results of these permutations are the requested
11574       // loaded values.  The trick is that the last "extra" load is not taken
11575       // from the address you might suspect (sizeof(vector) bytes after the
11576       // last requested load), but rather sizeof(vector) - 1 bytes after the
11577       // last requested vector. The point of this is to avoid a page fault if
11578       // the base address happened to be aligned. This works because if the
11579       // base address is aligned, then adding less than a full vector length
11580       // will cause the last vector in the sequence to be (re)loaded.
11581       // Otherwise, the next vector will be fetched as you might suspect was
11582       // necessary.
11583 
11584       // We might be able to reuse the permutation generation from
11585       // a different base address offset from this one by an aligned amount.
11586       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11587       // optimization later.
11588       Intrinsic::ID Intr, IntrLD, IntrPerm;
11589       MVT PermCntlTy, PermTy, LDTy;
11590       if (Subtarget.hasAltivec()) {
11591         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
11592                                  Intrinsic::ppc_altivec_lvsl;
11593         IntrLD = Intrinsic::ppc_altivec_lvx;
11594         IntrPerm = Intrinsic::ppc_altivec_vperm;
11595         PermCntlTy = MVT::v16i8;
11596         PermTy = MVT::v4i32;
11597         LDTy = MVT::v4i32;
11598       } else {
11599         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11600                                        Intrinsic::ppc_qpx_qvlpcls;
11601         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11602                                        Intrinsic::ppc_qpx_qvlfs;
11603         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11604         PermCntlTy = MVT::v4f64;
11605         PermTy = MVT::v4f64;
11606         LDTy = MemVT.getSimpleVT();
11607       }
11608 
11609       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11610 
11611       // Create the new MMO for the new base load. It is like the original MMO,
11612       // but represents an area in memory almost twice the vector size centered
11613       // on the original address. If the address is unaligned, we might start
11614       // reading up to (sizeof(vector)-1) bytes below the address of the
11615       // original unaligned load.
11616       MachineFunction &MF = DAG.getMachineFunction();
11617       MachineMemOperand *BaseMMO =
11618         MF.getMachineMemOperand(LD->getMemOperand(),
11619                                 -(long)MemVT.getStoreSize()+1,
11620                                 2*MemVT.getStoreSize()-1);
11621 
11622       // Create the new base load.
11623       SDValue LDXIntID =
11624           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11625       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11626       SDValue BaseLoad =
11627         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11628                                 DAG.getVTList(PermTy, MVT::Other),
11629                                 BaseLoadOps, LDTy, BaseMMO);
11630 
11631       // Note that the value of IncOffset (which is provided to the next
11632       // load's pointer info offset value, and thus used to calculate the
11633       // alignment), and the value of IncValue (which is actually used to
11634       // increment the pointer value) are different! This is because we
11635       // require the next load to appear to be aligned, even though it
11636       // is actually offset from the base pointer by a lesser amount.
11637       int IncOffset = VT.getSizeInBits() / 8;
11638       int IncValue = IncOffset;
11639 
11640       // Walk (both up and down) the chain looking for another load at the real
11641       // (aligned) offset (the alignment of the other load does not matter in
11642       // this case). If found, then do not use the offset reduction trick, as
11643       // that will prevent the loads from being later combined (as they would
11644       // otherwise be duplicates).
11645       if (!findConsecutiveLoad(LD, DAG))
11646         --IncValue;
11647 
11648       SDValue Increment =
11649           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11650       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11651 
11652       MachineMemOperand *ExtraMMO =
11653         MF.getMachineMemOperand(LD->getMemOperand(),
11654                                 1, 2*MemVT.getStoreSize()-1);
11655       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11656       SDValue ExtraLoad =
11657         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11658                                 DAG.getVTList(PermTy, MVT::Other),
11659                                 ExtraLoadOps, LDTy, ExtraMMO);
11660 
11661       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11662         BaseLoad.getValue(1), ExtraLoad.getValue(1));
11663 
11664       // Because vperm has a big-endian bias, we must reverse the order
11665       // of the input vectors and complement the permute control vector
11666       // when generating little endian code.  We have already handled the
11667       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11668       // and ExtraLoad here.
11669       SDValue Perm;
11670       if (isLittleEndian)
11671         Perm = BuildIntrinsicOp(IntrPerm,
11672                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11673       else
11674         Perm = BuildIntrinsicOp(IntrPerm,
11675                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11676 
11677       if (VT != PermTy)
11678         Perm = Subtarget.hasAltivec() ?
11679                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11680                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11681                                DAG.getTargetConstant(1, dl, MVT::i64));
11682                                // second argument is 1 because this rounding
11683                                // is always exact.
11684 
11685       // The output of the permutation is our loaded result, the TokenFactor is
11686       // our new chain.
11687       DCI.CombineTo(N, Perm, TF);
11688       return SDValue(N, 0);
11689     }
11690     }
11691     break;
11692     case ISD::INTRINSIC_WO_CHAIN: {
11693       bool isLittleEndian = Subtarget.isLittleEndian();
11694       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11695       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11696                                            : Intrinsic::ppc_altivec_lvsl);
11697       if ((IID == Intr ||
11698            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11699            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11700         N->getOperand(1)->getOpcode() == ISD::ADD) {
11701         SDValue Add = N->getOperand(1);
11702 
11703         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11704                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11705 
11706         if (DAG.MaskedValueIsZero(Add->getOperand(1),
11707                                   APInt::getAllOnesValue(Bits /* alignment */)
11708                                       .zext(Add.getScalarValueSizeInBits()))) {
11709           SDNode *BasePtr = Add->getOperand(0).getNode();
11710           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11711                                     UE = BasePtr->use_end();
11712                UI != UE; ++UI) {
11713             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11714                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11715               // We've found another LVSL/LVSR, and this address is an aligned
11716               // multiple of that one. The results will be the same, so use the
11717               // one we've just found instead.
11718 
11719               return SDValue(*UI, 0);
11720             }
11721           }
11722         }
11723 
11724         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11725           SDNode *BasePtr = Add->getOperand(0).getNode();
11726           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11727                UE = BasePtr->use_end(); UI != UE; ++UI) {
11728             if (UI->getOpcode() == ISD::ADD &&
11729                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11730                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11731                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11732                 (1ULL << Bits) == 0) {
11733               SDNode *OtherAdd = *UI;
11734               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11735                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11736                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11737                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11738                   return SDValue(*VI, 0);
11739                 }
11740               }
11741             }
11742           }
11743         }
11744       }
11745     }
11746 
11747     break;
11748   case ISD::INTRINSIC_W_CHAIN:
11749     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11750     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11751     if (Subtarget.needsSwapsForVSXMemOps()) {
11752       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11753       default:
11754         break;
11755       case Intrinsic::ppc_vsx_lxvw4x:
11756       case Intrinsic::ppc_vsx_lxvd2x:
11757         return expandVSXLoadForLE(N, DCI);
11758       }
11759     }
11760     break;
11761   case ISD::INTRINSIC_VOID:
11762     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11763     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11764     if (Subtarget.needsSwapsForVSXMemOps()) {
11765       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11766       default:
11767         break;
11768       case Intrinsic::ppc_vsx_stxvw4x:
11769       case Intrinsic::ppc_vsx_stxvd2x:
11770         return expandVSXStoreForLE(N, DCI);
11771       }
11772     }
11773     break;
11774   case ISD::BSWAP:
11775     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11776     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11777         N->getOperand(0).hasOneUse() &&
11778         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11779          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11780           N->getValueType(0) == MVT::i64))) {
11781       SDValue Load = N->getOperand(0);
11782       LoadSDNode *LD = cast<LoadSDNode>(Load);
11783       // Create the byte-swapping load.
11784       SDValue Ops[] = {
11785         LD->getChain(),    // Chain
11786         LD->getBasePtr(),  // Ptr
11787         DAG.getValueType(N->getValueType(0)) // VT
11788       };
11789       SDValue BSLoad =
11790         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11791                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11792                                               MVT::i64 : MVT::i32, MVT::Other),
11793                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11794 
11795       // If this is an i16 load, insert the truncate.
11796       SDValue ResVal = BSLoad;
11797       if (N->getValueType(0) == MVT::i16)
11798         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11799 
11800       // First, combine the bswap away.  This makes the value produced by the
11801       // load dead.
11802       DCI.CombineTo(N, ResVal);
11803 
11804       // Next, combine the load away, we give it a bogus result value but a real
11805       // chain result.  The result value is dead because the bswap is dead.
11806       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11807 
11808       // Return N so it doesn't get rechecked!
11809       return SDValue(N, 0);
11810     }
11811     break;
11812   case PPCISD::VCMP:
11813     // If a VCMPo node already exists with exactly the same operands as this
11814     // node, use its result instead of this node (VCMPo computes both a CR6 and
11815     // a normal output).
11816     //
11817     if (!N->getOperand(0).hasOneUse() &&
11818         !N->getOperand(1).hasOneUse() &&
11819         !N->getOperand(2).hasOneUse()) {
11820 
11821       // Scan all of the users of the LHS, looking for VCMPo's that match.
11822       SDNode *VCMPoNode = nullptr;
11823 
11824       SDNode *LHSN = N->getOperand(0).getNode();
11825       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11826            UI != E; ++UI)
11827         if (UI->getOpcode() == PPCISD::VCMPo &&
11828             UI->getOperand(1) == N->getOperand(1) &&
11829             UI->getOperand(2) == N->getOperand(2) &&
11830             UI->getOperand(0) == N->getOperand(0)) {
11831           VCMPoNode = *UI;
11832           break;
11833         }
11834 
11835       // If there is no VCMPo node, or if the flag value has a single use, don't
11836       // transform this.
11837       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11838         break;
11839 
11840       // Look at the (necessarily single) use of the flag value.  If it has a
11841       // chain, this transformation is more complex.  Note that multiple things
11842       // could use the value result, which we should ignore.
11843       SDNode *FlagUser = nullptr;
11844       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11845            FlagUser == nullptr; ++UI) {
11846         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11847         SDNode *User = *UI;
11848         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11849           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11850             FlagUser = User;
11851             break;
11852           }
11853         }
11854       }
11855 
11856       // If the user is a MFOCRF instruction, we know this is safe.
11857       // Otherwise we give up for right now.
11858       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11859         return SDValue(VCMPoNode, 0);
11860     }
11861     break;
11862   case ISD::BRCOND: {
11863     SDValue Cond = N->getOperand(1);
11864     SDValue Target = N->getOperand(2);
11865 
11866     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11867         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11868           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11869 
11870       // We now need to make the intrinsic dead (it cannot be instruction
11871       // selected).
11872       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11873       assert(Cond.getNode()->hasOneUse() &&
11874              "Counter decrement has more than one use");
11875 
11876       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11877                          N->getOperand(0), Target);
11878     }
11879   }
11880   break;
11881   case ISD::BR_CC: {
11882     // If this is a branch on an altivec predicate comparison, lower this so
11883     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11884     // lowering is done pre-legalize, because the legalizer lowers the predicate
11885     // compare down to code that is difficult to reassemble.
11886     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11887     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11888 
11889     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11890     // value. If so, pass-through the AND to get to the intrinsic.
11891     if (LHS.getOpcode() == ISD::AND &&
11892         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11893         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11894           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11895         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11896         !isNullConstant(LHS.getOperand(1)))
11897       LHS = LHS.getOperand(0);
11898 
11899     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11900         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11901           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11902         isa<ConstantSDNode>(RHS)) {
11903       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11904              "Counter decrement comparison is not EQ or NE");
11905 
11906       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11907       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11908                     (CC == ISD::SETNE && !Val);
11909 
11910       // We now need to make the intrinsic dead (it cannot be instruction
11911       // selected).
11912       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11913       assert(LHS.getNode()->hasOneUse() &&
11914              "Counter decrement has more than one use");
11915 
11916       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11917                          N->getOperand(0), N->getOperand(4));
11918     }
11919 
11920     int CompareOpc;
11921     bool isDot;
11922 
11923     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11924         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11925         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11926       assert(isDot && "Can't compare against a vector result!");
11927 
11928       // If this is a comparison against something other than 0/1, then we know
11929       // that the condition is never/always true.
11930       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11931       if (Val != 0 && Val != 1) {
11932         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11933           return N->getOperand(0);
11934         // Always !=, turn it into an unconditional branch.
11935         return DAG.getNode(ISD::BR, dl, MVT::Other,
11936                            N->getOperand(0), N->getOperand(4));
11937       }
11938 
11939       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11940 
11941       // Create the PPCISD altivec 'dot' comparison node.
11942       SDValue Ops[] = {
11943         LHS.getOperand(2),  // LHS of compare
11944         LHS.getOperand(3),  // RHS of compare
11945         DAG.getConstant(CompareOpc, dl, MVT::i32)
11946       };
11947       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11948       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11949 
11950       // Unpack the result based on how the target uses it.
11951       PPC::Predicate CompOpc;
11952       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11953       default:  // Can't happen, don't crash on invalid number though.
11954       case 0:   // Branch on the value of the EQ bit of CR6.
11955         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11956         break;
11957       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11958         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11959         break;
11960       case 2:   // Branch on the value of the LT bit of CR6.
11961         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11962         break;
11963       case 3:   // Branch on the inverted value of the LT bit of CR6.
11964         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11965         break;
11966       }
11967 
11968       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11969                          DAG.getConstant(CompOpc, dl, MVT::i32),
11970                          DAG.getRegister(PPC::CR6, MVT::i32),
11971                          N->getOperand(4), CompNode.getValue(1));
11972     }
11973     break;
11974   }
11975   case ISD::BUILD_VECTOR:
11976     return DAGCombineBuildVector(N, DCI);
11977   }
11978 
11979   return SDValue();
11980 }
11981 
11982 SDValue
11983 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11984                                   SelectionDAG &DAG,
11985                                   std::vector<SDNode *> *Created) const {
11986   // fold (sdiv X, pow2)
11987   EVT VT = N->getValueType(0);
11988   if (VT == MVT::i64 && !Subtarget.isPPC64())
11989     return SDValue();
11990   if ((VT != MVT::i32 && VT != MVT::i64) ||
11991       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11992     return SDValue();
11993 
11994   SDLoc DL(N);
11995   SDValue N0 = N->getOperand(0);
11996 
11997   bool IsNegPow2 = (-Divisor).isPowerOf2();
11998   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11999   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12000 
12001   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12002   if (Created)
12003     Created->push_back(Op.getNode());
12004 
12005   if (IsNegPow2) {
12006     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12007     if (Created)
12008       Created->push_back(Op.getNode());
12009   }
12010 
12011   return Op;
12012 }
12013 
12014 //===----------------------------------------------------------------------===//
12015 // Inline Assembly Support
12016 //===----------------------------------------------------------------------===//
12017 
12018 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12019                                                       APInt &KnownZero,
12020                                                       APInt &KnownOne,
12021                                                       const SelectionDAG &DAG,
12022                                                       unsigned Depth) const {
12023   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
12024   switch (Op.getOpcode()) {
12025   default: break;
12026   case PPCISD::LBRX: {
12027     // lhbrx is known to have the top bits cleared out.
12028     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12029       KnownZero = 0xFFFF0000;
12030     break;
12031   }
12032   case ISD::INTRINSIC_WO_CHAIN: {
12033     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12034     default: break;
12035     case Intrinsic::ppc_altivec_vcmpbfp_p:
12036     case Intrinsic::ppc_altivec_vcmpeqfp_p:
12037     case Intrinsic::ppc_altivec_vcmpequb_p:
12038     case Intrinsic::ppc_altivec_vcmpequh_p:
12039     case Intrinsic::ppc_altivec_vcmpequw_p:
12040     case Intrinsic::ppc_altivec_vcmpequd_p:
12041     case Intrinsic::ppc_altivec_vcmpgefp_p:
12042     case Intrinsic::ppc_altivec_vcmpgtfp_p:
12043     case Intrinsic::ppc_altivec_vcmpgtsb_p:
12044     case Intrinsic::ppc_altivec_vcmpgtsh_p:
12045     case Intrinsic::ppc_altivec_vcmpgtsw_p:
12046     case Intrinsic::ppc_altivec_vcmpgtsd_p:
12047     case Intrinsic::ppc_altivec_vcmpgtub_p:
12048     case Intrinsic::ppc_altivec_vcmpgtuh_p:
12049     case Intrinsic::ppc_altivec_vcmpgtuw_p:
12050     case Intrinsic::ppc_altivec_vcmpgtud_p:
12051       KnownZero = ~1U;  // All bits but the low one are known to be zero.
12052       break;
12053     }
12054   }
12055   }
12056 }
12057 
12058 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12059   switch (Subtarget.getDarwinDirective()) {
12060   default: break;
12061   case PPC::DIR_970:
12062   case PPC::DIR_PWR4:
12063   case PPC::DIR_PWR5:
12064   case PPC::DIR_PWR5X:
12065   case PPC::DIR_PWR6:
12066   case PPC::DIR_PWR6X:
12067   case PPC::DIR_PWR7:
12068   case PPC::DIR_PWR8:
12069   case PPC::DIR_PWR9: {
12070     if (!ML)
12071       break;
12072 
12073     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12074 
12075     // For small loops (between 5 and 8 instructions), align to a 32-byte
12076     // boundary so that the entire loop fits in one instruction-cache line.
12077     uint64_t LoopSize = 0;
12078     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12079       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12080         LoopSize += TII->getInstSizeInBytes(*J);
12081         if (LoopSize > 32)
12082           break;
12083       }
12084 
12085     if (LoopSize > 16 && LoopSize <= 32)
12086       return 5;
12087 
12088     break;
12089   }
12090   }
12091 
12092   return TargetLowering::getPrefLoopAlignment(ML);
12093 }
12094 
12095 /// getConstraintType - Given a constraint, return the type of
12096 /// constraint it is for this target.
12097 PPCTargetLowering::ConstraintType
12098 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12099   if (Constraint.size() == 1) {
12100     switch (Constraint[0]) {
12101     default: break;
12102     case 'b':
12103     case 'r':
12104     case 'f':
12105     case 'd':
12106     case 'v':
12107     case 'y':
12108       return C_RegisterClass;
12109     case 'Z':
12110       // FIXME: While Z does indicate a memory constraint, it specifically
12111       // indicates an r+r address (used in conjunction with the 'y' modifier
12112       // in the replacement string). Currently, we're forcing the base
12113       // register to be r0 in the asm printer (which is interpreted as zero)
12114       // and forming the complete address in the second register. This is
12115       // suboptimal.
12116       return C_Memory;
12117     }
12118   } else if (Constraint == "wc") { // individual CR bits.
12119     return C_RegisterClass;
12120   } else if (Constraint == "wa" || Constraint == "wd" ||
12121              Constraint == "wf" || Constraint == "ws") {
12122     return C_RegisterClass; // VSX registers.
12123   }
12124   return TargetLowering::getConstraintType(Constraint);
12125 }
12126 
12127 /// Examine constraint type and operand type and determine a weight value.
12128 /// This object must already have been set up with the operand type
12129 /// and the current alternative constraint selected.
12130 TargetLowering::ConstraintWeight
12131 PPCTargetLowering::getSingleConstraintMatchWeight(
12132     AsmOperandInfo &info, const char *constraint) const {
12133   ConstraintWeight weight = CW_Invalid;
12134   Value *CallOperandVal = info.CallOperandVal;
12135     // If we don't have a value, we can't do a match,
12136     // but allow it at the lowest weight.
12137   if (!CallOperandVal)
12138     return CW_Default;
12139   Type *type = CallOperandVal->getType();
12140 
12141   // Look at the constraint type.
12142   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12143     return CW_Register; // an individual CR bit.
12144   else if ((StringRef(constraint) == "wa" ||
12145             StringRef(constraint) == "wd" ||
12146             StringRef(constraint) == "wf") &&
12147            type->isVectorTy())
12148     return CW_Register;
12149   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12150     return CW_Register;
12151 
12152   switch (*constraint) {
12153   default:
12154     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12155     break;
12156   case 'b':
12157     if (type->isIntegerTy())
12158       weight = CW_Register;
12159     break;
12160   case 'f':
12161     if (type->isFloatTy())
12162       weight = CW_Register;
12163     break;
12164   case 'd':
12165     if (type->isDoubleTy())
12166       weight = CW_Register;
12167     break;
12168   case 'v':
12169     if (type->isVectorTy())
12170       weight = CW_Register;
12171     break;
12172   case 'y':
12173     weight = CW_Register;
12174     break;
12175   case 'Z':
12176     weight = CW_Memory;
12177     break;
12178   }
12179   return weight;
12180 }
12181 
12182 std::pair<unsigned, const TargetRegisterClass *>
12183 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12184                                                 StringRef Constraint,
12185                                                 MVT VT) const {
12186   if (Constraint.size() == 1) {
12187     // GCC RS6000 Constraint Letters
12188     switch (Constraint[0]) {
12189     case 'b':   // R1-R31
12190       if (VT == MVT::i64 && Subtarget.isPPC64())
12191         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12192       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12193     case 'r':   // R0-R31
12194       if (VT == MVT::i64 && Subtarget.isPPC64())
12195         return std::make_pair(0U, &PPC::G8RCRegClass);
12196       return std::make_pair(0U, &PPC::GPRCRegClass);
12197     // 'd' and 'f' constraints are both defined to be "the floating point
12198     // registers", where one is for 32-bit and the other for 64-bit. We don't
12199     // really care overly much here so just give them all the same reg classes.
12200     case 'd':
12201     case 'f':
12202       if (VT == MVT::f32 || VT == MVT::i32)
12203         return std::make_pair(0U, &PPC::F4RCRegClass);
12204       if (VT == MVT::f64 || VT == MVT::i64)
12205         return std::make_pair(0U, &PPC::F8RCRegClass);
12206       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12207         return std::make_pair(0U, &PPC::QFRCRegClass);
12208       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12209         return std::make_pair(0U, &PPC::QSRCRegClass);
12210       break;
12211     case 'v':
12212       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12213         return std::make_pair(0U, &PPC::QFRCRegClass);
12214       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12215         return std::make_pair(0U, &PPC::QSRCRegClass);
12216       if (Subtarget.hasAltivec())
12217         return std::make_pair(0U, &PPC::VRRCRegClass);
12218     case 'y':   // crrc
12219       return std::make_pair(0U, &PPC::CRRCRegClass);
12220     }
12221   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12222     // An individual CR bit.
12223     return std::make_pair(0U, &PPC::CRBITRCRegClass);
12224   } else if ((Constraint == "wa" || Constraint == "wd" ||
12225              Constraint == "wf") && Subtarget.hasVSX()) {
12226     return std::make_pair(0U, &PPC::VSRCRegClass);
12227   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12228     if (VT == MVT::f32 && Subtarget.hasP8Vector())
12229       return std::make_pair(0U, &PPC::VSSRCRegClass);
12230     else
12231       return std::make_pair(0U, &PPC::VSFRCRegClass);
12232   }
12233 
12234   std::pair<unsigned, const TargetRegisterClass *> R =
12235       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12236 
12237   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12238   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12239   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12240   // register.
12241   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12242   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12243   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12244       PPC::GPRCRegClass.contains(R.first))
12245     return std::make_pair(TRI->getMatchingSuperReg(R.first,
12246                             PPC::sub_32, &PPC::G8RCRegClass),
12247                           &PPC::G8RCRegClass);
12248 
12249   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12250   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12251     R.first = PPC::CR0;
12252     R.second = &PPC::CRRCRegClass;
12253   }
12254 
12255   return R;
12256 }
12257 
12258 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12259 /// vector.  If it is invalid, don't add anything to Ops.
12260 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12261                                                      std::string &Constraint,
12262                                                      std::vector<SDValue>&Ops,
12263                                                      SelectionDAG &DAG) const {
12264   SDValue Result;
12265 
12266   // Only support length 1 constraints.
12267   if (Constraint.length() > 1) return;
12268 
12269   char Letter = Constraint[0];
12270   switch (Letter) {
12271   default: break;
12272   case 'I':
12273   case 'J':
12274   case 'K':
12275   case 'L':
12276   case 'M':
12277   case 'N':
12278   case 'O':
12279   case 'P': {
12280     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12281     if (!CST) return; // Must be an immediate to match.
12282     SDLoc dl(Op);
12283     int64_t Value = CST->getSExtValue();
12284     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12285                          // numbers are printed as such.
12286     switch (Letter) {
12287     default: llvm_unreachable("Unknown constraint letter!");
12288     case 'I':  // "I" is a signed 16-bit constant.
12289       if (isInt<16>(Value))
12290         Result = DAG.getTargetConstant(Value, dl, TCVT);
12291       break;
12292     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
12293       if (isShiftedUInt<16, 16>(Value))
12294         Result = DAG.getTargetConstant(Value, dl, TCVT);
12295       break;
12296     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
12297       if (isShiftedInt<16, 16>(Value))
12298         Result = DAG.getTargetConstant(Value, dl, TCVT);
12299       break;
12300     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
12301       if (isUInt<16>(Value))
12302         Result = DAG.getTargetConstant(Value, dl, TCVT);
12303       break;
12304     case 'M':  // "M" is a constant that is greater than 31.
12305       if (Value > 31)
12306         Result = DAG.getTargetConstant(Value, dl, TCVT);
12307       break;
12308     case 'N':  // "N" is a positive constant that is an exact power of two.
12309       if (Value > 0 && isPowerOf2_64(Value))
12310         Result = DAG.getTargetConstant(Value, dl, TCVT);
12311       break;
12312     case 'O':  // "O" is the constant zero.
12313       if (Value == 0)
12314         Result = DAG.getTargetConstant(Value, dl, TCVT);
12315       break;
12316     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
12317       if (isInt<16>(-Value))
12318         Result = DAG.getTargetConstant(Value, dl, TCVT);
12319       break;
12320     }
12321     break;
12322   }
12323   }
12324 
12325   if (Result.getNode()) {
12326     Ops.push_back(Result);
12327     return;
12328   }
12329 
12330   // Handle standard constraint letters.
12331   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12332 }
12333 
12334 // isLegalAddressingMode - Return true if the addressing mode represented
12335 // by AM is legal for this target, for a load/store of the specified type.
12336 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12337                                               const AddrMode &AM, Type *Ty,
12338                                               unsigned AS) const {
12339   // PPC does not allow r+i addressing modes for vectors!
12340   if (Ty->isVectorTy() && AM.BaseOffs != 0)
12341     return false;
12342 
12343   // PPC allows a sign-extended 16-bit immediate field.
12344   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12345     return false;
12346 
12347   // No global is ever allowed as a base.
12348   if (AM.BaseGV)
12349     return false;
12350 
12351   // PPC only support r+r,
12352   switch (AM.Scale) {
12353   case 0:  // "r+i" or just "i", depending on HasBaseReg.
12354     break;
12355   case 1:
12356     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
12357       return false;
12358     // Otherwise we have r+r or r+i.
12359     break;
12360   case 2:
12361     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
12362       return false;
12363     // Allow 2*r as r+r.
12364     break;
12365   default:
12366     // No other scales are supported.
12367     return false;
12368   }
12369 
12370   return true;
12371 }
12372 
12373 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12374                                            SelectionDAG &DAG) const {
12375   MachineFunction &MF = DAG.getMachineFunction();
12376   MachineFrameInfo &MFI = MF.getFrameInfo();
12377   MFI.setReturnAddressIsTaken(true);
12378 
12379   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12380     return SDValue();
12381 
12382   SDLoc dl(Op);
12383   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12384 
12385   // Make sure the function does not optimize away the store of the RA to
12386   // the stack.
12387   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12388   FuncInfo->setLRStoreRequired();
12389   bool isPPC64 = Subtarget.isPPC64();
12390   auto PtrVT = getPointerTy(MF.getDataLayout());
12391 
12392   if (Depth > 0) {
12393     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12394     SDValue Offset =
12395         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12396                         isPPC64 ? MVT::i64 : MVT::i32);
12397     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12398                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12399                        MachinePointerInfo());
12400   }
12401 
12402   // Just load the return address off the stack.
12403   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12404   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12405                      MachinePointerInfo());
12406 }
12407 
12408 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12409                                           SelectionDAG &DAG) const {
12410   SDLoc dl(Op);
12411   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12412 
12413   MachineFunction &MF = DAG.getMachineFunction();
12414   MachineFrameInfo &MFI = MF.getFrameInfo();
12415   MFI.setFrameAddressIsTaken(true);
12416 
12417   EVT PtrVT = getPointerTy(MF.getDataLayout());
12418   bool isPPC64 = PtrVT == MVT::i64;
12419 
12420   // Naked functions never have a frame pointer, and so we use r1. For all
12421   // other functions, this decision must be delayed until during PEI.
12422   unsigned FrameReg;
12423   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12424     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12425   else
12426     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12427 
12428   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12429                                          PtrVT);
12430   while (Depth--)
12431     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12432                             FrameAddr, MachinePointerInfo());
12433   return FrameAddr;
12434 }
12435 
12436 // FIXME? Maybe this could be a TableGen attribute on some registers and
12437 // this table could be generated automatically from RegInfo.
12438 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12439                                               SelectionDAG &DAG) const {
12440   bool isPPC64 = Subtarget.isPPC64();
12441   bool isDarwinABI = Subtarget.isDarwinABI();
12442 
12443   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12444       (!isPPC64 && VT != MVT::i32))
12445     report_fatal_error("Invalid register global variable type");
12446 
12447   bool is64Bit = isPPC64 && VT == MVT::i64;
12448   unsigned Reg = StringSwitch<unsigned>(RegName)
12449                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12450                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12451                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12452                                   (is64Bit ? PPC::X13 : PPC::R13))
12453                    .Default(0);
12454 
12455   if (Reg)
12456     return Reg;
12457   report_fatal_error("Invalid register name global variable");
12458 }
12459 
12460 bool
12461 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12462   // The PowerPC target isn't yet aware of offsets.
12463   return false;
12464 }
12465 
12466 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12467                                            const CallInst &I,
12468                                            unsigned Intrinsic) const {
12469   switch (Intrinsic) {
12470   case Intrinsic::ppc_qpx_qvlfd:
12471   case Intrinsic::ppc_qpx_qvlfs:
12472   case Intrinsic::ppc_qpx_qvlfcd:
12473   case Intrinsic::ppc_qpx_qvlfcs:
12474   case Intrinsic::ppc_qpx_qvlfiwa:
12475   case Intrinsic::ppc_qpx_qvlfiwz:
12476   case Intrinsic::ppc_altivec_lvx:
12477   case Intrinsic::ppc_altivec_lvxl:
12478   case Intrinsic::ppc_altivec_lvebx:
12479   case Intrinsic::ppc_altivec_lvehx:
12480   case Intrinsic::ppc_altivec_lvewx:
12481   case Intrinsic::ppc_vsx_lxvd2x:
12482   case Intrinsic::ppc_vsx_lxvw4x: {
12483     EVT VT;
12484     switch (Intrinsic) {
12485     case Intrinsic::ppc_altivec_lvebx:
12486       VT = MVT::i8;
12487       break;
12488     case Intrinsic::ppc_altivec_lvehx:
12489       VT = MVT::i16;
12490       break;
12491     case Intrinsic::ppc_altivec_lvewx:
12492       VT = MVT::i32;
12493       break;
12494     case Intrinsic::ppc_vsx_lxvd2x:
12495       VT = MVT::v2f64;
12496       break;
12497     case Intrinsic::ppc_qpx_qvlfd:
12498       VT = MVT::v4f64;
12499       break;
12500     case Intrinsic::ppc_qpx_qvlfs:
12501       VT = MVT::v4f32;
12502       break;
12503     case Intrinsic::ppc_qpx_qvlfcd:
12504       VT = MVT::v2f64;
12505       break;
12506     case Intrinsic::ppc_qpx_qvlfcs:
12507       VT = MVT::v2f32;
12508       break;
12509     default:
12510       VT = MVT::v4i32;
12511       break;
12512     }
12513 
12514     Info.opc = ISD::INTRINSIC_W_CHAIN;
12515     Info.memVT = VT;
12516     Info.ptrVal = I.getArgOperand(0);
12517     Info.offset = -VT.getStoreSize()+1;
12518     Info.size = 2*VT.getStoreSize()-1;
12519     Info.align = 1;
12520     Info.vol = false;
12521     Info.readMem = true;
12522     Info.writeMem = false;
12523     return true;
12524   }
12525   case Intrinsic::ppc_qpx_qvlfda:
12526   case Intrinsic::ppc_qpx_qvlfsa:
12527   case Intrinsic::ppc_qpx_qvlfcda:
12528   case Intrinsic::ppc_qpx_qvlfcsa:
12529   case Intrinsic::ppc_qpx_qvlfiwaa:
12530   case Intrinsic::ppc_qpx_qvlfiwza: {
12531     EVT VT;
12532     switch (Intrinsic) {
12533     case Intrinsic::ppc_qpx_qvlfda:
12534       VT = MVT::v4f64;
12535       break;
12536     case Intrinsic::ppc_qpx_qvlfsa:
12537       VT = MVT::v4f32;
12538       break;
12539     case Intrinsic::ppc_qpx_qvlfcda:
12540       VT = MVT::v2f64;
12541       break;
12542     case Intrinsic::ppc_qpx_qvlfcsa:
12543       VT = MVT::v2f32;
12544       break;
12545     default:
12546       VT = MVT::v4i32;
12547       break;
12548     }
12549 
12550     Info.opc = ISD::INTRINSIC_W_CHAIN;
12551     Info.memVT = VT;
12552     Info.ptrVal = I.getArgOperand(0);
12553     Info.offset = 0;
12554     Info.size = VT.getStoreSize();
12555     Info.align = 1;
12556     Info.vol = false;
12557     Info.readMem = true;
12558     Info.writeMem = false;
12559     return true;
12560   }
12561   case Intrinsic::ppc_qpx_qvstfd:
12562   case Intrinsic::ppc_qpx_qvstfs:
12563   case Intrinsic::ppc_qpx_qvstfcd:
12564   case Intrinsic::ppc_qpx_qvstfcs:
12565   case Intrinsic::ppc_qpx_qvstfiw:
12566   case Intrinsic::ppc_altivec_stvx:
12567   case Intrinsic::ppc_altivec_stvxl:
12568   case Intrinsic::ppc_altivec_stvebx:
12569   case Intrinsic::ppc_altivec_stvehx:
12570   case Intrinsic::ppc_altivec_stvewx:
12571   case Intrinsic::ppc_vsx_stxvd2x:
12572   case Intrinsic::ppc_vsx_stxvw4x: {
12573     EVT VT;
12574     switch (Intrinsic) {
12575     case Intrinsic::ppc_altivec_stvebx:
12576       VT = MVT::i8;
12577       break;
12578     case Intrinsic::ppc_altivec_stvehx:
12579       VT = MVT::i16;
12580       break;
12581     case Intrinsic::ppc_altivec_stvewx:
12582       VT = MVT::i32;
12583       break;
12584     case Intrinsic::ppc_vsx_stxvd2x:
12585       VT = MVT::v2f64;
12586       break;
12587     case Intrinsic::ppc_qpx_qvstfd:
12588       VT = MVT::v4f64;
12589       break;
12590     case Intrinsic::ppc_qpx_qvstfs:
12591       VT = MVT::v4f32;
12592       break;
12593     case Intrinsic::ppc_qpx_qvstfcd:
12594       VT = MVT::v2f64;
12595       break;
12596     case Intrinsic::ppc_qpx_qvstfcs:
12597       VT = MVT::v2f32;
12598       break;
12599     default:
12600       VT = MVT::v4i32;
12601       break;
12602     }
12603 
12604     Info.opc = ISD::INTRINSIC_VOID;
12605     Info.memVT = VT;
12606     Info.ptrVal = I.getArgOperand(1);
12607     Info.offset = -VT.getStoreSize()+1;
12608     Info.size = 2*VT.getStoreSize()-1;
12609     Info.align = 1;
12610     Info.vol = false;
12611     Info.readMem = false;
12612     Info.writeMem = true;
12613     return true;
12614   }
12615   case Intrinsic::ppc_qpx_qvstfda:
12616   case Intrinsic::ppc_qpx_qvstfsa:
12617   case Intrinsic::ppc_qpx_qvstfcda:
12618   case Intrinsic::ppc_qpx_qvstfcsa:
12619   case Intrinsic::ppc_qpx_qvstfiwa: {
12620     EVT VT;
12621     switch (Intrinsic) {
12622     case Intrinsic::ppc_qpx_qvstfda:
12623       VT = MVT::v4f64;
12624       break;
12625     case Intrinsic::ppc_qpx_qvstfsa:
12626       VT = MVT::v4f32;
12627       break;
12628     case Intrinsic::ppc_qpx_qvstfcda:
12629       VT = MVT::v2f64;
12630       break;
12631     case Intrinsic::ppc_qpx_qvstfcsa:
12632       VT = MVT::v2f32;
12633       break;
12634     default:
12635       VT = MVT::v4i32;
12636       break;
12637     }
12638 
12639     Info.opc = ISD::INTRINSIC_VOID;
12640     Info.memVT = VT;
12641     Info.ptrVal = I.getArgOperand(1);
12642     Info.offset = 0;
12643     Info.size = VT.getStoreSize();
12644     Info.align = 1;
12645     Info.vol = false;
12646     Info.readMem = false;
12647     Info.writeMem = true;
12648     return true;
12649   }
12650   default:
12651     break;
12652   }
12653 
12654   return false;
12655 }
12656 
12657 /// getOptimalMemOpType - Returns the target specific optimal type for load
12658 /// and store operations as a result of memset, memcpy, and memmove
12659 /// lowering. If DstAlign is zero that means it's safe to destination
12660 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12661 /// means there isn't a need to check it against alignment requirement,
12662 /// probably because the source does not need to be loaded. If 'IsMemset' is
12663 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12664 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12665 /// source is constant so it does not need to be loaded.
12666 /// It returns EVT::Other if the type should be determined using generic
12667 /// target-independent logic.
12668 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12669                                            unsigned DstAlign, unsigned SrcAlign,
12670                                            bool IsMemset, bool ZeroMemset,
12671                                            bool MemcpyStrSrc,
12672                                            MachineFunction &MF) const {
12673   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12674     const Function *F = MF.getFunction();
12675     // When expanding a memset, require at least two QPX instructions to cover
12676     // the cost of loading the value to be stored from the constant pool.
12677     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12678        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12679         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12680       return MVT::v4f64;
12681     }
12682 
12683     // We should use Altivec/VSX loads and stores when available. For unaligned
12684     // addresses, unaligned VSX loads are only fast starting with the P8.
12685     if (Subtarget.hasAltivec() && Size >= 16 &&
12686         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12687          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12688       return MVT::v4i32;
12689   }
12690 
12691   if (Subtarget.isPPC64()) {
12692     return MVT::i64;
12693   }
12694 
12695   return MVT::i32;
12696 }
12697 
12698 /// \brief Returns true if it is beneficial to convert a load of a constant
12699 /// to just the constant itself.
12700 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12701                                                           Type *Ty) const {
12702   assert(Ty->isIntegerTy());
12703 
12704   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12705   return !(BitSize == 0 || BitSize > 64);
12706 }
12707 
12708 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12709   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12710     return false;
12711   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12712   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12713   return NumBits1 == 64 && NumBits2 == 32;
12714 }
12715 
12716 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12717   if (!VT1.isInteger() || !VT2.isInteger())
12718     return false;
12719   unsigned NumBits1 = VT1.getSizeInBits();
12720   unsigned NumBits2 = VT2.getSizeInBits();
12721   return NumBits1 == 64 && NumBits2 == 32;
12722 }
12723 
12724 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12725   // Generally speaking, zexts are not free, but they are free when they can be
12726   // folded with other operations.
12727   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12728     EVT MemVT = LD->getMemoryVT();
12729     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12730          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12731         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12732          LD->getExtensionType() == ISD::ZEXTLOAD))
12733       return true;
12734   }
12735 
12736   // FIXME: Add other cases...
12737   //  - 32-bit shifts with a zext to i64
12738   //  - zext after ctlz, bswap, etc.
12739   //  - zext after and by a constant mask
12740 
12741   return TargetLowering::isZExtFree(Val, VT2);
12742 }
12743 
12744 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12745   assert(VT.isFloatingPoint());
12746   return true;
12747 }
12748 
12749 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12750   return isInt<16>(Imm) || isUInt<16>(Imm);
12751 }
12752 
12753 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12754   return isInt<16>(Imm) || isUInt<16>(Imm);
12755 }
12756 
12757 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12758                                                        unsigned,
12759                                                        unsigned,
12760                                                        bool *Fast) const {
12761   if (DisablePPCUnaligned)
12762     return false;
12763 
12764   // PowerPC supports unaligned memory access for simple non-vector types.
12765   // Although accessing unaligned addresses is not as efficient as accessing
12766   // aligned addresses, it is generally more efficient than manual expansion,
12767   // and generally only traps for software emulation when crossing page
12768   // boundaries.
12769 
12770   if (!VT.isSimple())
12771     return false;
12772 
12773   if (VT.getSimpleVT().isVector()) {
12774     if (Subtarget.hasVSX()) {
12775       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12776           VT != MVT::v4f32 && VT != MVT::v4i32)
12777         return false;
12778     } else {
12779       return false;
12780     }
12781   }
12782 
12783   if (VT == MVT::ppcf128)
12784     return false;
12785 
12786   if (Fast)
12787     *Fast = true;
12788 
12789   return true;
12790 }
12791 
12792 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12793   VT = VT.getScalarType();
12794 
12795   if (!VT.isSimple())
12796     return false;
12797 
12798   switch (VT.getSimpleVT().SimpleTy) {
12799   case MVT::f32:
12800   case MVT::f64:
12801     return true;
12802   default:
12803     break;
12804   }
12805 
12806   return false;
12807 }
12808 
12809 const MCPhysReg *
12810 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12811   // LR is a callee-save register, but we must treat it as clobbered by any call
12812   // site. Hence we include LR in the scratch registers, which are in turn added
12813   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12814   // to CTR, which is used by any indirect call.
12815   static const MCPhysReg ScratchRegs[] = {
12816     PPC::X12, PPC::LR8, PPC::CTR8, 0
12817   };
12818 
12819   return ScratchRegs;
12820 }
12821 
12822 unsigned PPCTargetLowering::getExceptionPointerRegister(
12823     const Constant *PersonalityFn) const {
12824   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12825 }
12826 
12827 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12828     const Constant *PersonalityFn) const {
12829   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12830 }
12831 
12832 bool
12833 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12834                      EVT VT , unsigned DefinedValues) const {
12835   if (VT == MVT::v2i64)
12836     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12837 
12838   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12839     return true;
12840 
12841   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12842 }
12843 
12844 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12845   if (DisableILPPref || Subtarget.enableMachineScheduler())
12846     return TargetLowering::getSchedulingPreference(N);
12847 
12848   return Sched::ILP;
12849 }
12850 
12851 // Create a fast isel object.
12852 FastISel *
12853 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12854                                   const TargetLibraryInfo *LibInfo) const {
12855   return PPC::createFastISel(FuncInfo, LibInfo);
12856 }
12857 
12858 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12859   if (Subtarget.isDarwinABI()) return;
12860   if (!Subtarget.isPPC64()) return;
12861 
12862   // Update IsSplitCSR in PPCFunctionInfo
12863   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12864   PFI->setIsSplitCSR(true);
12865 }
12866 
12867 void PPCTargetLowering::insertCopiesSplitCSR(
12868   MachineBasicBlock *Entry,
12869   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12870   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12871   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12872   if (!IStart)
12873     return;
12874 
12875   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12876   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12877   MachineBasicBlock::iterator MBBI = Entry->begin();
12878   for (const MCPhysReg *I = IStart; *I; ++I) {
12879     const TargetRegisterClass *RC = nullptr;
12880     if (PPC::G8RCRegClass.contains(*I))
12881       RC = &PPC::G8RCRegClass;
12882     else if (PPC::F8RCRegClass.contains(*I))
12883       RC = &PPC::F8RCRegClass;
12884     else if (PPC::CRRCRegClass.contains(*I))
12885       RC = &PPC::CRRCRegClass;
12886     else if (PPC::VRRCRegClass.contains(*I))
12887       RC = &PPC::VRRCRegClass;
12888     else
12889       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12890 
12891     unsigned NewVR = MRI->createVirtualRegister(RC);
12892     // Create copy from CSR to a virtual register.
12893     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12894     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12895     // nounwind. If we want to generalize this later, we may need to emit
12896     // CFI pseudo-instructions.
12897     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12898              Attribute::NoUnwind) &&
12899            "Function should be nounwind in insertCopiesSplitCSR!");
12900     Entry->addLiveIn(*I);
12901     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12902       .addReg(*I);
12903 
12904     // Insert the copy-back instructions right before the terminator
12905     for (auto *Exit : Exits)
12906       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12907               TII->get(TargetOpcode::COPY), *I)
12908         .addReg(NewVR);
12909   }
12910 }
12911 
12912 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12913 bool PPCTargetLowering::useLoadStackGuardNode() const {
12914   if (!Subtarget.isTargetLinux())
12915     return TargetLowering::useLoadStackGuardNode();
12916   return true;
12917 }
12918 
12919 // Override to disable global variable loading on Linux.
12920 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12921   if (!Subtarget.isTargetLinux())
12922     return TargetLowering::insertSSPDeclarations(M);
12923 }
12924 
12925 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12926   if (!VT.isSimple() || !Subtarget.hasVSX())
12927     return false;
12928 
12929   switch(VT.getSimpleVT().SimpleTy) {
12930   default:
12931     // For FP types that are currently not supported by PPC backend, return
12932     // false. Examples: f16, f80.
12933     return false;
12934   case MVT::f32:
12935   case MVT::f64:
12936   case MVT::ppcf128:
12937     return Imm.isPosZero();
12938   }
12939 }
12940