1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.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/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.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/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/MC/MCExpr.h"
74 #include "llvm/MC/MCRegisterInfo.h"
75 #include "llvm/Support/AtomicOrdering.h"
76 #include "llvm/Support/BranchProbability.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CodeGen.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/Format.h"
84 #include "llvm/Support/KnownBits.h"
85 #include "llvm/Support/MachineValueType.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetMachine.h"
89 #include "llvm/Target/TargetOptions.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97 
98 using namespace llvm;
99 
100 #define DEBUG_TYPE "ppc-lowering"
101 
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 
114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
115 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
116 
117 STATISTIC(NumTailCalls, "Number of tail calls");
118 STATISTIC(NumSiblingCalls, "Number of sibling calls");
119 
120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
121 
122 // FIXME: Remove this once the bug has been fixed!
123 extern cl::opt<bool> ANDIGlueBug;
124 
125 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
126                                      const PPCSubtarget &STI)
127     : TargetLowering(TM), Subtarget(STI) {
128   // Use _setjmp/_longjmp instead of setjmp/longjmp.
129   setUseUnderscoreSetJmp(true);
130   setUseUnderscoreLongJmp(true);
131 
132   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
133   // arguments are at least 4/8 bytes aligned.
134   bool isPPC64 = Subtarget.isPPC64();
135   setMinStackArgumentAlignment(isPPC64 ? 8:4);
136 
137   // Set up the register classes.
138   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
139   if (!useSoftFloat()) {
140     if (hasSPE()) {
141       addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
142       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
143     } else {
144       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
145       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
146     }
147   }
148 
149   // Match BITREVERSE to customized fast code sequence in the td file.
150   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
151   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
152 
153   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
154   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
155 
156   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
157   for (MVT VT : MVT::integer_valuetypes()) {
158     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
159     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
160   }
161 
162   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
163 
164   // PowerPC has pre-inc load and store's.
165   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
166   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
167   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
168   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
169   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
170   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
171   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
172   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
173   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
174   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
175   if (!Subtarget.hasSPE()) {
176     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
177     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
178     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
179     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
180   }
181 
182   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
183   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
184   for (MVT VT : ScalarIntVTs) {
185     setOperationAction(ISD::ADDC, VT, Legal);
186     setOperationAction(ISD::ADDE, VT, Legal);
187     setOperationAction(ISD::SUBC, VT, Legal);
188     setOperationAction(ISD::SUBE, VT, Legal);
189   }
190 
191   if (Subtarget.useCRBits()) {
192     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193 
194     if (isPPC64 || Subtarget.hasFPCVT()) {
195       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
196       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
197                          isPPC64 ? MVT::i64 : MVT::i32);
198       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
199       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
200                         isPPC64 ? MVT::i64 : MVT::i32);
201     } else {
202       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
203       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
204     }
205 
206     // PowerPC does not support direct load/store of condition registers.
207     setOperationAction(ISD::LOAD, MVT::i1, Custom);
208     setOperationAction(ISD::STORE, MVT::i1, Custom);
209 
210     // FIXME: Remove this once the ANDI glue bug is fixed:
211     if (ANDIGlueBug)
212       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
213 
214     for (MVT VT : MVT::integer_valuetypes()) {
215       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
216       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
217       setTruncStoreAction(VT, MVT::i1, Expand);
218     }
219 
220     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
221   }
222 
223   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
224   // PPC (the libcall is not available).
225   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
226   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
227 
228   // We do not currently implement these libm ops for PowerPC.
229   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
230   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
231   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
232   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
233   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
234   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
235 
236   // PowerPC has no SREM/UREM instructions unless we are on P9
237   // On P9 we may use a hardware instruction to compute the remainder.
238   // The instructions are not legalized directly because in the cases where the
239   // result of both the remainder and the division is required it is more
240   // efficient to compute the remainder from the result of the division rather
241   // than use the remainder instruction.
242   if (Subtarget.isISA3_0()) {
243     setOperationAction(ISD::SREM, MVT::i32, Custom);
244     setOperationAction(ISD::UREM, MVT::i32, Custom);
245     setOperationAction(ISD::SREM, MVT::i64, Custom);
246     setOperationAction(ISD::UREM, MVT::i64, Custom);
247   } else {
248     setOperationAction(ISD::SREM, MVT::i32, Expand);
249     setOperationAction(ISD::UREM, MVT::i32, Expand);
250     setOperationAction(ISD::SREM, MVT::i64, Expand);
251     setOperationAction(ISD::UREM, MVT::i64, Expand);
252   }
253 
254   if (Subtarget.hasP9Vector()) {
255     setOperationAction(ISD::ABS, MVT::v4i32, Legal);
256     setOperationAction(ISD::ABS, MVT::v8i16, Legal);
257     setOperationAction(ISD::ABS, MVT::v16i8, Legal);
258   }
259 
260   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
261   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
262   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
263   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
264   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
265   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
266   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
267   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
268   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
269 
270   // We don't support sin/cos/sqrt/fmod/pow
271   setOperationAction(ISD::FSIN , MVT::f64, Expand);
272   setOperationAction(ISD::FCOS , MVT::f64, Expand);
273   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
274   setOperationAction(ISD::FREM , MVT::f64, Expand);
275   setOperationAction(ISD::FPOW , MVT::f64, Expand);
276   setOperationAction(ISD::FSIN , MVT::f32, Expand);
277   setOperationAction(ISD::FCOS , MVT::f32, Expand);
278   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
279   setOperationAction(ISD::FREM , MVT::f32, Expand);
280   setOperationAction(ISD::FPOW , MVT::f32, Expand);
281   if (Subtarget.hasSPE()) {
282     setOperationAction(ISD::FMA  , MVT::f64, Expand);
283     setOperationAction(ISD::FMA  , MVT::f32, Expand);
284   } else {
285     setOperationAction(ISD::FMA  , MVT::f64, Legal);
286     setOperationAction(ISD::FMA  , MVT::f32, Legal);
287   }
288 
289   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
290 
291   // If we're enabling GP optimizations, use hardware square root
292   if (!Subtarget.hasFSQRT() &&
293       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
294         Subtarget.hasFRE()))
295     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
296 
297   if (!Subtarget.hasFSQRT() &&
298       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
299         Subtarget.hasFRES()))
300     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
301 
302   if (Subtarget.hasFCPSGN()) {
303     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
304     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
305   } else {
306     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
307     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
308   }
309 
310   if (Subtarget.hasFPRND()) {
311     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
312     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
313     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
314     setOperationAction(ISD::FROUND, MVT::f64, Legal);
315 
316     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
317     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
318     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
319     setOperationAction(ISD::FROUND, MVT::f32, Legal);
320   }
321 
322   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
323   // to speed up scalar BSWAP64.
324   // CTPOP or CTTZ were introduced in P8/P9 respectively
325   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
326   if (Subtarget.isISA3_0()) {
327     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
328     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
329     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
330   } else {
331     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
332     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
333     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
334   }
335 
336   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
337     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
338     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
339   } else {
340     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
341     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
342   }
343 
344   // PowerPC does not have ROTR
345   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
346   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
347 
348   if (!Subtarget.useCRBits()) {
349     // PowerPC does not have Select
350     setOperationAction(ISD::SELECT, MVT::i32, Expand);
351     setOperationAction(ISD::SELECT, MVT::i64, Expand);
352     setOperationAction(ISD::SELECT, MVT::f32, Expand);
353     setOperationAction(ISD::SELECT, MVT::f64, Expand);
354   }
355 
356   // PowerPC wants to turn select_cc of FP into fsel when possible.
357   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
358   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
359 
360   // PowerPC wants to optimize integer setcc a bit
361   if (!Subtarget.useCRBits())
362     setOperationAction(ISD::SETCC, MVT::i32, Custom);
363 
364   // PowerPC does not have BRCOND which requires SetCC
365   if (!Subtarget.useCRBits())
366     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
367 
368   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
369 
370   if (Subtarget.hasSPE()) {
371     // SPE has built-in conversions
372     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
373     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
374     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
375   } else {
376     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
377     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
378 
379     // PowerPC does not have [U|S]INT_TO_FP
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
382   }
383 
384   if (Subtarget.hasDirectMove() && isPPC64) {
385     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
386     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
387     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
388     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
389   } else {
390     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
391     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
392     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
393     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
394   }
395 
396   // We cannot sextinreg(i1).  Expand to shifts.
397   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
398 
399   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
400   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
401   // support continuation, user-level threading, and etc.. As a result, no
402   // other SjLj exception interfaces are implemented and please don't build
403   // your own exception handling based on them.
404   // LLVM/Clang supports zero-cost DWARF exception handling.
405   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
406   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
407 
408   // We want to legalize GlobalAddress and ConstantPool nodes into the
409   // appropriate instructions to materialize the address.
410   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
411   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
412   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
413   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
414   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
415   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
416   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
417   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
418   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
419   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
420 
421   // TRAP is legal.
422   setOperationAction(ISD::TRAP, MVT::Other, Legal);
423 
424   // TRAMPOLINE is custom lowered.
425   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
426   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
427 
428   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
429   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
430 
431   if (Subtarget.isSVR4ABI()) {
432     if (isPPC64) {
433       // VAARG always uses double-word chunks, so promote anything smaller.
434       setOperationAction(ISD::VAARG, MVT::i1, Promote);
435       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
436       setOperationAction(ISD::VAARG, MVT::i8, Promote);
437       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
438       setOperationAction(ISD::VAARG, MVT::i16, Promote);
439       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
440       setOperationAction(ISD::VAARG, MVT::i32, Promote);
441       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
442       setOperationAction(ISD::VAARG, MVT::Other, Expand);
443     } else {
444       // VAARG is custom lowered with the 32-bit SVR4 ABI.
445       setOperationAction(ISD::VAARG, MVT::Other, Custom);
446       setOperationAction(ISD::VAARG, MVT::i64, Custom);
447     }
448   } else
449     setOperationAction(ISD::VAARG, MVT::Other, Expand);
450 
451   if (Subtarget.isSVR4ABI() && !isPPC64)
452     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
453     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
454   else
455     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
456 
457   // Use the default implementation.
458   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
459   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
460   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
461   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
462   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
463   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
464   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
465   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
466   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
467 
468   // We want to custom lower some of our intrinsics.
469   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
470 
471   // To handle counter-based loop conditions.
472   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
473 
474   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
475   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
476   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
477   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
478 
479   // Comparisons that require checking two conditions.
480   if (Subtarget.hasSPE()) {
481     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
482     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
483     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
484     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
485   }
486   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
487   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
488   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
489   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
490   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
491   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
492   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
493   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
494   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
495   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
496   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
497   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
498 
499   if (Subtarget.has64BitSupport()) {
500     // They also have instructions for converting between i64 and fp.
501     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
502     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
503     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
504     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
505     // This is just the low 32 bits of a (signed) fp->i64 conversion.
506     // We cannot do this with Promote because i64 is not a legal type.
507     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
508 
509     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
510       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
511   } else {
512     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
513     if (Subtarget.hasSPE())
514       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
515     else
516       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
517   }
518 
519   // With the instructions enabled under FPCVT, we can do everything.
520   if (Subtarget.hasFPCVT()) {
521     if (Subtarget.has64BitSupport()) {
522       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
523       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
524       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
525       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
526     }
527 
528     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
529     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
530     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
531     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
532   }
533 
534   if (Subtarget.use64BitRegs()) {
535     // 64-bit PowerPC implementations can support i64 types directly
536     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
537     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
538     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
539     // 64-bit PowerPC wants to expand i128 shifts itself.
540     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
541     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
542     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
543   } else {
544     // 32-bit PowerPC wants to expand i64 shifts itself.
545     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
546     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
547     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
548   }
549 
550   if (Subtarget.hasAltivec()) {
551     // First set operation action for all vector types to expand. Then we
552     // will selectively turn on ones that can be effectively codegen'd.
553     for (MVT VT : MVT::vector_valuetypes()) {
554       // add/sub are legal for all supported vector VT's.
555       setOperationAction(ISD::ADD, VT, Legal);
556       setOperationAction(ISD::SUB, VT, Legal);
557 
558       // Vector instructions introduced in P8
559       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
560         setOperationAction(ISD::CTPOP, VT, Legal);
561         setOperationAction(ISD::CTLZ, VT, Legal);
562       }
563       else {
564         setOperationAction(ISD::CTPOP, VT, Expand);
565         setOperationAction(ISD::CTLZ, VT, Expand);
566       }
567 
568       // Vector instructions introduced in P9
569       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
570         setOperationAction(ISD::CTTZ, VT, Legal);
571       else
572         setOperationAction(ISD::CTTZ, VT, Expand);
573 
574       // We promote all shuffles to v16i8.
575       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
576       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
577 
578       // We promote all non-typed operations to v4i32.
579       setOperationAction(ISD::AND   , VT, Promote);
580       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
581       setOperationAction(ISD::OR    , VT, Promote);
582       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
583       setOperationAction(ISD::XOR   , VT, Promote);
584       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
585       setOperationAction(ISD::LOAD  , VT, Promote);
586       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
587       setOperationAction(ISD::SELECT, VT, Promote);
588       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
589       setOperationAction(ISD::SELECT_CC, VT, Promote);
590       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
591       setOperationAction(ISD::STORE, VT, Promote);
592       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
593 
594       // No other operations are legal.
595       setOperationAction(ISD::MUL , VT, Expand);
596       setOperationAction(ISD::SDIV, VT, Expand);
597       setOperationAction(ISD::SREM, VT, Expand);
598       setOperationAction(ISD::UDIV, VT, Expand);
599       setOperationAction(ISD::UREM, VT, Expand);
600       setOperationAction(ISD::FDIV, VT, Expand);
601       setOperationAction(ISD::FREM, VT, Expand);
602       setOperationAction(ISD::FNEG, VT, Expand);
603       setOperationAction(ISD::FSQRT, VT, Expand);
604       setOperationAction(ISD::FLOG, VT, Expand);
605       setOperationAction(ISD::FLOG10, VT, Expand);
606       setOperationAction(ISD::FLOG2, VT, Expand);
607       setOperationAction(ISD::FEXP, VT, Expand);
608       setOperationAction(ISD::FEXP2, VT, Expand);
609       setOperationAction(ISD::FSIN, VT, Expand);
610       setOperationAction(ISD::FCOS, VT, Expand);
611       setOperationAction(ISD::FABS, VT, Expand);
612       setOperationAction(ISD::FFLOOR, VT, Expand);
613       setOperationAction(ISD::FCEIL,  VT, Expand);
614       setOperationAction(ISD::FTRUNC, VT, Expand);
615       setOperationAction(ISD::FRINT,  VT, Expand);
616       setOperationAction(ISD::FNEARBYINT, VT, Expand);
617       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
618       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
619       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
620       setOperationAction(ISD::MULHU, VT, Expand);
621       setOperationAction(ISD::MULHS, VT, Expand);
622       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
623       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
624       setOperationAction(ISD::UDIVREM, VT, Expand);
625       setOperationAction(ISD::SDIVREM, VT, Expand);
626       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
627       setOperationAction(ISD::FPOW, VT, Expand);
628       setOperationAction(ISD::BSWAP, VT, Expand);
629       setOperationAction(ISD::VSELECT, VT, Expand);
630       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
631       setOperationAction(ISD::ROTL, VT, Expand);
632       setOperationAction(ISD::ROTR, VT, Expand);
633 
634       for (MVT InnerVT : MVT::vector_valuetypes()) {
635         setTruncStoreAction(VT, InnerVT, Expand);
636         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
637         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
638         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
639       }
640     }
641 
642     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
643     // with merges, splats, etc.
644     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
645 
646     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
647     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
648     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
649     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
650     setOperationAction(ISD::SELECT, MVT::v4i32,
651                        Subtarget.useCRBits() ? Legal : Expand);
652     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
653     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
654     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
655     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
656     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
657     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
658     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
659     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
660     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
661 
662     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
663     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
664     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
665     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
666 
667     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
668     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
669 
670     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
671       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
672       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
673     }
674 
675     if (Subtarget.hasP8Altivec())
676       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
677     else
678       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
679 
680     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
681     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
682 
683     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
684     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
685 
686     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
687     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
688     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
689     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
690 
691     // Altivec does not contain unordered floating-point compare instructions
692     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
693     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
694     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
695     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
696 
697     if (Subtarget.hasVSX()) {
698       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
699       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
700       if (Subtarget.hasP8Vector()) {
701         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
702         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
703       }
704       if (Subtarget.hasDirectMove() && isPPC64) {
705         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
706         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
707         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
708         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
709         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
710         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
711         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
712         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
713       }
714       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
715 
716       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
717       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
718       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
719       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
720       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
721 
722       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
723 
724       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
725       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
726 
727       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
728       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
729 
730       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
731       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
732       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
733       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
734       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
735 
736       // Share the Altivec comparison restrictions.
737       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
738       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
739       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
740       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
741 
742       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
743       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
744 
745       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
746 
747       if (Subtarget.hasP8Vector())
748         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
749 
750       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
751 
752       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
753       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
754       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
755 
756       if (Subtarget.hasP8Altivec()) {
757         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
758         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
759         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
760 
761         // 128 bit shifts can be accomplished via 3 instructions for SHL and
762         // SRL, but not for SRA because of the instructions available:
763         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
764         // doing
765         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
766         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
767         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
768 
769         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
770       }
771       else {
772         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
773         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
774         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
775 
776         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
777 
778         // VSX v2i64 only supports non-arithmetic operations.
779         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
780         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
781       }
782 
783       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
784       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
785       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
786       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
787 
788       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
789 
790       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
791       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
792       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
793       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
794 
795       // Vector operation legalization checks the result type of
796       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
797       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
798       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
799       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
800       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
801 
802       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
803       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
804       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
805       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
806 
807       if (Subtarget.hasDirectMove())
808         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
809       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
810 
811       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
812     }
813 
814     if (Subtarget.hasP8Altivec()) {
815       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
816       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
817     }
818 
819     if (Subtarget.hasP9Vector()) {
820       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
821       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
822 
823       // 128 bit shifts can be accomplished via 3 instructions for SHL and
824       // SRL, but not for SRA because of the instructions available:
825       // VS{RL} and VS{RL}O.
826       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
827       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
828       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
829 
830       if (EnableQuadPrecision) {
831         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
832         setOperationAction(ISD::FADD, MVT::f128, Legal);
833         setOperationAction(ISD::FSUB, MVT::f128, Legal);
834         setOperationAction(ISD::FDIV, MVT::f128, Legal);
835         setOperationAction(ISD::FMUL, MVT::f128, Legal);
836         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
837         // No extending loads to f128 on PPC.
838         for (MVT FPT : MVT::fp_valuetypes())
839           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
840         setOperationAction(ISD::FMA, MVT::f128, Legal);
841         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
842         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
843         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
844         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
845         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
846         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
847 
848         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
849         setOperationAction(ISD::FRINT, MVT::f128, Legal);
850         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
851         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
852         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
853         setOperationAction(ISD::FROUND, MVT::f128, Legal);
854 
855         setOperationAction(ISD::SELECT, MVT::f128, Expand);
856         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
857         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
858         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
859         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
860         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
861         // No implementation for these ops for PowerPC.
862         setOperationAction(ISD::FSIN , MVT::f128, Expand);
863         setOperationAction(ISD::FCOS , MVT::f128, Expand);
864         setOperationAction(ISD::FPOW, MVT::f128, Expand);
865         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
866         setOperationAction(ISD::FREM, MVT::f128, Expand);
867       }
868 
869     }
870 
871     if (Subtarget.hasP9Altivec()) {
872       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
873       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
874     }
875   }
876 
877   if (Subtarget.hasQPX()) {
878     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
879     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
880     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
881     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
882 
883     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
884     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
885 
886     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
887     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
888 
889     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
890     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
891 
892     if (!Subtarget.useCRBits())
893       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
894     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
895 
896     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
897     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
898     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
899     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
900     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
901     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
902     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
903 
904     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
905     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
906 
907     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
908     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
909     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
910 
911     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
912     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
913     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
914     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
915     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
916     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
917     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
918     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
919     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
920     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
921 
922     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
923     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
924 
925     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
926     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
927 
928     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
929 
930     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
931     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
932     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
933     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
934 
935     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
936     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
937 
938     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
939     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
940 
941     if (!Subtarget.useCRBits())
942       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
943     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
944 
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
946     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
947     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
948     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
949     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
950     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
951     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
952 
953     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
954     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
955 
956     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
957     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
958     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
959     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
960     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
961     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
962     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
963     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
964     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
965     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
966 
967     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
968     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
969 
970     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
971     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
972 
973     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
974 
975     setOperationAction(ISD::AND , MVT::v4i1, Legal);
976     setOperationAction(ISD::OR , MVT::v4i1, Legal);
977     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
978 
979     if (!Subtarget.useCRBits())
980       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
981     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
982 
983     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
984     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
985 
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
988     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
989     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
990     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
991     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
992     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
993 
994     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
995     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
996 
997     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
998 
999     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1000     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1001     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1002     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1003 
1004     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1005     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1006     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1007     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1008 
1009     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1010     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1011 
1012     // These need to set FE_INEXACT, and so cannot be vectorized here.
1013     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1014     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1015 
1016     if (TM.Options.UnsafeFPMath) {
1017       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1018       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1019 
1020       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1021       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1022     } else {
1023       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1024       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1025 
1026       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1027       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1028     }
1029   }
1030 
1031   if (Subtarget.has64BitSupport())
1032     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1033 
1034   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1035 
1036   if (!isPPC64) {
1037     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1038     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1039   }
1040 
1041   setBooleanContents(ZeroOrOneBooleanContent);
1042 
1043   if (Subtarget.hasAltivec()) {
1044     // Altivec instructions set fields to all zeros or all ones.
1045     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1046   }
1047 
1048   if (!isPPC64) {
1049     // These libcalls are not available in 32-bit.
1050     setLibcallName(RTLIB::SHL_I128, nullptr);
1051     setLibcallName(RTLIB::SRL_I128, nullptr);
1052     setLibcallName(RTLIB::SRA_I128, nullptr);
1053   }
1054 
1055   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1056 
1057   // We have target-specific dag combine patterns for the following nodes:
1058   setTargetDAGCombine(ISD::ADD);
1059   setTargetDAGCombine(ISD::SHL);
1060   setTargetDAGCombine(ISD::SRA);
1061   setTargetDAGCombine(ISD::SRL);
1062   setTargetDAGCombine(ISD::SINT_TO_FP);
1063   setTargetDAGCombine(ISD::BUILD_VECTOR);
1064   if (Subtarget.hasFPCVT())
1065     setTargetDAGCombine(ISD::UINT_TO_FP);
1066   setTargetDAGCombine(ISD::LOAD);
1067   setTargetDAGCombine(ISD::STORE);
1068   setTargetDAGCombine(ISD::BR_CC);
1069   if (Subtarget.useCRBits())
1070     setTargetDAGCombine(ISD::BRCOND);
1071   setTargetDAGCombine(ISD::BSWAP);
1072   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1073   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1074   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1075 
1076   setTargetDAGCombine(ISD::SIGN_EXTEND);
1077   setTargetDAGCombine(ISD::ZERO_EXTEND);
1078   setTargetDAGCombine(ISD::ANY_EXTEND);
1079 
1080   if (Subtarget.useCRBits()) {
1081     setTargetDAGCombine(ISD::TRUNCATE);
1082     setTargetDAGCombine(ISD::SETCC);
1083     setTargetDAGCombine(ISD::SELECT_CC);
1084   }
1085 
1086   // Use reciprocal estimates.
1087   if (TM.Options.UnsafeFPMath) {
1088     setTargetDAGCombine(ISD::FDIV);
1089     setTargetDAGCombine(ISD::FSQRT);
1090   }
1091 
1092   // Darwin long double math library functions have $LDBL128 appended.
1093   if (Subtarget.isDarwin()) {
1094     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1095     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1096     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1097     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1098     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1099     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1100     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1101     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1102     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1103     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1104   }
1105 
1106   if (EnableQuadPrecision) {
1107     setLibcallName(RTLIB::LOG_F128, "logf128");
1108     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1109     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1110     setLibcallName(RTLIB::EXP_F128, "expf128");
1111     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1112     setLibcallName(RTLIB::SIN_F128, "sinf128");
1113     setLibcallName(RTLIB::COS_F128, "cosf128");
1114     setLibcallName(RTLIB::POW_F128, "powf128");
1115     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1116     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1117     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1118     setLibcallName(RTLIB::REM_F128, "fmodf128");
1119   }
1120 
1121   // With 32 condition bits, we don't need to sink (and duplicate) compares
1122   // aggressively in CodeGenPrep.
1123   if (Subtarget.useCRBits()) {
1124     setHasMultipleConditionRegisters();
1125     setJumpIsExpensive();
1126   }
1127 
1128   setMinFunctionAlignment(2);
1129   if (Subtarget.isDarwin())
1130     setPrefFunctionAlignment(4);
1131 
1132   switch (Subtarget.getDarwinDirective()) {
1133   default: break;
1134   case PPC::DIR_970:
1135   case PPC::DIR_A2:
1136   case PPC::DIR_E500:
1137   case PPC::DIR_E500mc:
1138   case PPC::DIR_E5500:
1139   case PPC::DIR_PWR4:
1140   case PPC::DIR_PWR5:
1141   case PPC::DIR_PWR5X:
1142   case PPC::DIR_PWR6:
1143   case PPC::DIR_PWR6X:
1144   case PPC::DIR_PWR7:
1145   case PPC::DIR_PWR8:
1146   case PPC::DIR_PWR9:
1147     setPrefFunctionAlignment(4);
1148     setPrefLoopAlignment(4);
1149     break;
1150   }
1151 
1152   if (Subtarget.enableMachineScheduler())
1153     setSchedulingPreference(Sched::Source);
1154   else
1155     setSchedulingPreference(Sched::Hybrid);
1156 
1157   computeRegisterProperties(STI.getRegisterInfo());
1158 
1159   // The Freescale cores do better with aggressive inlining of memcpy and
1160   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1161   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1162       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1163     MaxStoresPerMemset = 32;
1164     MaxStoresPerMemsetOptSize = 16;
1165     MaxStoresPerMemcpy = 32;
1166     MaxStoresPerMemcpyOptSize = 8;
1167     MaxStoresPerMemmove = 32;
1168     MaxStoresPerMemmoveOptSize = 8;
1169   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1170     // The A2 also benefits from (very) aggressive inlining of memcpy and
1171     // friends. The overhead of a the function call, even when warm, can be
1172     // over one hundred cycles.
1173     MaxStoresPerMemset = 128;
1174     MaxStoresPerMemcpy = 128;
1175     MaxStoresPerMemmove = 128;
1176     MaxLoadsPerMemcmp = 128;
1177   } else {
1178     MaxLoadsPerMemcmp = 8;
1179     MaxLoadsPerMemcmpOptSize = 4;
1180   }
1181 }
1182 
1183 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1184 /// the desired ByVal argument alignment.
1185 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1186                              unsigned MaxMaxAlign) {
1187   if (MaxAlign == MaxMaxAlign)
1188     return;
1189   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1190     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1191       MaxAlign = 32;
1192     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1193       MaxAlign = 16;
1194   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1195     unsigned EltAlign = 0;
1196     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1197     if (EltAlign > MaxAlign)
1198       MaxAlign = EltAlign;
1199   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1200     for (auto *EltTy : STy->elements()) {
1201       unsigned EltAlign = 0;
1202       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1203       if (EltAlign > MaxAlign)
1204         MaxAlign = EltAlign;
1205       if (MaxAlign == MaxMaxAlign)
1206         break;
1207     }
1208   }
1209 }
1210 
1211 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1212 /// function arguments in the caller parameter area.
1213 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1214                                                   const DataLayout &DL) const {
1215   // Darwin passes everything on 4 byte boundary.
1216   if (Subtarget.isDarwin())
1217     return 4;
1218 
1219   // 16byte and wider vectors are passed on 16byte boundary.
1220   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1221   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1222   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1223     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1224   return Align;
1225 }
1226 
1227 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1228                                                           CallingConv:: ID CC,
1229                                                           EVT VT) const {
1230   if (Subtarget.hasSPE() && VT == MVT::f64)
1231     return 2;
1232   return PPCTargetLowering::getNumRegisters(Context, VT);
1233 }
1234 
1235 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1236                                                      CallingConv:: ID CC,
1237                                                      EVT VT) const {
1238   if (Subtarget.hasSPE() && VT == MVT::f64)
1239     return MVT::i32;
1240   return PPCTargetLowering::getRegisterType(Context, VT);
1241 }
1242 
1243 bool PPCTargetLowering::useSoftFloat() const {
1244   return Subtarget.useSoftFloat();
1245 }
1246 
1247 bool PPCTargetLowering::hasSPE() const {
1248   return Subtarget.hasSPE();
1249 }
1250 
1251 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1252   switch ((PPCISD::NodeType)Opcode) {
1253   case PPCISD::FIRST_NUMBER:    break;
1254   case PPCISD::FSEL:            return "PPCISD::FSEL";
1255   case PPCISD::FCFID:           return "PPCISD::FCFID";
1256   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1257   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1258   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1259   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1260   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1261   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1262   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1263   case PPCISD::FP_TO_UINT_IN_VSR:
1264                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1265   case PPCISD::FP_TO_SINT_IN_VSR:
1266                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1267   case PPCISD::FRE:             return "PPCISD::FRE";
1268   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1269   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1270   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1271   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1272   case PPCISD::VPERM:           return "PPCISD::VPERM";
1273   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1274   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1275   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1276   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1277   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1278   case PPCISD::CMPB:            return "PPCISD::CMPB";
1279   case PPCISD::Hi:              return "PPCISD::Hi";
1280   case PPCISD::Lo:              return "PPCISD::Lo";
1281   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1282   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1283   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1284   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1285   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1286   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1287   case PPCISD::SRL:             return "PPCISD::SRL";
1288   case PPCISD::SRA:             return "PPCISD::SRA";
1289   case PPCISD::SHL:             return "PPCISD::SHL";
1290   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1291   case PPCISD::CALL:            return "PPCISD::CALL";
1292   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1293   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1294   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1295   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1296   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1297   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1298   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1299   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1300   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1301   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1302   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1303   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1304   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1305   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1306   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1307   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1308   case PPCISD::VCMP:            return "PPCISD::VCMP";
1309   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1310   case PPCISD::LBRX:            return "PPCISD::LBRX";
1311   case PPCISD::STBRX:           return "PPCISD::STBRX";
1312   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1313   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1314   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1315   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1316   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1317   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1318   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1319   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1320   case PPCISD::ST_VSR_SCAL_INT:
1321                                 return "PPCISD::ST_VSR_SCAL_INT";
1322   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1323   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1324   case PPCISD::BDZ:             return "PPCISD::BDZ";
1325   case PPCISD::MFFS:            return "PPCISD::MFFS";
1326   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1327   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1328   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1329   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1330   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1331   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1332   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1333   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1334   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1335   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1336   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1337   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1338   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1339   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1340   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1341   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1342   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1343   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1344   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1345   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1346   case PPCISD::SC:              return "PPCISD::SC";
1347   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1348   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1349   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1350   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1351   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1352   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1353   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1354   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1355   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1356   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1357   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1358   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1359   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1360   }
1361   return nullptr;
1362 }
1363 
1364 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1365                                           EVT VT) const {
1366   if (!VT.isVector())
1367     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1368 
1369   if (Subtarget.hasQPX())
1370     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1371 
1372   return VT.changeVectorElementTypeToInteger();
1373 }
1374 
1375 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1376   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1377   return true;
1378 }
1379 
1380 //===----------------------------------------------------------------------===//
1381 // Node matching predicates, for use by the tblgen matching code.
1382 //===----------------------------------------------------------------------===//
1383 
1384 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1385 static bool isFloatingPointZero(SDValue Op) {
1386   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1387     return CFP->getValueAPF().isZero();
1388   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1389     // Maybe this has already been legalized into the constant pool?
1390     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1391       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1392         return CFP->getValueAPF().isZero();
1393   }
1394   return false;
1395 }
1396 
1397 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1398 /// true if Op is undef or if it matches the specified value.
1399 static bool isConstantOrUndef(int Op, int Val) {
1400   return Op < 0 || Op == Val;
1401 }
1402 
1403 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1404 /// VPKUHUM instruction.
1405 /// The ShuffleKind distinguishes between big-endian operations with
1406 /// two different inputs (0), either-endian operations with two identical
1407 /// inputs (1), and little-endian operations with two different inputs (2).
1408 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1409 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1410                                SelectionDAG &DAG) {
1411   bool IsLE = DAG.getDataLayout().isLittleEndian();
1412   if (ShuffleKind == 0) {
1413     if (IsLE)
1414       return false;
1415     for (unsigned i = 0; i != 16; ++i)
1416       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1417         return false;
1418   } else if (ShuffleKind == 2) {
1419     if (!IsLE)
1420       return false;
1421     for (unsigned i = 0; i != 16; ++i)
1422       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1423         return false;
1424   } else if (ShuffleKind == 1) {
1425     unsigned j = IsLE ? 0 : 1;
1426     for (unsigned i = 0; i != 8; ++i)
1427       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1428           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1429         return false;
1430   }
1431   return true;
1432 }
1433 
1434 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1435 /// VPKUWUM instruction.
1436 /// The ShuffleKind distinguishes between big-endian operations with
1437 /// two different inputs (0), either-endian operations with two identical
1438 /// inputs (1), and little-endian operations with two different inputs (2).
1439 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1440 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1441                                SelectionDAG &DAG) {
1442   bool IsLE = DAG.getDataLayout().isLittleEndian();
1443   if (ShuffleKind == 0) {
1444     if (IsLE)
1445       return false;
1446     for (unsigned i = 0; i != 16; i += 2)
1447       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1448           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1449         return false;
1450   } else if (ShuffleKind == 2) {
1451     if (!IsLE)
1452       return false;
1453     for (unsigned i = 0; i != 16; i += 2)
1454       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1455           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1456         return false;
1457   } else if (ShuffleKind == 1) {
1458     unsigned j = IsLE ? 0 : 2;
1459     for (unsigned i = 0; i != 8; i += 2)
1460       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1461           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1462           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1463           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1464         return false;
1465   }
1466   return true;
1467 }
1468 
1469 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1470 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1471 /// current subtarget.
1472 ///
1473 /// The ShuffleKind distinguishes between big-endian operations with
1474 /// two different inputs (0), either-endian operations with two identical
1475 /// inputs (1), and little-endian operations with two different inputs (2).
1476 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1477 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1478                                SelectionDAG &DAG) {
1479   const PPCSubtarget& Subtarget =
1480     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1481   if (!Subtarget.hasP8Vector())
1482     return false;
1483 
1484   bool IsLE = DAG.getDataLayout().isLittleEndian();
1485   if (ShuffleKind == 0) {
1486     if (IsLE)
1487       return false;
1488     for (unsigned i = 0; i != 16; i += 4)
1489       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1490           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1491           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1492           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1493         return false;
1494   } else if (ShuffleKind == 2) {
1495     if (!IsLE)
1496       return false;
1497     for (unsigned i = 0; i != 16; i += 4)
1498       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1499           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1500           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1501           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1502         return false;
1503   } else if (ShuffleKind == 1) {
1504     unsigned j = IsLE ? 0 : 4;
1505     for (unsigned i = 0; i != 8; i += 4)
1506       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1507           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1508           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1509           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1510           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1511           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1512           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1513           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1514         return false;
1515   }
1516   return true;
1517 }
1518 
1519 /// isVMerge - Common function, used to match vmrg* shuffles.
1520 ///
1521 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1522                      unsigned LHSStart, unsigned RHSStart) {
1523   if (N->getValueType(0) != MVT::v16i8)
1524     return false;
1525   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1526          "Unsupported merge size!");
1527 
1528   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1529     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1530       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1531                              LHSStart+j+i*UnitSize) ||
1532           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1533                              RHSStart+j+i*UnitSize))
1534         return false;
1535     }
1536   return true;
1537 }
1538 
1539 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1540 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1541 /// The ShuffleKind distinguishes between big-endian merges with two
1542 /// different inputs (0), either-endian merges with two identical inputs (1),
1543 /// and little-endian merges with two different inputs (2).  For the latter,
1544 /// the input operands are swapped (see PPCInstrAltivec.td).
1545 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1546                              unsigned ShuffleKind, SelectionDAG &DAG) {
1547   if (DAG.getDataLayout().isLittleEndian()) {
1548     if (ShuffleKind == 1) // unary
1549       return isVMerge(N, UnitSize, 0, 0);
1550     else if (ShuffleKind == 2) // swapped
1551       return isVMerge(N, UnitSize, 0, 16);
1552     else
1553       return false;
1554   } else {
1555     if (ShuffleKind == 1) // unary
1556       return isVMerge(N, UnitSize, 8, 8);
1557     else if (ShuffleKind == 0) // normal
1558       return isVMerge(N, UnitSize, 8, 24);
1559     else
1560       return false;
1561   }
1562 }
1563 
1564 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1565 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1566 /// The ShuffleKind distinguishes between big-endian merges with two
1567 /// different inputs (0), either-endian merges with two identical inputs (1),
1568 /// and little-endian merges with two different inputs (2).  For the latter,
1569 /// the input operands are swapped (see PPCInstrAltivec.td).
1570 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1571                              unsigned ShuffleKind, SelectionDAG &DAG) {
1572   if (DAG.getDataLayout().isLittleEndian()) {
1573     if (ShuffleKind == 1) // unary
1574       return isVMerge(N, UnitSize, 8, 8);
1575     else if (ShuffleKind == 2) // swapped
1576       return isVMerge(N, UnitSize, 8, 24);
1577     else
1578       return false;
1579   } else {
1580     if (ShuffleKind == 1) // unary
1581       return isVMerge(N, UnitSize, 0, 0);
1582     else if (ShuffleKind == 0) // normal
1583       return isVMerge(N, UnitSize, 0, 16);
1584     else
1585       return false;
1586   }
1587 }
1588 
1589 /**
1590  * Common function used to match vmrgew and vmrgow shuffles
1591  *
1592  * The indexOffset determines whether to look for even or odd words in
1593  * the shuffle mask. This is based on the of the endianness of the target
1594  * machine.
1595  *   - Little Endian:
1596  *     - Use offset of 0 to check for odd elements
1597  *     - Use offset of 4 to check for even elements
1598  *   - Big Endian:
1599  *     - Use offset of 0 to check for even elements
1600  *     - Use offset of 4 to check for odd elements
1601  * A detailed description of the vector element ordering for little endian and
1602  * big endian can be found at
1603  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1604  * Targeting your applications - what little endian and big endian IBM XL C/C++
1605  * compiler differences mean to you
1606  *
1607  * The mask to the shuffle vector instruction specifies the indices of the
1608  * elements from the two input vectors to place in the result. The elements are
1609  * numbered in array-access order, starting with the first vector. These vectors
1610  * are always of type v16i8, thus each vector will contain 16 elements of size
1611  * 8. More info on the shuffle vector can be found in the
1612  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1613  * Language Reference.
1614  *
1615  * The RHSStartValue indicates whether the same input vectors are used (unary)
1616  * or two different input vectors are used, based on the following:
1617  *   - If the instruction uses the same vector for both inputs, the range of the
1618  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1619  *     be 0.
1620  *   - If the instruction has two different vectors then the range of the
1621  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1622  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1623  *     to 31 specify elements in the second vector).
1624  *
1625  * \param[in] N The shuffle vector SD Node to analyze
1626  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1627  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1628  * vector to the shuffle_vector instruction
1629  * \return true iff this shuffle vector represents an even or odd word merge
1630  */
1631 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1632                      unsigned RHSStartValue) {
1633   if (N->getValueType(0) != MVT::v16i8)
1634     return false;
1635 
1636   for (unsigned i = 0; i < 2; ++i)
1637     for (unsigned j = 0; j < 4; ++j)
1638       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1639                              i*RHSStartValue+j+IndexOffset) ||
1640           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1641                              i*RHSStartValue+j+IndexOffset+8))
1642         return false;
1643   return true;
1644 }
1645 
1646 /**
1647  * Determine if the specified shuffle mask is suitable for the vmrgew or
1648  * vmrgow instructions.
1649  *
1650  * \param[in] N The shuffle vector SD Node to analyze
1651  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1652  * \param[in] ShuffleKind Identify the type of merge:
1653  *   - 0 = big-endian merge with two different inputs;
1654  *   - 1 = either-endian merge with two identical inputs;
1655  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1656  *     little-endian merges).
1657  * \param[in] DAG The current SelectionDAG
1658  * \return true iff this shuffle mask
1659  */
1660 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1661                               unsigned ShuffleKind, SelectionDAG &DAG) {
1662   if (DAG.getDataLayout().isLittleEndian()) {
1663     unsigned indexOffset = CheckEven ? 4 : 0;
1664     if (ShuffleKind == 1) // Unary
1665       return isVMerge(N, indexOffset, 0);
1666     else if (ShuffleKind == 2) // swapped
1667       return isVMerge(N, indexOffset, 16);
1668     else
1669       return false;
1670   }
1671   else {
1672     unsigned indexOffset = CheckEven ? 0 : 4;
1673     if (ShuffleKind == 1) // Unary
1674       return isVMerge(N, indexOffset, 0);
1675     else if (ShuffleKind == 0) // Normal
1676       return isVMerge(N, indexOffset, 16);
1677     else
1678       return false;
1679   }
1680   return false;
1681 }
1682 
1683 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1684 /// amount, otherwise return -1.
1685 /// The ShuffleKind distinguishes between big-endian operations with two
1686 /// different inputs (0), either-endian operations with two identical inputs
1687 /// (1), and little-endian operations with two different inputs (2).  For the
1688 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1689 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1690                              SelectionDAG &DAG) {
1691   if (N->getValueType(0) != MVT::v16i8)
1692     return -1;
1693 
1694   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1695 
1696   // Find the first non-undef value in the shuffle mask.
1697   unsigned i;
1698   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1699     /*search*/;
1700 
1701   if (i == 16) return -1;  // all undef.
1702 
1703   // Otherwise, check to see if the rest of the elements are consecutively
1704   // numbered from this value.
1705   unsigned ShiftAmt = SVOp->getMaskElt(i);
1706   if (ShiftAmt < i) return -1;
1707 
1708   ShiftAmt -= i;
1709   bool isLE = DAG.getDataLayout().isLittleEndian();
1710 
1711   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1712     // Check the rest of the elements to see if they are consecutive.
1713     for (++i; i != 16; ++i)
1714       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1715         return -1;
1716   } else if (ShuffleKind == 1) {
1717     // Check the rest of the elements to see if they are consecutive.
1718     for (++i; i != 16; ++i)
1719       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1720         return -1;
1721   } else
1722     return -1;
1723 
1724   if (isLE)
1725     ShiftAmt = 16 - ShiftAmt;
1726 
1727   return ShiftAmt;
1728 }
1729 
1730 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1731 /// specifies a splat of a single element that is suitable for input to
1732 /// VSPLTB/VSPLTH/VSPLTW.
1733 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1734   assert(N->getValueType(0) == MVT::v16i8 &&
1735          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1736 
1737   // The consecutive indices need to specify an element, not part of two
1738   // different elements.  So abandon ship early if this isn't the case.
1739   if (N->getMaskElt(0) % EltSize != 0)
1740     return false;
1741 
1742   // This is a splat operation if each element of the permute is the same, and
1743   // if the value doesn't reference the second vector.
1744   unsigned ElementBase = N->getMaskElt(0);
1745 
1746   // FIXME: Handle UNDEF elements too!
1747   if (ElementBase >= 16)
1748     return false;
1749 
1750   // Check that the indices are consecutive, in the case of a multi-byte element
1751   // splatted with a v16i8 mask.
1752   for (unsigned i = 1; i != EltSize; ++i)
1753     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1754       return false;
1755 
1756   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1757     if (N->getMaskElt(i) < 0) continue;
1758     for (unsigned j = 0; j != EltSize; ++j)
1759       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1760         return false;
1761   }
1762   return true;
1763 }
1764 
1765 /// Check that the mask is shuffling N byte elements. Within each N byte
1766 /// element of the mask, the indices could be either in increasing or
1767 /// decreasing order as long as they are consecutive.
1768 /// \param[in] N the shuffle vector SD Node to analyze
1769 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1770 /// Word/DoubleWord/QuadWord).
1771 /// \param[in] StepLen the delta indices number among the N byte element, if
1772 /// the mask is in increasing/decreasing order then it is 1/-1.
1773 /// \return true iff the mask is shuffling N byte elements.
1774 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1775                                    int StepLen) {
1776   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1777          "Unexpected element width.");
1778   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1779 
1780   unsigned NumOfElem = 16 / Width;
1781   unsigned MaskVal[16]; //  Width is never greater than 16
1782   for (unsigned i = 0; i < NumOfElem; ++i) {
1783     MaskVal[0] = N->getMaskElt(i * Width);
1784     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1785       return false;
1786     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1787       return false;
1788     }
1789 
1790     for (unsigned int j = 1; j < Width; ++j) {
1791       MaskVal[j] = N->getMaskElt(i * Width + j);
1792       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1793         return false;
1794       }
1795     }
1796   }
1797 
1798   return true;
1799 }
1800 
1801 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1802                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1803   if (!isNByteElemShuffleMask(N, 4, 1))
1804     return false;
1805 
1806   // Now we look at mask elements 0,4,8,12
1807   unsigned M0 = N->getMaskElt(0) / 4;
1808   unsigned M1 = N->getMaskElt(4) / 4;
1809   unsigned M2 = N->getMaskElt(8) / 4;
1810   unsigned M3 = N->getMaskElt(12) / 4;
1811   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1812   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1813 
1814   // Below, let H and L be arbitrary elements of the shuffle mask
1815   // where H is in the range [4,7] and L is in the range [0,3].
1816   // H, 1, 2, 3 or L, 5, 6, 7
1817   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1818       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1819     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1820     InsertAtByte = IsLE ? 12 : 0;
1821     Swap = M0 < 4;
1822     return true;
1823   }
1824   // 0, H, 2, 3 or 4, L, 6, 7
1825   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1826       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1827     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1828     InsertAtByte = IsLE ? 8 : 4;
1829     Swap = M1 < 4;
1830     return true;
1831   }
1832   // 0, 1, H, 3 or 4, 5, L, 7
1833   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1834       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1835     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1836     InsertAtByte = IsLE ? 4 : 8;
1837     Swap = M2 < 4;
1838     return true;
1839   }
1840   // 0, 1, 2, H or 4, 5, 6, L
1841   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1842       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1843     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1844     InsertAtByte = IsLE ? 0 : 12;
1845     Swap = M3 < 4;
1846     return true;
1847   }
1848 
1849   // If both vector operands for the shuffle are the same vector, the mask will
1850   // contain only elements from the first one and the second one will be undef.
1851   if (N->getOperand(1).isUndef()) {
1852     ShiftElts = 0;
1853     Swap = true;
1854     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1855     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1856       InsertAtByte = IsLE ? 12 : 0;
1857       return true;
1858     }
1859     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1860       InsertAtByte = IsLE ? 8 : 4;
1861       return true;
1862     }
1863     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1864       InsertAtByte = IsLE ? 4 : 8;
1865       return true;
1866     }
1867     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1868       InsertAtByte = IsLE ? 0 : 12;
1869       return true;
1870     }
1871   }
1872 
1873   return false;
1874 }
1875 
1876 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1877                                bool &Swap, bool IsLE) {
1878   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1879   // Ensure each byte index of the word is consecutive.
1880   if (!isNByteElemShuffleMask(N, 4, 1))
1881     return false;
1882 
1883   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1884   unsigned M0 = N->getMaskElt(0) / 4;
1885   unsigned M1 = N->getMaskElt(4) / 4;
1886   unsigned M2 = N->getMaskElt(8) / 4;
1887   unsigned M3 = N->getMaskElt(12) / 4;
1888 
1889   // If both vector operands for the shuffle are the same vector, the mask will
1890   // contain only elements from the first one and the second one will be undef.
1891   if (N->getOperand(1).isUndef()) {
1892     assert(M0 < 4 && "Indexing into an undef vector?");
1893     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1894       return false;
1895 
1896     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1897     Swap = false;
1898     return true;
1899   }
1900 
1901   // Ensure each word index of the ShuffleVector Mask is consecutive.
1902   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1903     return false;
1904 
1905   if (IsLE) {
1906     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1907       // Input vectors don't need to be swapped if the leading element
1908       // of the result is one of the 3 left elements of the second vector
1909       // (or if there is no shift to be done at all).
1910       Swap = false;
1911       ShiftElts = (8 - M0) % 8;
1912     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1913       // Input vectors need to be swapped if the leading element
1914       // of the result is one of the 3 left elements of the first vector
1915       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1916       Swap = true;
1917       ShiftElts = (4 - M0) % 4;
1918     }
1919 
1920     return true;
1921   } else {                                          // BE
1922     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1923       // Input vectors don't need to be swapped if the leading element
1924       // of the result is one of the 4 elements of the first vector.
1925       Swap = false;
1926       ShiftElts = M0;
1927     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1928       // Input vectors need to be swapped if the leading element
1929       // of the result is one of the 4 elements of the right vector.
1930       Swap = true;
1931       ShiftElts = M0 - 4;
1932     }
1933 
1934     return true;
1935   }
1936 }
1937 
1938 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1939   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1940 
1941   if (!isNByteElemShuffleMask(N, Width, -1))
1942     return false;
1943 
1944   for (int i = 0; i < 16; i += Width)
1945     if (N->getMaskElt(i) != i + Width - 1)
1946       return false;
1947 
1948   return true;
1949 }
1950 
1951 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1952   return isXXBRShuffleMaskHelper(N, 2);
1953 }
1954 
1955 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1956   return isXXBRShuffleMaskHelper(N, 4);
1957 }
1958 
1959 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1960   return isXXBRShuffleMaskHelper(N, 8);
1961 }
1962 
1963 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1964   return isXXBRShuffleMaskHelper(N, 16);
1965 }
1966 
1967 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1968 /// if the inputs to the instruction should be swapped and set \p DM to the
1969 /// value for the immediate.
1970 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1971 /// AND element 0 of the result comes from the first input (LE) or second input
1972 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1973 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1974 /// mask.
1975 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
1976                                bool &Swap, bool IsLE) {
1977   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1978 
1979   // Ensure each byte index of the double word is consecutive.
1980   if (!isNByteElemShuffleMask(N, 8, 1))
1981     return false;
1982 
1983   unsigned M0 = N->getMaskElt(0) / 8;
1984   unsigned M1 = N->getMaskElt(8) / 8;
1985   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1986 
1987   // If both vector operands for the shuffle are the same vector, the mask will
1988   // contain only elements from the first one and the second one will be undef.
1989   if (N->getOperand(1).isUndef()) {
1990     if ((M0 | M1) < 2) {
1991       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1992       Swap = false;
1993       return true;
1994     } else
1995       return false;
1996   }
1997 
1998   if (IsLE) {
1999     if (M0 > 1 && M1 < 2) {
2000       Swap = false;
2001     } else if (M0 < 2 && M1 > 1) {
2002       M0 = (M0 + 2) % 4;
2003       M1 = (M1 + 2) % 4;
2004       Swap = true;
2005     } else
2006       return false;
2007 
2008     // Note: if control flow comes here that means Swap is already set above
2009     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2010     return true;
2011   } else { // BE
2012     if (M0 < 2 && M1 > 1) {
2013       Swap = false;
2014     } else if (M0 > 1 && M1 < 2) {
2015       M0 = (M0 + 2) % 4;
2016       M1 = (M1 + 2) % 4;
2017       Swap = true;
2018     } else
2019       return false;
2020 
2021     // Note: if control flow comes here that means Swap is already set above
2022     DM = (M0 << 1) + (M1 & 1);
2023     return true;
2024   }
2025 }
2026 
2027 
2028 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2029 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2030 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2031                                 SelectionDAG &DAG) {
2032   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2033   assert(isSplatShuffleMask(SVOp, EltSize));
2034   if (DAG.getDataLayout().isLittleEndian())
2035     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2036   else
2037     return SVOp->getMaskElt(0) / EltSize;
2038 }
2039 
2040 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2041 /// by using a vspltis[bhw] instruction of the specified element size, return
2042 /// the constant being splatted.  The ByteSize field indicates the number of
2043 /// bytes of each element [124] -> [bhw].
2044 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2045   SDValue OpVal(nullptr, 0);
2046 
2047   // If ByteSize of the splat is bigger than the element size of the
2048   // build_vector, then we have a case where we are checking for a splat where
2049   // multiple elements of the buildvector are folded together into a single
2050   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2051   unsigned EltSize = 16/N->getNumOperands();
2052   if (EltSize < ByteSize) {
2053     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2054     SDValue UniquedVals[4];
2055     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2056 
2057     // See if all of the elements in the buildvector agree across.
2058     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2059       if (N->getOperand(i).isUndef()) continue;
2060       // If the element isn't a constant, bail fully out.
2061       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2062 
2063       if (!UniquedVals[i&(Multiple-1)].getNode())
2064         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2065       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2066         return SDValue();  // no match.
2067     }
2068 
2069     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2070     // either constant or undef values that are identical for each chunk.  See
2071     // if these chunks can form into a larger vspltis*.
2072 
2073     // Check to see if all of the leading entries are either 0 or -1.  If
2074     // neither, then this won't fit into the immediate field.
2075     bool LeadingZero = true;
2076     bool LeadingOnes = true;
2077     for (unsigned i = 0; i != Multiple-1; ++i) {
2078       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2079 
2080       LeadingZero &= isNullConstant(UniquedVals[i]);
2081       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2082     }
2083     // Finally, check the least significant entry.
2084     if (LeadingZero) {
2085       if (!UniquedVals[Multiple-1].getNode())
2086         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2087       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2088       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2089         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2090     }
2091     if (LeadingOnes) {
2092       if (!UniquedVals[Multiple-1].getNode())
2093         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2094       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2095       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2096         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2097     }
2098 
2099     return SDValue();
2100   }
2101 
2102   // Check to see if this buildvec has a single non-undef value in its elements.
2103   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2104     if (N->getOperand(i).isUndef()) continue;
2105     if (!OpVal.getNode())
2106       OpVal = N->getOperand(i);
2107     else if (OpVal != N->getOperand(i))
2108       return SDValue();
2109   }
2110 
2111   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2112 
2113   unsigned ValSizeInBytes = EltSize;
2114   uint64_t Value = 0;
2115   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2116     Value = CN->getZExtValue();
2117   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2118     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2119     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2120   }
2121 
2122   // If the splat value is larger than the element value, then we can never do
2123   // this splat.  The only case that we could fit the replicated bits into our
2124   // immediate field for would be zero, and we prefer to use vxor for it.
2125   if (ValSizeInBytes < ByteSize) return SDValue();
2126 
2127   // If the element value is larger than the splat value, check if it consists
2128   // of a repeated bit pattern of size ByteSize.
2129   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2130     return SDValue();
2131 
2132   // Properly sign extend the value.
2133   int MaskVal = SignExtend32(Value, ByteSize * 8);
2134 
2135   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2136   if (MaskVal == 0) return SDValue();
2137 
2138   // Finally, if this value fits in a 5 bit sext field, return it
2139   if (SignExtend32<5>(MaskVal) == MaskVal)
2140     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2141   return SDValue();
2142 }
2143 
2144 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2145 /// amount, otherwise return -1.
2146 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2147   EVT VT = N->getValueType(0);
2148   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2149     return -1;
2150 
2151   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2152 
2153   // Find the first non-undef value in the shuffle mask.
2154   unsigned i;
2155   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2156     /*search*/;
2157 
2158   if (i == 4) return -1;  // all undef.
2159 
2160   // Otherwise, check to see if the rest of the elements are consecutively
2161   // numbered from this value.
2162   unsigned ShiftAmt = SVOp->getMaskElt(i);
2163   if (ShiftAmt < i) return -1;
2164   ShiftAmt -= i;
2165 
2166   // Check the rest of the elements to see if they are consecutive.
2167   for (++i; i != 4; ++i)
2168     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2169       return -1;
2170 
2171   return ShiftAmt;
2172 }
2173 
2174 //===----------------------------------------------------------------------===//
2175 //  Addressing Mode Selection
2176 //===----------------------------------------------------------------------===//
2177 
2178 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2179 /// or 64-bit immediate, and if the value can be accurately represented as a
2180 /// sign extension from a 16-bit value.  If so, this returns true and the
2181 /// immediate.
2182 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2183   if (!isa<ConstantSDNode>(N))
2184     return false;
2185 
2186   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2187   if (N->getValueType(0) == MVT::i32)
2188     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2189   else
2190     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2191 }
2192 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2193   return isIntS16Immediate(Op.getNode(), Imm);
2194 }
2195 
2196 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2197 /// can be represented as an indexed [r+r] operation.  Returns false if it
2198 /// can be more efficiently represented with [r+imm].
2199 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2200                                             SDValue &Index,
2201                                             SelectionDAG &DAG) const {
2202   int16_t imm = 0;
2203   if (N.getOpcode() == ISD::ADD) {
2204     if (isIntS16Immediate(N.getOperand(1), imm))
2205       return false;    // r+i
2206     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2207       return false;    // r+i
2208 
2209     Base = N.getOperand(0);
2210     Index = N.getOperand(1);
2211     return true;
2212   } else if (N.getOpcode() == ISD::OR) {
2213     if (isIntS16Immediate(N.getOperand(1), imm))
2214       return false;    // r+i can fold it if we can.
2215 
2216     // If this is an or of disjoint bitfields, we can codegen this as an add
2217     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2218     // disjoint.
2219     KnownBits LHSKnown, RHSKnown;
2220     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2221 
2222     if (LHSKnown.Zero.getBoolValue()) {
2223       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2224       // If all of the bits are known zero on the LHS or RHS, the add won't
2225       // carry.
2226       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2227         Base = N.getOperand(0);
2228         Index = N.getOperand(1);
2229         return true;
2230       }
2231     }
2232   }
2233 
2234   return false;
2235 }
2236 
2237 // If we happen to be doing an i64 load or store into a stack slot that has
2238 // less than a 4-byte alignment, then the frame-index elimination may need to
2239 // use an indexed load or store instruction (because the offset may not be a
2240 // multiple of 4). The extra register needed to hold the offset comes from the
2241 // register scavenger, and it is possible that the scavenger will need to use
2242 // an emergency spill slot. As a result, we need to make sure that a spill slot
2243 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2244 // stack slot.
2245 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2246   // FIXME: This does not handle the LWA case.
2247   if (VT != MVT::i64)
2248     return;
2249 
2250   // NOTE: We'll exclude negative FIs here, which come from argument
2251   // lowering, because there are no known test cases triggering this problem
2252   // using packed structures (or similar). We can remove this exclusion if
2253   // we find such a test case. The reason why this is so test-case driven is
2254   // because this entire 'fixup' is only to prevent crashes (from the
2255   // register scavenger) on not-really-valid inputs. For example, if we have:
2256   //   %a = alloca i1
2257   //   %b = bitcast i1* %a to i64*
2258   //   store i64* a, i64 b
2259   // then the store should really be marked as 'align 1', but is not. If it
2260   // were marked as 'align 1' then the indexed form would have been
2261   // instruction-selected initially, and the problem this 'fixup' is preventing
2262   // won't happen regardless.
2263   if (FrameIdx < 0)
2264     return;
2265 
2266   MachineFunction &MF = DAG.getMachineFunction();
2267   MachineFrameInfo &MFI = MF.getFrameInfo();
2268 
2269   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2270   if (Align >= 4)
2271     return;
2272 
2273   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2274   FuncInfo->setHasNonRISpills();
2275 }
2276 
2277 /// Returns true if the address N can be represented by a base register plus
2278 /// a signed 16-bit displacement [r+imm], and if it is not better
2279 /// represented as reg+reg.  If \p Alignment is non-zero, only accept
2280 /// displacements that are multiples of that value.
2281 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2282                                             SDValue &Base,
2283                                             SelectionDAG &DAG,
2284                                             unsigned Alignment) const {
2285   // FIXME dl should come from parent load or store, not from address
2286   SDLoc dl(N);
2287   // If this can be more profitably realized as r+r, fail.
2288   if (SelectAddressRegReg(N, Disp, Base, DAG))
2289     return false;
2290 
2291   if (N.getOpcode() == ISD::ADD) {
2292     int16_t imm = 0;
2293     if (isIntS16Immediate(N.getOperand(1), imm) &&
2294         (!Alignment || (imm % Alignment) == 0)) {
2295       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2296       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2297         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2298         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2299       } else {
2300         Base = N.getOperand(0);
2301       }
2302       return true; // [r+i]
2303     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2304       // Match LOAD (ADD (X, Lo(G))).
2305       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2306              && "Cannot handle constant offsets yet!");
2307       Disp = N.getOperand(1).getOperand(0);  // The global address.
2308       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2309              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2310              Disp.getOpcode() == ISD::TargetConstantPool ||
2311              Disp.getOpcode() == ISD::TargetJumpTable);
2312       Base = N.getOperand(0);
2313       return true;  // [&g+r]
2314     }
2315   } else if (N.getOpcode() == ISD::OR) {
2316     int16_t imm = 0;
2317     if (isIntS16Immediate(N.getOperand(1), imm) &&
2318         (!Alignment || (imm % Alignment) == 0)) {
2319       // If this is an or of disjoint bitfields, we can codegen this as an add
2320       // (for better address arithmetic) if the LHS and RHS of the OR are
2321       // provably disjoint.
2322       KnownBits LHSKnown;
2323       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2324 
2325       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2326         // If all of the bits are known zero on the LHS or RHS, the add won't
2327         // carry.
2328         if (FrameIndexSDNode *FI =
2329               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2330           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2331           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2332         } else {
2333           Base = N.getOperand(0);
2334         }
2335         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2336         return true;
2337       }
2338     }
2339   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2340     // Loading from a constant address.
2341 
2342     // If this address fits entirely in a 16-bit sext immediate field, codegen
2343     // this as "d, 0"
2344     int16_t Imm;
2345     if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2346       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2347       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2348                              CN->getValueType(0));
2349       return true;
2350     }
2351 
2352     // Handle 32-bit sext immediates with LIS + addr mode.
2353     if ((CN->getValueType(0) == MVT::i32 ||
2354          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2355         (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2356       int Addr = (int)CN->getZExtValue();
2357 
2358       // Otherwise, break this down into an LIS + disp.
2359       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2360 
2361       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2362                                    MVT::i32);
2363       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2364       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2365       return true;
2366     }
2367   }
2368 
2369   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2370   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2371     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2372     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2373   } else
2374     Base = N;
2375   return true;      // [r+0]
2376 }
2377 
2378 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2379 /// represented as an indexed [r+r] operation.
2380 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2381                                                 SDValue &Index,
2382                                                 SelectionDAG &DAG) const {
2383   // Check to see if we can easily represent this as an [r+r] address.  This
2384   // will fail if it thinks that the address is more profitably represented as
2385   // reg+imm, e.g. where imm = 0.
2386   if (SelectAddressRegReg(N, Base, Index, DAG))
2387     return true;
2388 
2389   // If the address is the result of an add, we will utilize the fact that the
2390   // address calculation includes an implicit add.  However, we can reduce
2391   // register pressure if we do not materialize a constant just for use as the
2392   // index register.  We only get rid of the add if it is not an add of a
2393   // value and a 16-bit signed constant and both have a single use.
2394   int16_t imm = 0;
2395   if (N.getOpcode() == ISD::ADD &&
2396       (!isIntS16Immediate(N.getOperand(1), imm) ||
2397        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2398     Base = N.getOperand(0);
2399     Index = N.getOperand(1);
2400     return true;
2401   }
2402 
2403   // Otherwise, do it the hard way, using R0 as the base register.
2404   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2405                          N.getValueType());
2406   Index = N;
2407   return true;
2408 }
2409 
2410 /// Returns true if we should use a direct load into vector instruction
2411 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2412 static bool usePartialVectorLoads(SDNode *N) {
2413   if (!N->hasOneUse())
2414     return false;
2415 
2416   // If there are any other uses other than scalar to vector, then we should
2417   // keep it as a scalar load -> direct move pattern to prevent multiple
2418   // loads.  Currently, only check for i64 since we have lxsd/lfd to do this
2419   // efficiently, but no update equivalent.
2420   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2421     EVT MemVT = LD->getMemoryVT();
2422     if (MemVT.isSimple() && MemVT.getSimpleVT().SimpleTy == MVT::i64) {
2423       SDNode *User = *(LD->use_begin());
2424       if (User->getOpcode() == ISD::SCALAR_TO_VECTOR)
2425         return true;
2426     }
2427   }
2428 
2429   return false;
2430 }
2431 
2432 /// getPreIndexedAddressParts - returns true by value, base pointer and
2433 /// offset pointer and addressing mode by reference if the node's address
2434 /// can be legally represented as pre-indexed load / store address.
2435 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2436                                                   SDValue &Offset,
2437                                                   ISD::MemIndexedMode &AM,
2438                                                   SelectionDAG &DAG) const {
2439   if (DisablePPCPreinc) return false;
2440 
2441   bool isLoad = true;
2442   SDValue Ptr;
2443   EVT VT;
2444   unsigned Alignment;
2445   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2446     Ptr = LD->getBasePtr();
2447     VT = LD->getMemoryVT();
2448     Alignment = LD->getAlignment();
2449   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2450     Ptr = ST->getBasePtr();
2451     VT  = ST->getMemoryVT();
2452     Alignment = ST->getAlignment();
2453     isLoad = false;
2454   } else
2455     return false;
2456 
2457   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2458   // instructions because we can fold these into a more efficient instruction
2459   // instead, (such as LXSD).
2460   if (isLoad && usePartialVectorLoads(N)) {
2461     return false;
2462   }
2463 
2464   // PowerPC doesn't have preinc load/store instructions for vectors (except
2465   // for QPX, which does have preinc r+r forms).
2466   if (VT.isVector()) {
2467     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2468       return false;
2469     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2470       AM = ISD::PRE_INC;
2471       return true;
2472     }
2473   }
2474 
2475   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2476     // Common code will reject creating a pre-inc form if the base pointer
2477     // is a frame index, or if N is a store and the base pointer is either
2478     // the same as or a predecessor of the value being stored.  Check for
2479     // those situations here, and try with swapped Base/Offset instead.
2480     bool Swap = false;
2481 
2482     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2483       Swap = true;
2484     else if (!isLoad) {
2485       SDValue Val = cast<StoreSDNode>(N)->getValue();
2486       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2487         Swap = true;
2488     }
2489 
2490     if (Swap)
2491       std::swap(Base, Offset);
2492 
2493     AM = ISD::PRE_INC;
2494     return true;
2495   }
2496 
2497   // LDU/STU can only handle immediates that are a multiple of 4.
2498   if (VT != MVT::i64) {
2499     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2500       return false;
2501   } else {
2502     // LDU/STU need an address with at least 4-byte alignment.
2503     if (Alignment < 4)
2504       return false;
2505 
2506     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2507       return false;
2508   }
2509 
2510   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2511     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2512     // sext i32 to i64 when addr mode is r+i.
2513     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2514         LD->getExtensionType() == ISD::SEXTLOAD &&
2515         isa<ConstantSDNode>(Offset))
2516       return false;
2517   }
2518 
2519   AM = ISD::PRE_INC;
2520   return true;
2521 }
2522 
2523 //===----------------------------------------------------------------------===//
2524 //  LowerOperation implementation
2525 //===----------------------------------------------------------------------===//
2526 
2527 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2528 /// and LoOpFlags to the target MO flags.
2529 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2530                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2531                                const GlobalValue *GV = nullptr) {
2532   HiOpFlags = PPCII::MO_HA;
2533   LoOpFlags = PPCII::MO_LO;
2534 
2535   // Don't use the pic base if not in PIC relocation model.
2536   if (IsPIC) {
2537     HiOpFlags |= PPCII::MO_PIC_FLAG;
2538     LoOpFlags |= PPCII::MO_PIC_FLAG;
2539   }
2540 
2541   // If this is a reference to a global value that requires a non-lazy-ptr, make
2542   // sure that instruction lowering adds it.
2543   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2544     HiOpFlags |= PPCII::MO_NLP_FLAG;
2545     LoOpFlags |= PPCII::MO_NLP_FLAG;
2546 
2547     if (GV->hasHiddenVisibility()) {
2548       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2549       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2550     }
2551   }
2552 }
2553 
2554 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2555                              SelectionDAG &DAG) {
2556   SDLoc DL(HiPart);
2557   EVT PtrVT = HiPart.getValueType();
2558   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2559 
2560   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2561   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2562 
2563   // With PIC, the first instruction is actually "GR+hi(&G)".
2564   if (isPIC)
2565     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2566                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2567 
2568   // Generate non-pic code that has direct accesses to the constant pool.
2569   // The address of the global is just (hi(&g)+lo(&g)).
2570   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2571 }
2572 
2573 static void setUsesTOCBasePtr(MachineFunction &MF) {
2574   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2575   FuncInfo->setUsesTOCBasePtr();
2576 }
2577 
2578 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2579   setUsesTOCBasePtr(DAG.getMachineFunction());
2580 }
2581 
2582 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2583                            SDValue GA) {
2584   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2585   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2586                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2587 
2588   SDValue Ops[] = { GA, Reg };
2589   return DAG.getMemIntrinsicNode(
2590       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2591       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2592       MachineMemOperand::MOLoad);
2593 }
2594 
2595 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2596                                              SelectionDAG &DAG) const {
2597   EVT PtrVT = Op.getValueType();
2598   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2599   const Constant *C = CP->getConstVal();
2600 
2601   // 64-bit SVR4 ABI code is always position-independent.
2602   // The actual address of the GlobalValue is stored in the TOC.
2603   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2604     setUsesTOCBasePtr(DAG);
2605     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2606     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2607   }
2608 
2609   unsigned MOHiFlag, MOLoFlag;
2610   bool IsPIC = isPositionIndependent();
2611   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2612 
2613   if (IsPIC && Subtarget.isSVR4ABI()) {
2614     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2615                                            PPCII::MO_PIC_FLAG);
2616     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2617   }
2618 
2619   SDValue CPIHi =
2620     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2621   SDValue CPILo =
2622     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2623   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2624 }
2625 
2626 // For 64-bit PowerPC, prefer the more compact relative encodings.
2627 // This trades 32 bits per jump table entry for one or two instructions
2628 // on the jump site.
2629 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2630   if (isJumpTableRelative())
2631     return MachineJumpTableInfo::EK_LabelDifference32;
2632 
2633   return TargetLowering::getJumpTableEncoding();
2634 }
2635 
2636 bool PPCTargetLowering::isJumpTableRelative() const {
2637   if (Subtarget.isPPC64())
2638     return true;
2639   return TargetLowering::isJumpTableRelative();
2640 }
2641 
2642 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2643                                                     SelectionDAG &DAG) const {
2644   if (!Subtarget.isPPC64())
2645     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2646 
2647   switch (getTargetMachine().getCodeModel()) {
2648   case CodeModel::Small:
2649   case CodeModel::Medium:
2650     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2651   default:
2652     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2653                        getPointerTy(DAG.getDataLayout()));
2654   }
2655 }
2656 
2657 const MCExpr *
2658 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2659                                                 unsigned JTI,
2660                                                 MCContext &Ctx) const {
2661   if (!Subtarget.isPPC64())
2662     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2663 
2664   switch (getTargetMachine().getCodeModel()) {
2665   case CodeModel::Small:
2666   case CodeModel::Medium:
2667     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2668   default:
2669     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2670   }
2671 }
2672 
2673 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2674   EVT PtrVT = Op.getValueType();
2675   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2676 
2677   // 64-bit SVR4 ABI code is always position-independent.
2678   // The actual address of the GlobalValue is stored in the TOC.
2679   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2680     setUsesTOCBasePtr(DAG);
2681     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2682     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2683   }
2684 
2685   unsigned MOHiFlag, MOLoFlag;
2686   bool IsPIC = isPositionIndependent();
2687   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2688 
2689   if (IsPIC && Subtarget.isSVR4ABI()) {
2690     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2691                                         PPCII::MO_PIC_FLAG);
2692     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2693   }
2694 
2695   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2696   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2697   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2698 }
2699 
2700 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2701                                              SelectionDAG &DAG) const {
2702   EVT PtrVT = Op.getValueType();
2703   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2704   const BlockAddress *BA = BASDN->getBlockAddress();
2705 
2706   // 64-bit SVR4 ABI code is always position-independent.
2707   // The actual BlockAddress is stored in the TOC.
2708   if (Subtarget.isSVR4ABI() &&
2709       (Subtarget.isPPC64() || isPositionIndependent())) {
2710     if (Subtarget.isPPC64())
2711       setUsesTOCBasePtr(DAG);
2712     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2713     return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2714   }
2715 
2716   unsigned MOHiFlag, MOLoFlag;
2717   bool IsPIC = isPositionIndependent();
2718   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2719   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2720   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2721   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2722 }
2723 
2724 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2725                                               SelectionDAG &DAG) const {
2726   // FIXME: TLS addresses currently use medium model code sequences,
2727   // which is the most useful form.  Eventually support for small and
2728   // large models could be added if users need it, at the cost of
2729   // additional complexity.
2730   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2731   if (DAG.getTarget().useEmulatedTLS())
2732     return LowerToTLSEmulatedModel(GA, DAG);
2733 
2734   SDLoc dl(GA);
2735   const GlobalValue *GV = GA->getGlobal();
2736   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2737   bool is64bit = Subtarget.isPPC64();
2738   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2739   PICLevel::Level picLevel = M->getPICLevel();
2740 
2741   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2742 
2743   if (Model == TLSModel::LocalExec) {
2744     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2745                                                PPCII::MO_TPREL_HA);
2746     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2747                                                PPCII::MO_TPREL_LO);
2748     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2749                              : DAG.getRegister(PPC::R2, MVT::i32);
2750 
2751     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2752     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2753   }
2754 
2755   if (Model == TLSModel::InitialExec) {
2756     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2757     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2758                                                 PPCII::MO_TLS);
2759     SDValue GOTPtr;
2760     if (is64bit) {
2761       setUsesTOCBasePtr(DAG);
2762       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2763       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2764                            PtrVT, GOTReg, TGA);
2765     } else
2766       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2767     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2768                                    PtrVT, TGA, GOTPtr);
2769     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2770   }
2771 
2772   if (Model == TLSModel::GeneralDynamic) {
2773     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2774     SDValue GOTPtr;
2775     if (is64bit) {
2776       setUsesTOCBasePtr(DAG);
2777       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2778       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2779                                    GOTReg, TGA);
2780     } else {
2781       if (picLevel == PICLevel::SmallPIC)
2782         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2783       else
2784         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2785     }
2786     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2787                        GOTPtr, TGA, TGA);
2788   }
2789 
2790   if (Model == TLSModel::LocalDynamic) {
2791     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2792     SDValue GOTPtr;
2793     if (is64bit) {
2794       setUsesTOCBasePtr(DAG);
2795       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2796       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2797                            GOTReg, TGA);
2798     } else {
2799       if (picLevel == PICLevel::SmallPIC)
2800         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2801       else
2802         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2803     }
2804     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2805                                   PtrVT, GOTPtr, TGA, TGA);
2806     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2807                                       PtrVT, TLSAddr, TGA);
2808     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2809   }
2810 
2811   llvm_unreachable("Unknown TLS model!");
2812 }
2813 
2814 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2815                                               SelectionDAG &DAG) const {
2816   EVT PtrVT = Op.getValueType();
2817   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2818   SDLoc DL(GSDN);
2819   const GlobalValue *GV = GSDN->getGlobal();
2820 
2821   // 64-bit SVR4 ABI code is always position-independent.
2822   // The actual address of the GlobalValue is stored in the TOC.
2823   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2824     setUsesTOCBasePtr(DAG);
2825     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2826     return getTOCEntry(DAG, DL, true, GA);
2827   }
2828 
2829   unsigned MOHiFlag, MOLoFlag;
2830   bool IsPIC = isPositionIndependent();
2831   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2832 
2833   if (IsPIC && Subtarget.isSVR4ABI()) {
2834     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2835                                             GSDN->getOffset(),
2836                                             PPCII::MO_PIC_FLAG);
2837     return getTOCEntry(DAG, DL, false, GA);
2838   }
2839 
2840   SDValue GAHi =
2841     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2842   SDValue GALo =
2843     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2844 
2845   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2846 
2847   // If the global reference is actually to a non-lazy-pointer, we have to do an
2848   // extra load to get the address of the global.
2849   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2850     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2851   return Ptr;
2852 }
2853 
2854 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2855   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2856   SDLoc dl(Op);
2857 
2858   if (Op.getValueType() == MVT::v2i64) {
2859     // When the operands themselves are v2i64 values, we need to do something
2860     // special because VSX has no underlying comparison operations for these.
2861     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2862       // Equality can be handled by casting to the legal type for Altivec
2863       // comparisons, everything else needs to be expanded.
2864       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2865         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2866                  DAG.getSetCC(dl, MVT::v4i32,
2867                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2868                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2869                    CC));
2870       }
2871 
2872       return SDValue();
2873     }
2874 
2875     // We handle most of these in the usual way.
2876     return Op;
2877   }
2878 
2879   // If we're comparing for equality to zero, expose the fact that this is
2880   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2881   // fold the new nodes.
2882   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2883     return V;
2884 
2885   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2886     // Leave comparisons against 0 and -1 alone for now, since they're usually
2887     // optimized.  FIXME: revisit this when we can custom lower all setcc
2888     // optimizations.
2889     if (C->isAllOnesValue() || C->isNullValue())
2890       return SDValue();
2891   }
2892 
2893   // If we have an integer seteq/setne, turn it into a compare against zero
2894   // by xor'ing the rhs with the lhs, which is faster than setting a
2895   // condition register, reading it back out, and masking the correct bit.  The
2896   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2897   // the result to other bit-twiddling opportunities.
2898   EVT LHSVT = Op.getOperand(0).getValueType();
2899   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2900     EVT VT = Op.getValueType();
2901     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2902                                 Op.getOperand(1));
2903     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2904   }
2905   return SDValue();
2906 }
2907 
2908 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2909   SDNode *Node = Op.getNode();
2910   EVT VT = Node->getValueType(0);
2911   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2912   SDValue InChain = Node->getOperand(0);
2913   SDValue VAListPtr = Node->getOperand(1);
2914   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2915   SDLoc dl(Node);
2916 
2917   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2918 
2919   // gpr_index
2920   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2921                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2922   InChain = GprIndex.getValue(1);
2923 
2924   if (VT == MVT::i64) {
2925     // Check if GprIndex is even
2926     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2927                                  DAG.getConstant(1, dl, MVT::i32));
2928     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2929                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2930     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2931                                           DAG.getConstant(1, dl, MVT::i32));
2932     // Align GprIndex to be even if it isn't
2933     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2934                            GprIndex);
2935   }
2936 
2937   // fpr index is 1 byte after gpr
2938   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2939                                DAG.getConstant(1, dl, MVT::i32));
2940 
2941   // fpr
2942   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2943                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2944   InChain = FprIndex.getValue(1);
2945 
2946   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2947                                        DAG.getConstant(8, dl, MVT::i32));
2948 
2949   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2950                                         DAG.getConstant(4, dl, MVT::i32));
2951 
2952   // areas
2953   SDValue OverflowArea =
2954       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2955   InChain = OverflowArea.getValue(1);
2956 
2957   SDValue RegSaveArea =
2958       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2959   InChain = RegSaveArea.getValue(1);
2960 
2961   // select overflow_area if index > 8
2962   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2963                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2964 
2965   // adjustment constant gpr_index * 4/8
2966   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2967                                     VT.isInteger() ? GprIndex : FprIndex,
2968                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2969                                                     MVT::i32));
2970 
2971   // OurReg = RegSaveArea + RegConstant
2972   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2973                                RegConstant);
2974 
2975   // Floating types are 32 bytes into RegSaveArea
2976   if (VT.isFloatingPoint())
2977     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2978                          DAG.getConstant(32, dl, MVT::i32));
2979 
2980   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2981   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2982                                    VT.isInteger() ? GprIndex : FprIndex,
2983                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2984                                                    MVT::i32));
2985 
2986   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2987                               VT.isInteger() ? VAListPtr : FprPtr,
2988                               MachinePointerInfo(SV), MVT::i8);
2989 
2990   // determine if we should load from reg_save_area or overflow_area
2991   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2992 
2993   // increase overflow_area by 4/8 if gpr/fpr > 8
2994   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2995                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2996                                           dl, MVT::i32));
2997 
2998   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2999                              OverflowAreaPlusN);
3000 
3001   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3002                               MachinePointerInfo(), MVT::i32);
3003 
3004   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3005 }
3006 
3007 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3008   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3009 
3010   // We have to copy the entire va_list struct:
3011   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3012   return DAG.getMemcpy(Op.getOperand(0), Op,
3013                        Op.getOperand(1), Op.getOperand(2),
3014                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3015                        false, MachinePointerInfo(), MachinePointerInfo());
3016 }
3017 
3018 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3019                                                   SelectionDAG &DAG) const {
3020   return Op.getOperand(0);
3021 }
3022 
3023 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3024                                                 SelectionDAG &DAG) const {
3025   SDValue Chain = Op.getOperand(0);
3026   SDValue Trmp = Op.getOperand(1); // trampoline
3027   SDValue FPtr = Op.getOperand(2); // nested function
3028   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3029   SDLoc dl(Op);
3030 
3031   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3032   bool isPPC64 = (PtrVT == MVT::i64);
3033   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3034 
3035   TargetLowering::ArgListTy Args;
3036   TargetLowering::ArgListEntry Entry;
3037 
3038   Entry.Ty = IntPtrTy;
3039   Entry.Node = Trmp; Args.push_back(Entry);
3040 
3041   // TrampSize == (isPPC64 ? 48 : 40);
3042   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3043                                isPPC64 ? MVT::i64 : MVT::i32);
3044   Args.push_back(Entry);
3045 
3046   Entry.Node = FPtr; Args.push_back(Entry);
3047   Entry.Node = Nest; Args.push_back(Entry);
3048 
3049   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3050   TargetLowering::CallLoweringInfo CLI(DAG);
3051   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3052       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3053       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3054 
3055   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3056   return CallResult.second;
3057 }
3058 
3059 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3060   MachineFunction &MF = DAG.getMachineFunction();
3061   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3062   EVT PtrVT = getPointerTy(MF.getDataLayout());
3063 
3064   SDLoc dl(Op);
3065 
3066   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3067     // vastart just stores the address of the VarArgsFrameIndex slot into the
3068     // memory location argument.
3069     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3070     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3071     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3072                         MachinePointerInfo(SV));
3073   }
3074 
3075   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3076   // We suppose the given va_list is already allocated.
3077   //
3078   // typedef struct {
3079   //  char gpr;     /* index into the array of 8 GPRs
3080   //                 * stored in the register save area
3081   //                 * gpr=0 corresponds to r3,
3082   //                 * gpr=1 to r4, etc.
3083   //                 */
3084   //  char fpr;     /* index into the array of 8 FPRs
3085   //                 * stored in the register save area
3086   //                 * fpr=0 corresponds to f1,
3087   //                 * fpr=1 to f2, etc.
3088   //                 */
3089   //  char *overflow_arg_area;
3090   //                /* location on stack that holds
3091   //                 * the next overflow argument
3092   //                 */
3093   //  char *reg_save_area;
3094   //               /* where r3:r10 and f1:f8 (if saved)
3095   //                * are stored
3096   //                */
3097   // } va_list[1];
3098 
3099   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3100   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3101   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3102                                             PtrVT);
3103   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3104                                  PtrVT);
3105 
3106   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3107   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3108 
3109   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3110   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3111 
3112   uint64_t FPROffset = 1;
3113   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3114 
3115   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3116 
3117   // Store first byte : number of int regs
3118   SDValue firstStore =
3119       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3120                         MachinePointerInfo(SV), MVT::i8);
3121   uint64_t nextOffset = FPROffset;
3122   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3123                                   ConstFPROffset);
3124 
3125   // Store second byte : number of float regs
3126   SDValue secondStore =
3127       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3128                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3129   nextOffset += StackOffset;
3130   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3131 
3132   // Store second word : arguments given on stack
3133   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3134                                     MachinePointerInfo(SV, nextOffset));
3135   nextOffset += FrameOffset;
3136   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3137 
3138   // Store third word : arguments given in registers
3139   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3140                       MachinePointerInfo(SV, nextOffset));
3141 }
3142 
3143 #include "PPCGenCallingConv.inc"
3144 
3145 // Function whose sole purpose is to kill compiler warnings
3146 // stemming from unused functions included from PPCGenCallingConv.inc.
3147 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
3148   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
3149 }
3150 
3151 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
3152                                       CCValAssign::LocInfo &LocInfo,
3153                                       ISD::ArgFlagsTy &ArgFlags,
3154                                       CCState &State) {
3155   return true;
3156 }
3157 
3158 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
3159                                              MVT &LocVT,
3160                                              CCValAssign::LocInfo &LocInfo,
3161                                              ISD::ArgFlagsTy &ArgFlags,
3162                                              CCState &State) {
3163   static const MCPhysReg ArgRegs[] = {
3164     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3165     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3166   };
3167   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3168 
3169   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3170 
3171   // Skip one register if the first unallocated register has an even register
3172   // number and there are still argument registers available which have not been
3173   // allocated yet. RegNum is actually an index into ArgRegs, which means we
3174   // need to skip a register if RegNum is odd.
3175   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3176     State.AllocateReg(ArgRegs[RegNum]);
3177   }
3178 
3179   // Always return false here, as this function only makes sure that the first
3180   // unallocated register has an odd register number and does not actually
3181   // allocate a register for the current argument.
3182   return false;
3183 }
3184 
3185 bool
3186 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
3187                                                   MVT &LocVT,
3188                                                   CCValAssign::LocInfo &LocInfo,
3189                                                   ISD::ArgFlagsTy &ArgFlags,
3190                                                   CCState &State) {
3191   static const MCPhysReg ArgRegs[] = {
3192     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3193     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3194   };
3195   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3196 
3197   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3198   int RegsLeft = NumArgRegs - RegNum;
3199 
3200   // Skip if there is not enough registers left for long double type (4 gpr regs
3201   // in soft float mode) and put long double argument on the stack.
3202   if (RegNum != NumArgRegs && RegsLeft < 4) {
3203     for (int i = 0; i < RegsLeft; i++) {
3204       State.AllocateReg(ArgRegs[RegNum + i]);
3205     }
3206   }
3207 
3208   return false;
3209 }
3210 
3211 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3212                                                MVT &LocVT,
3213                                                CCValAssign::LocInfo &LocInfo,
3214                                                ISD::ArgFlagsTy &ArgFlags,
3215                                                CCState &State) {
3216   static const MCPhysReg ArgRegs[] = {
3217     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3218     PPC::F8
3219   };
3220 
3221   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3222 
3223   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3224 
3225   // If there is only one Floating-point register left we need to put both f64
3226   // values of a split ppc_fp128 value on the stack.
3227   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3228     State.AllocateReg(ArgRegs[RegNum]);
3229   }
3230 
3231   // Always return false here, as this function only makes sure that the two f64
3232   // values a ppc_fp128 value is split into are both passed in registers or both
3233   // passed on the stack and does not actually allocate a register for the
3234   // current argument.
3235   return false;
3236 }
3237 
3238 /// FPR - The set of FP registers that should be allocated for arguments,
3239 /// on Darwin.
3240 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3241                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3242                                 PPC::F11, PPC::F12, PPC::F13};
3243 
3244 /// QFPR - The set of QPX registers that should be allocated for arguments.
3245 static const MCPhysReg QFPR[] = {
3246     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3247     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3248 
3249 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3250 /// the stack.
3251 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3252                                        unsigned PtrByteSize) {
3253   unsigned ArgSize = ArgVT.getStoreSize();
3254   if (Flags.isByVal())
3255     ArgSize = Flags.getByValSize();
3256 
3257   // Round up to multiples of the pointer size, except for array members,
3258   // which are always packed.
3259   if (!Flags.isInConsecutiveRegs())
3260     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3261 
3262   return ArgSize;
3263 }
3264 
3265 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3266 /// on the stack.
3267 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3268                                             ISD::ArgFlagsTy Flags,
3269                                             unsigned PtrByteSize) {
3270   unsigned Align = PtrByteSize;
3271 
3272   // Altivec parameters are padded to a 16 byte boundary.
3273   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3274       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3275       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3276       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3277     Align = 16;
3278   // QPX vector types stored in double-precision are padded to a 32 byte
3279   // boundary.
3280   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3281     Align = 32;
3282 
3283   // ByVal parameters are aligned as requested.
3284   if (Flags.isByVal()) {
3285     unsigned BVAlign = Flags.getByValAlign();
3286     if (BVAlign > PtrByteSize) {
3287       if (BVAlign % PtrByteSize != 0)
3288           llvm_unreachable(
3289             "ByVal alignment is not a multiple of the pointer size");
3290 
3291       Align = BVAlign;
3292     }
3293   }
3294 
3295   // Array members are always packed to their original alignment.
3296   if (Flags.isInConsecutiveRegs()) {
3297     // If the array member was split into multiple registers, the first
3298     // needs to be aligned to the size of the full type.  (Except for
3299     // ppcf128, which is only aligned as its f64 components.)
3300     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3301       Align = OrigVT.getStoreSize();
3302     else
3303       Align = ArgVT.getStoreSize();
3304   }
3305 
3306   return Align;
3307 }
3308 
3309 /// CalculateStackSlotUsed - Return whether this argument will use its
3310 /// stack slot (instead of being passed in registers).  ArgOffset,
3311 /// AvailableFPRs, and AvailableVRs must hold the current argument
3312 /// position, and will be updated to account for this argument.
3313 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3314                                    ISD::ArgFlagsTy Flags,
3315                                    unsigned PtrByteSize,
3316                                    unsigned LinkageSize,
3317                                    unsigned ParamAreaSize,
3318                                    unsigned &ArgOffset,
3319                                    unsigned &AvailableFPRs,
3320                                    unsigned &AvailableVRs, bool HasQPX) {
3321   bool UseMemory = false;
3322 
3323   // Respect alignment of argument on the stack.
3324   unsigned Align =
3325     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3326   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3327   // If there's no space left in the argument save area, we must
3328   // use memory (this check also catches zero-sized arguments).
3329   if (ArgOffset >= LinkageSize + ParamAreaSize)
3330     UseMemory = true;
3331 
3332   // Allocate argument on the stack.
3333   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3334   if (Flags.isInConsecutiveRegsLast())
3335     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3336   // If we overran the argument save area, we must use memory
3337   // (this check catches arguments passed partially in memory)
3338   if (ArgOffset > LinkageSize + ParamAreaSize)
3339     UseMemory = true;
3340 
3341   // However, if the argument is actually passed in an FPR or a VR,
3342   // we don't use memory after all.
3343   if (!Flags.isByVal()) {
3344     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3345         // QPX registers overlap with the scalar FP registers.
3346         (HasQPX && (ArgVT == MVT::v4f32 ||
3347                     ArgVT == MVT::v4f64 ||
3348                     ArgVT == MVT::v4i1)))
3349       if (AvailableFPRs > 0) {
3350         --AvailableFPRs;
3351         return false;
3352       }
3353     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3354         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3355         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3356         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3357       if (AvailableVRs > 0) {
3358         --AvailableVRs;
3359         return false;
3360       }
3361   }
3362 
3363   return UseMemory;
3364 }
3365 
3366 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3367 /// ensure minimum alignment required for target.
3368 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3369                                      unsigned NumBytes) {
3370   unsigned TargetAlign = Lowering->getStackAlignment();
3371   unsigned AlignMask = TargetAlign - 1;
3372   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3373   return NumBytes;
3374 }
3375 
3376 SDValue PPCTargetLowering::LowerFormalArguments(
3377     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3378     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3379     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3380   if (Subtarget.isSVR4ABI()) {
3381     if (Subtarget.isPPC64())
3382       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3383                                          dl, DAG, InVals);
3384     else
3385       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3386                                          dl, DAG, InVals);
3387   } else {
3388     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3389                                        dl, DAG, InVals);
3390   }
3391 }
3392 
3393 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3394     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3395     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3396     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3397 
3398   // 32-bit SVR4 ABI Stack Frame Layout:
3399   //              +-----------------------------------+
3400   //        +-->  |            Back chain             |
3401   //        |     +-----------------------------------+
3402   //        |     | Floating-point register save area |
3403   //        |     +-----------------------------------+
3404   //        |     |    General register save area     |
3405   //        |     +-----------------------------------+
3406   //        |     |          CR save word             |
3407   //        |     +-----------------------------------+
3408   //        |     |         VRSAVE save word          |
3409   //        |     +-----------------------------------+
3410   //        |     |         Alignment padding         |
3411   //        |     +-----------------------------------+
3412   //        |     |     Vector register save area     |
3413   //        |     +-----------------------------------+
3414   //        |     |       Local variable space        |
3415   //        |     +-----------------------------------+
3416   //        |     |        Parameter list area        |
3417   //        |     +-----------------------------------+
3418   //        |     |           LR save word            |
3419   //        |     +-----------------------------------+
3420   // SP-->  +---  |            Back chain             |
3421   //              +-----------------------------------+
3422   //
3423   // Specifications:
3424   //   System V Application Binary Interface PowerPC Processor Supplement
3425   //   AltiVec Technology Programming Interface Manual
3426 
3427   MachineFunction &MF = DAG.getMachineFunction();
3428   MachineFrameInfo &MFI = MF.getFrameInfo();
3429   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3430 
3431   EVT PtrVT = getPointerTy(MF.getDataLayout());
3432   // Potential tail calls could cause overwriting of argument stack slots.
3433   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3434                        (CallConv == CallingConv::Fast));
3435   unsigned PtrByteSize = 4;
3436 
3437   // Assign locations to all of the incoming arguments.
3438   SmallVector<CCValAssign, 16> ArgLocs;
3439   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3440                  *DAG.getContext());
3441 
3442   // Reserve space for the linkage area on the stack.
3443   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3444   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3445   if (useSoftFloat() || hasSPE())
3446     CCInfo.PreAnalyzeFormalArguments(Ins);
3447 
3448   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3449   CCInfo.clearWasPPCF128();
3450 
3451   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3452     CCValAssign &VA = ArgLocs[i];
3453 
3454     // Arguments stored in registers.
3455     if (VA.isRegLoc()) {
3456       const TargetRegisterClass *RC;
3457       EVT ValVT = VA.getValVT();
3458 
3459       switch (ValVT.getSimpleVT().SimpleTy) {
3460         default:
3461           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3462         case MVT::i1:
3463         case MVT::i32:
3464           RC = &PPC::GPRCRegClass;
3465           break;
3466         case MVT::f32:
3467           if (Subtarget.hasP8Vector())
3468             RC = &PPC::VSSRCRegClass;
3469           else if (Subtarget.hasSPE())
3470             RC = &PPC::SPE4RCRegClass;
3471           else
3472             RC = &PPC::F4RCRegClass;
3473           break;
3474         case MVT::f64:
3475           if (Subtarget.hasVSX())
3476             RC = &PPC::VSFRCRegClass;
3477           else if (Subtarget.hasSPE())
3478             RC = &PPC::SPERCRegClass;
3479           else
3480             RC = &PPC::F8RCRegClass;
3481           break;
3482         case MVT::v16i8:
3483         case MVT::v8i16:
3484         case MVT::v4i32:
3485           RC = &PPC::VRRCRegClass;
3486           break;
3487         case MVT::v4f32:
3488           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3489           break;
3490         case MVT::v2f64:
3491         case MVT::v2i64:
3492           RC = &PPC::VRRCRegClass;
3493           break;
3494         case MVT::v4f64:
3495           RC = &PPC::QFRCRegClass;
3496           break;
3497         case MVT::v4i1:
3498           RC = &PPC::QBRCRegClass;
3499           break;
3500       }
3501 
3502       // Transform the arguments stored in physical registers into virtual ones.
3503       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3504       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3505                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3506 
3507       if (ValVT == MVT::i1)
3508         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3509 
3510       InVals.push_back(ArgValue);
3511     } else {
3512       // Argument stored in memory.
3513       assert(VA.isMemLoc());
3514 
3515       // Get the extended size of the argument type in stack
3516       unsigned ArgSize = VA.getLocVT().getStoreSize();
3517       // Get the actual size of the argument type
3518       unsigned ObjSize = VA.getValVT().getStoreSize();
3519       unsigned ArgOffset = VA.getLocMemOffset();
3520       // Stack objects in PPC32 are right justified.
3521       ArgOffset += ArgSize - ObjSize;
3522       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3523 
3524       // Create load nodes to retrieve arguments from the stack.
3525       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3526       InVals.push_back(
3527           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3528     }
3529   }
3530 
3531   // Assign locations to all of the incoming aggregate by value arguments.
3532   // Aggregates passed by value are stored in the local variable space of the
3533   // caller's stack frame, right above the parameter list area.
3534   SmallVector<CCValAssign, 16> ByValArgLocs;
3535   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3536                       ByValArgLocs, *DAG.getContext());
3537 
3538   // Reserve stack space for the allocations in CCInfo.
3539   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3540 
3541   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3542 
3543   // Area that is at least reserved in the caller of this function.
3544   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3545   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3546 
3547   // Set the size that is at least reserved in caller of this function.  Tail
3548   // call optimized function's reserved stack space needs to be aligned so that
3549   // taking the difference between two stack areas will result in an aligned
3550   // stack.
3551   MinReservedArea =
3552       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3553   FuncInfo->setMinReservedArea(MinReservedArea);
3554 
3555   SmallVector<SDValue, 8> MemOps;
3556 
3557   // If the function takes variable number of arguments, make a frame index for
3558   // the start of the first vararg value... for expansion of llvm.va_start.
3559   if (isVarArg) {
3560     static const MCPhysReg GPArgRegs[] = {
3561       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3562       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3563     };
3564     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3565 
3566     static const MCPhysReg FPArgRegs[] = {
3567       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3568       PPC::F8
3569     };
3570     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3571 
3572     if (useSoftFloat() || hasSPE())
3573        NumFPArgRegs = 0;
3574 
3575     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3576     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3577 
3578     // Make room for NumGPArgRegs and NumFPArgRegs.
3579     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3580                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3581 
3582     FuncInfo->setVarArgsStackOffset(
3583       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3584                             CCInfo.getNextStackOffset(), true));
3585 
3586     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3587     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3588 
3589     // The fixed integer arguments of a variadic function are stored to the
3590     // VarArgsFrameIndex on the stack so that they may be loaded by
3591     // dereferencing the result of va_next.
3592     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3593       // Get an existing live-in vreg, or add a new one.
3594       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3595       if (!VReg)
3596         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3597 
3598       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3599       SDValue Store =
3600           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3601       MemOps.push_back(Store);
3602       // Increment the address by four for the next argument to store
3603       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3604       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3605     }
3606 
3607     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3608     // is set.
3609     // The double arguments are stored to the VarArgsFrameIndex
3610     // on the stack.
3611     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3612       // Get an existing live-in vreg, or add a new one.
3613       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3614       if (!VReg)
3615         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3616 
3617       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3618       SDValue Store =
3619           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3620       MemOps.push_back(Store);
3621       // Increment the address by eight for the next argument to store
3622       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3623                                          PtrVT);
3624       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3625     }
3626   }
3627 
3628   if (!MemOps.empty())
3629     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3630 
3631   return Chain;
3632 }
3633 
3634 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3635 // value to MVT::i64 and then truncate to the correct register size.
3636 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3637                                              EVT ObjectVT, SelectionDAG &DAG,
3638                                              SDValue ArgVal,
3639                                              const SDLoc &dl) const {
3640   if (Flags.isSExt())
3641     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3642                          DAG.getValueType(ObjectVT));
3643   else if (Flags.isZExt())
3644     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3645                          DAG.getValueType(ObjectVT));
3646 
3647   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3648 }
3649 
3650 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3651     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3652     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3653     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3654   // TODO: add description of PPC stack frame format, or at least some docs.
3655   //
3656   bool isELFv2ABI = Subtarget.isELFv2ABI();
3657   bool isLittleEndian = Subtarget.isLittleEndian();
3658   MachineFunction &MF = DAG.getMachineFunction();
3659   MachineFrameInfo &MFI = MF.getFrameInfo();
3660   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3661 
3662   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3663          "fastcc not supported on varargs functions");
3664 
3665   EVT PtrVT = getPointerTy(MF.getDataLayout());
3666   // Potential tail calls could cause overwriting of argument stack slots.
3667   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3668                        (CallConv == CallingConv::Fast));
3669   unsigned PtrByteSize = 8;
3670   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3671 
3672   static const MCPhysReg GPR[] = {
3673     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3674     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3675   };
3676   static const MCPhysReg VR[] = {
3677     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3678     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3679   };
3680 
3681   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3682   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3683   const unsigned Num_VR_Regs  = array_lengthof(VR);
3684   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3685 
3686   // Do a first pass over the arguments to determine whether the ABI
3687   // guarantees that our caller has allocated the parameter save area
3688   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3689   // in the ELFv2 ABI, it is true if this is a vararg function or if
3690   // any parameter is located in a stack slot.
3691 
3692   bool HasParameterArea = !isELFv2ABI || isVarArg;
3693   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3694   unsigned NumBytes = LinkageSize;
3695   unsigned AvailableFPRs = Num_FPR_Regs;
3696   unsigned AvailableVRs = Num_VR_Regs;
3697   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3698     if (Ins[i].Flags.isNest())
3699       continue;
3700 
3701     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3702                                PtrByteSize, LinkageSize, ParamAreaSize,
3703                                NumBytes, AvailableFPRs, AvailableVRs,
3704                                Subtarget.hasQPX()))
3705       HasParameterArea = true;
3706   }
3707 
3708   // Add DAG nodes to load the arguments or copy them out of registers.  On
3709   // entry to a function on PPC, the arguments start after the linkage area,
3710   // although the first ones are often in registers.
3711 
3712   unsigned ArgOffset = LinkageSize;
3713   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3714   unsigned &QFPR_idx = FPR_idx;
3715   SmallVector<SDValue, 8> MemOps;
3716   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3717   unsigned CurArgIdx = 0;
3718   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3719     SDValue ArgVal;
3720     bool needsLoad = false;
3721     EVT ObjectVT = Ins[ArgNo].VT;
3722     EVT OrigVT = Ins[ArgNo].ArgVT;
3723     unsigned ObjSize = ObjectVT.getStoreSize();
3724     unsigned ArgSize = ObjSize;
3725     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3726     if (Ins[ArgNo].isOrigArg()) {
3727       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3728       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3729     }
3730     // We re-align the argument offset for each argument, except when using the
3731     // fast calling convention, when we need to make sure we do that only when
3732     // we'll actually use a stack slot.
3733     unsigned CurArgOffset, Align;
3734     auto ComputeArgOffset = [&]() {
3735       /* Respect alignment of argument on the stack.  */
3736       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3737       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3738       CurArgOffset = ArgOffset;
3739     };
3740 
3741     if (CallConv != CallingConv::Fast) {
3742       ComputeArgOffset();
3743 
3744       /* Compute GPR index associated with argument offset.  */
3745       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3746       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3747     }
3748 
3749     // FIXME the codegen can be much improved in some cases.
3750     // We do not have to keep everything in memory.
3751     if (Flags.isByVal()) {
3752       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3753 
3754       if (CallConv == CallingConv::Fast)
3755         ComputeArgOffset();
3756 
3757       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3758       ObjSize = Flags.getByValSize();
3759       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3760       // Empty aggregate parameters do not take up registers.  Examples:
3761       //   struct { } a;
3762       //   union  { } b;
3763       //   int c[0];
3764       // etc.  However, we have to provide a place-holder in InVals, so
3765       // pretend we have an 8-byte item at the current address for that
3766       // purpose.
3767       if (!ObjSize) {
3768         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3769         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3770         InVals.push_back(FIN);
3771         continue;
3772       }
3773 
3774       // Create a stack object covering all stack doublewords occupied
3775       // by the argument.  If the argument is (fully or partially) on
3776       // the stack, or if the argument is fully in registers but the
3777       // caller has allocated the parameter save anyway, we can refer
3778       // directly to the caller's stack frame.  Otherwise, create a
3779       // local copy in our own frame.
3780       int FI;
3781       if (HasParameterArea ||
3782           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3783         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3784       else
3785         FI = MFI.CreateStackObject(ArgSize, Align, false);
3786       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3787 
3788       // Handle aggregates smaller than 8 bytes.
3789       if (ObjSize < PtrByteSize) {
3790         // The value of the object is its address, which differs from the
3791         // address of the enclosing doubleword on big-endian systems.
3792         SDValue Arg = FIN;
3793         if (!isLittleEndian) {
3794           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3795           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3796         }
3797         InVals.push_back(Arg);
3798 
3799         if (GPR_idx != Num_GPR_Regs) {
3800           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3801           FuncInfo->addLiveInAttr(VReg, Flags);
3802           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3803           SDValue Store;
3804 
3805           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3806             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3807                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3808             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3809                                       MachinePointerInfo(&*FuncArg), ObjType);
3810           } else {
3811             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3812             // store the whole register as-is to the parameter save area
3813             // slot.
3814             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3815                                  MachinePointerInfo(&*FuncArg));
3816           }
3817 
3818           MemOps.push_back(Store);
3819         }
3820         // Whether we copied from a register or not, advance the offset
3821         // into the parameter save area by a full doubleword.
3822         ArgOffset += PtrByteSize;
3823         continue;
3824       }
3825 
3826       // The value of the object is its address, which is the address of
3827       // its first stack doubleword.
3828       InVals.push_back(FIN);
3829 
3830       // Store whatever pieces of the object are in registers to memory.
3831       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3832         if (GPR_idx == Num_GPR_Regs)
3833           break;
3834 
3835         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3836         FuncInfo->addLiveInAttr(VReg, Flags);
3837         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3838         SDValue Addr = FIN;
3839         if (j) {
3840           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3841           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3842         }
3843         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3844                                      MachinePointerInfo(&*FuncArg, j));
3845         MemOps.push_back(Store);
3846         ++GPR_idx;
3847       }
3848       ArgOffset += ArgSize;
3849       continue;
3850     }
3851 
3852     switch (ObjectVT.getSimpleVT().SimpleTy) {
3853     default: llvm_unreachable("Unhandled argument type!");
3854     case MVT::i1:
3855     case MVT::i32:
3856     case MVT::i64:
3857       if (Flags.isNest()) {
3858         // The 'nest' parameter, if any, is passed in R11.
3859         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3860         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3861 
3862         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3863           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3864 
3865         break;
3866       }
3867 
3868       // These can be scalar arguments or elements of an integer array type
3869       // passed directly.  Clang may use those instead of "byval" aggregate
3870       // types to avoid forcing arguments to memory unnecessarily.
3871       if (GPR_idx != Num_GPR_Regs) {
3872         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3873         FuncInfo->addLiveInAttr(VReg, Flags);
3874         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3875 
3876         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3877           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3878           // value to MVT::i64 and then truncate to the correct register size.
3879           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3880       } else {
3881         if (CallConv == CallingConv::Fast)
3882           ComputeArgOffset();
3883 
3884         needsLoad = true;
3885         ArgSize = PtrByteSize;
3886       }
3887       if (CallConv != CallingConv::Fast || needsLoad)
3888         ArgOffset += 8;
3889       break;
3890 
3891     case MVT::f32:
3892     case MVT::f64:
3893       // These can be scalar arguments or elements of a float array type
3894       // passed directly.  The latter are used to implement ELFv2 homogenous
3895       // float aggregates.
3896       if (FPR_idx != Num_FPR_Regs) {
3897         unsigned VReg;
3898 
3899         if (ObjectVT == MVT::f32)
3900           VReg = MF.addLiveIn(FPR[FPR_idx],
3901                               Subtarget.hasP8Vector()
3902                                   ? &PPC::VSSRCRegClass
3903                                   : &PPC::F4RCRegClass);
3904         else
3905           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3906                                                 ? &PPC::VSFRCRegClass
3907                                                 : &PPC::F8RCRegClass);
3908 
3909         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3910         ++FPR_idx;
3911       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3912         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3913         // once we support fp <-> gpr moves.
3914 
3915         // This can only ever happen in the presence of f32 array types,
3916         // since otherwise we never run out of FPRs before running out
3917         // of GPRs.
3918         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3919         FuncInfo->addLiveInAttr(VReg, Flags);
3920         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3921 
3922         if (ObjectVT == MVT::f32) {
3923           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3924             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3925                                  DAG.getConstant(32, dl, MVT::i32));
3926           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3927         }
3928 
3929         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3930       } else {
3931         if (CallConv == CallingConv::Fast)
3932           ComputeArgOffset();
3933 
3934         needsLoad = true;
3935       }
3936 
3937       // When passing an array of floats, the array occupies consecutive
3938       // space in the argument area; only round up to the next doubleword
3939       // at the end of the array.  Otherwise, each float takes 8 bytes.
3940       if (CallConv != CallingConv::Fast || needsLoad) {
3941         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3942         ArgOffset += ArgSize;
3943         if (Flags.isInConsecutiveRegsLast())
3944           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3945       }
3946       break;
3947     case MVT::v4f32:
3948     case MVT::v4i32:
3949     case MVT::v8i16:
3950     case MVT::v16i8:
3951     case MVT::v2f64:
3952     case MVT::v2i64:
3953     case MVT::v1i128:
3954     case MVT::f128:
3955       if (!Subtarget.hasQPX()) {
3956         // These can be scalar arguments or elements of a vector array type
3957         // passed directly.  The latter are used to implement ELFv2 homogenous
3958         // vector aggregates.
3959         if (VR_idx != Num_VR_Regs) {
3960           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3961           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3962           ++VR_idx;
3963         } else {
3964           if (CallConv == CallingConv::Fast)
3965             ComputeArgOffset();
3966           needsLoad = true;
3967         }
3968         if (CallConv != CallingConv::Fast || needsLoad)
3969           ArgOffset += 16;
3970         break;
3971       } // not QPX
3972 
3973       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3974              "Invalid QPX parameter type");
3975       /* fall through */
3976 
3977     case MVT::v4f64:
3978     case MVT::v4i1:
3979       // QPX vectors are treated like their scalar floating-point subregisters
3980       // (except that they're larger).
3981       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3982       if (QFPR_idx != Num_QFPR_Regs) {
3983         const TargetRegisterClass *RC;
3984         switch (ObjectVT.getSimpleVT().SimpleTy) {
3985         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3986         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3987         default:         RC = &PPC::QBRCRegClass; break;
3988         }
3989 
3990         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3991         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3992         ++QFPR_idx;
3993       } else {
3994         if (CallConv == CallingConv::Fast)
3995           ComputeArgOffset();
3996         needsLoad = true;
3997       }
3998       if (CallConv != CallingConv::Fast || needsLoad)
3999         ArgOffset += Sz;
4000       break;
4001     }
4002 
4003     // We need to load the argument to a virtual register if we determined
4004     // above that we ran out of physical registers of the appropriate type.
4005     if (needsLoad) {
4006       if (ObjSize < ArgSize && !isLittleEndian)
4007         CurArgOffset += ArgSize - ObjSize;
4008       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4009       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4010       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4011     }
4012 
4013     InVals.push_back(ArgVal);
4014   }
4015 
4016   // Area that is at least reserved in the caller of this function.
4017   unsigned MinReservedArea;
4018   if (HasParameterArea)
4019     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4020   else
4021     MinReservedArea = LinkageSize;
4022 
4023   // Set the size that is at least reserved in caller of this function.  Tail
4024   // call optimized functions' reserved stack space needs to be aligned so that
4025   // taking the difference between two stack areas will result in an aligned
4026   // stack.
4027   MinReservedArea =
4028       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4029   FuncInfo->setMinReservedArea(MinReservedArea);
4030 
4031   // If the function takes variable number of arguments, make a frame index for
4032   // the start of the first vararg value... for expansion of llvm.va_start.
4033   if (isVarArg) {
4034     int Depth = ArgOffset;
4035 
4036     FuncInfo->setVarArgsFrameIndex(
4037       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4038     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4039 
4040     // If this function is vararg, store any remaining integer argument regs
4041     // to their spots on the stack so that they may be loaded by dereferencing
4042     // the result of va_next.
4043     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4044          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4045       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4046       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4047       SDValue Store =
4048           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4049       MemOps.push_back(Store);
4050       // Increment the address by four for the next argument to store
4051       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4052       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4053     }
4054   }
4055 
4056   if (!MemOps.empty())
4057     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4058 
4059   return Chain;
4060 }
4061 
4062 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4063     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4064     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4065     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4066   // TODO: add description of PPC stack frame format, or at least some docs.
4067   //
4068   MachineFunction &MF = DAG.getMachineFunction();
4069   MachineFrameInfo &MFI = MF.getFrameInfo();
4070   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4071 
4072   EVT PtrVT = getPointerTy(MF.getDataLayout());
4073   bool isPPC64 = PtrVT == MVT::i64;
4074   // Potential tail calls could cause overwriting of argument stack slots.
4075   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4076                        (CallConv == CallingConv::Fast));
4077   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4078   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4079   unsigned ArgOffset = LinkageSize;
4080   // Area that is at least reserved in caller of this function.
4081   unsigned MinReservedArea = ArgOffset;
4082 
4083   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4084     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4085     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4086   };
4087   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4088     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4089     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4090   };
4091   static const MCPhysReg VR[] = {
4092     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4093     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4094   };
4095 
4096   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4097   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4098   const unsigned Num_VR_Regs  = array_lengthof( VR);
4099 
4100   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4101 
4102   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4103 
4104   // In 32-bit non-varargs functions, the stack space for vectors is after the
4105   // stack space for non-vectors.  We do not use this space unless we have
4106   // too many vectors to fit in registers, something that only occurs in
4107   // constructed examples:), but we have to walk the arglist to figure
4108   // that out...for the pathological case, compute VecArgOffset as the
4109   // start of the vector parameter area.  Computing VecArgOffset is the
4110   // entire point of the following loop.
4111   unsigned VecArgOffset = ArgOffset;
4112   if (!isVarArg && !isPPC64) {
4113     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4114          ++ArgNo) {
4115       EVT ObjectVT = Ins[ArgNo].VT;
4116       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4117 
4118       if (Flags.isByVal()) {
4119         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4120         unsigned ObjSize = Flags.getByValSize();
4121         unsigned ArgSize =
4122                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4123         VecArgOffset += ArgSize;
4124         continue;
4125       }
4126 
4127       switch(ObjectVT.getSimpleVT().SimpleTy) {
4128       default: llvm_unreachable("Unhandled argument type!");
4129       case MVT::i1:
4130       case MVT::i32:
4131       case MVT::f32:
4132         VecArgOffset += 4;
4133         break;
4134       case MVT::i64:  // PPC64
4135       case MVT::f64:
4136         // FIXME: We are guaranteed to be !isPPC64 at this point.
4137         // Does MVT::i64 apply?
4138         VecArgOffset += 8;
4139         break;
4140       case MVT::v4f32:
4141       case MVT::v4i32:
4142       case MVT::v8i16:
4143       case MVT::v16i8:
4144         // Nothing to do, we're only looking at Nonvector args here.
4145         break;
4146       }
4147     }
4148   }
4149   // We've found where the vector parameter area in memory is.  Skip the
4150   // first 12 parameters; these don't use that memory.
4151   VecArgOffset = ((VecArgOffset+15)/16)*16;
4152   VecArgOffset += 12*16;
4153 
4154   // Add DAG nodes to load the arguments or copy them out of registers.  On
4155   // entry to a function on PPC, the arguments start after the linkage area,
4156   // although the first ones are often in registers.
4157 
4158   SmallVector<SDValue, 8> MemOps;
4159   unsigned nAltivecParamsAtEnd = 0;
4160   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4161   unsigned CurArgIdx = 0;
4162   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4163     SDValue ArgVal;
4164     bool needsLoad = false;
4165     EVT ObjectVT = Ins[ArgNo].VT;
4166     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4167     unsigned ArgSize = ObjSize;
4168     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4169     if (Ins[ArgNo].isOrigArg()) {
4170       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4171       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4172     }
4173     unsigned CurArgOffset = ArgOffset;
4174 
4175     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4176     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4177         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4178       if (isVarArg || isPPC64) {
4179         MinReservedArea = ((MinReservedArea+15)/16)*16;
4180         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4181                                                   Flags,
4182                                                   PtrByteSize);
4183       } else  nAltivecParamsAtEnd++;
4184     } else
4185       // Calculate min reserved area.
4186       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4187                                                 Flags,
4188                                                 PtrByteSize);
4189 
4190     // FIXME the codegen can be much improved in some cases.
4191     // We do not have to keep everything in memory.
4192     if (Flags.isByVal()) {
4193       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4194 
4195       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4196       ObjSize = Flags.getByValSize();
4197       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4198       // Objects of size 1 and 2 are right justified, everything else is
4199       // left justified.  This means the memory address is adjusted forwards.
4200       if (ObjSize==1 || ObjSize==2) {
4201         CurArgOffset = CurArgOffset + (4 - ObjSize);
4202       }
4203       // The value of the object is its address.
4204       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4205       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4206       InVals.push_back(FIN);
4207       if (ObjSize==1 || ObjSize==2) {
4208         if (GPR_idx != Num_GPR_Regs) {
4209           unsigned VReg;
4210           if (isPPC64)
4211             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4212           else
4213             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4214           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4215           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4216           SDValue Store =
4217               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4218                                 MachinePointerInfo(&*FuncArg), ObjType);
4219           MemOps.push_back(Store);
4220           ++GPR_idx;
4221         }
4222 
4223         ArgOffset += PtrByteSize;
4224 
4225         continue;
4226       }
4227       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4228         // Store whatever pieces of the object are in registers
4229         // to memory.  ArgOffset will be the address of the beginning
4230         // of the object.
4231         if (GPR_idx != Num_GPR_Regs) {
4232           unsigned VReg;
4233           if (isPPC64)
4234             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4235           else
4236             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4237           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4238           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4239           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4240           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4241                                        MachinePointerInfo(&*FuncArg, j));
4242           MemOps.push_back(Store);
4243           ++GPR_idx;
4244           ArgOffset += PtrByteSize;
4245         } else {
4246           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4247           break;
4248         }
4249       }
4250       continue;
4251     }
4252 
4253     switch (ObjectVT.getSimpleVT().SimpleTy) {
4254     default: llvm_unreachable("Unhandled argument type!");
4255     case MVT::i1:
4256     case MVT::i32:
4257       if (!isPPC64) {
4258         if (GPR_idx != Num_GPR_Regs) {
4259           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4260           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4261 
4262           if (ObjectVT == MVT::i1)
4263             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4264 
4265           ++GPR_idx;
4266         } else {
4267           needsLoad = true;
4268           ArgSize = PtrByteSize;
4269         }
4270         // All int arguments reserve stack space in the Darwin ABI.
4271         ArgOffset += PtrByteSize;
4272         break;
4273       }
4274       LLVM_FALLTHROUGH;
4275     case MVT::i64:  // PPC64
4276       if (GPR_idx != Num_GPR_Regs) {
4277         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4278         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4279 
4280         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4281           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4282           // value to MVT::i64 and then truncate to the correct register size.
4283           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4284 
4285         ++GPR_idx;
4286       } else {
4287         needsLoad = true;
4288         ArgSize = PtrByteSize;
4289       }
4290       // All int arguments reserve stack space in the Darwin ABI.
4291       ArgOffset += 8;
4292       break;
4293 
4294     case MVT::f32:
4295     case MVT::f64:
4296       // Every 4 bytes of argument space consumes one of the GPRs available for
4297       // argument passing.
4298       if (GPR_idx != Num_GPR_Regs) {
4299         ++GPR_idx;
4300         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4301           ++GPR_idx;
4302       }
4303       if (FPR_idx != Num_FPR_Regs) {
4304         unsigned VReg;
4305 
4306         if (ObjectVT == MVT::f32)
4307           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4308         else
4309           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4310 
4311         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4312         ++FPR_idx;
4313       } else {
4314         needsLoad = true;
4315       }
4316 
4317       // All FP arguments reserve stack space in the Darwin ABI.
4318       ArgOffset += isPPC64 ? 8 : ObjSize;
4319       break;
4320     case MVT::v4f32:
4321     case MVT::v4i32:
4322     case MVT::v8i16:
4323     case MVT::v16i8:
4324       // Note that vector arguments in registers don't reserve stack space,
4325       // except in varargs functions.
4326       if (VR_idx != Num_VR_Regs) {
4327         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4328         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4329         if (isVarArg) {
4330           while ((ArgOffset % 16) != 0) {
4331             ArgOffset += PtrByteSize;
4332             if (GPR_idx != Num_GPR_Regs)
4333               GPR_idx++;
4334           }
4335           ArgOffset += 16;
4336           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4337         }
4338         ++VR_idx;
4339       } else {
4340         if (!isVarArg && !isPPC64) {
4341           // Vectors go after all the nonvectors.
4342           CurArgOffset = VecArgOffset;
4343           VecArgOffset += 16;
4344         } else {
4345           // Vectors are aligned.
4346           ArgOffset = ((ArgOffset+15)/16)*16;
4347           CurArgOffset = ArgOffset;
4348           ArgOffset += 16;
4349         }
4350         needsLoad = true;
4351       }
4352       break;
4353     }
4354 
4355     // We need to load the argument to a virtual register if we determined above
4356     // that we ran out of physical registers of the appropriate type.
4357     if (needsLoad) {
4358       int FI = MFI.CreateFixedObject(ObjSize,
4359                                      CurArgOffset + (ArgSize - ObjSize),
4360                                      isImmutable);
4361       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4362       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4363     }
4364 
4365     InVals.push_back(ArgVal);
4366   }
4367 
4368   // Allow for Altivec parameters at the end, if needed.
4369   if (nAltivecParamsAtEnd) {
4370     MinReservedArea = ((MinReservedArea+15)/16)*16;
4371     MinReservedArea += 16*nAltivecParamsAtEnd;
4372   }
4373 
4374   // Area that is at least reserved in the caller of this function.
4375   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4376 
4377   // Set the size that is at least reserved in caller of this function.  Tail
4378   // call optimized functions' reserved stack space needs to be aligned so that
4379   // taking the difference between two stack areas will result in an aligned
4380   // stack.
4381   MinReservedArea =
4382       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4383   FuncInfo->setMinReservedArea(MinReservedArea);
4384 
4385   // If the function takes variable number of arguments, make a frame index for
4386   // the start of the first vararg value... for expansion of llvm.va_start.
4387   if (isVarArg) {
4388     int Depth = ArgOffset;
4389 
4390     FuncInfo->setVarArgsFrameIndex(
4391       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4392                             Depth, true));
4393     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4394 
4395     // If this function is vararg, store any remaining integer argument regs
4396     // to their spots on the stack so that they may be loaded by dereferencing
4397     // the result of va_next.
4398     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4399       unsigned VReg;
4400 
4401       if (isPPC64)
4402         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4403       else
4404         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4405 
4406       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4407       SDValue Store =
4408           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4409       MemOps.push_back(Store);
4410       // Increment the address by four for the next argument to store
4411       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4412       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4413     }
4414   }
4415 
4416   if (!MemOps.empty())
4417     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4418 
4419   return Chain;
4420 }
4421 
4422 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4423 /// adjusted to accommodate the arguments for the tailcall.
4424 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4425                                    unsigned ParamSize) {
4426 
4427   if (!isTailCall) return 0;
4428 
4429   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4430   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4431   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4432   // Remember only if the new adjustment is bigger.
4433   if (SPDiff < FI->getTailCallSPDelta())
4434     FI->setTailCallSPDelta(SPDiff);
4435 
4436   return SPDiff;
4437 }
4438 
4439 static bool isFunctionGlobalAddress(SDValue Callee);
4440 
4441 static bool
4442 callsShareTOCBase(const Function *Caller, SDValue Callee,
4443                     const TargetMachine &TM) {
4444   // If !G, Callee can be an external symbol.
4445   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4446   if (!G)
4447     return false;
4448 
4449   // The medium and large code models are expected to provide a sufficiently
4450   // large TOC to provide all data addressing needs of a module with a
4451   // single TOC. Since each module will be addressed with a single TOC then we
4452   // only need to check that caller and callee don't cross dso boundaries.
4453   if (CodeModel::Medium == TM.getCodeModel() ||
4454       CodeModel::Large == TM.getCodeModel())
4455     return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4456 
4457   // Otherwise we need to ensure callee and caller are in the same section,
4458   // since the linker may allocate multiple TOCs, and we don't know which
4459   // sections will belong to the same TOC base.
4460 
4461   const GlobalValue *GV = G->getGlobal();
4462   if (!GV->isStrongDefinitionForLinker())
4463     return false;
4464 
4465   // Any explicitly-specified sections and section prefixes must also match.
4466   // Also, if we're using -ffunction-sections, then each function is always in
4467   // a different section (the same is true for COMDAT functions).
4468   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4469       GV->getSection() != Caller->getSection())
4470     return false;
4471   if (const auto *F = dyn_cast<Function>(GV)) {
4472     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4473       return false;
4474   }
4475 
4476   // If the callee might be interposed, then we can't assume the ultimate call
4477   // target will be in the same section. Even in cases where we can assume that
4478   // interposition won't happen, in any case where the linker might insert a
4479   // stub to allow for interposition, we must generate code as though
4480   // interposition might occur. To understand why this matters, consider a
4481   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4482   // in the same section, but a is in a different module (i.e. has a different
4483   // TOC base pointer). If the linker allows for interposition between b and c,
4484   // then it will generate a stub for the call edge between b and c which will
4485   // save the TOC pointer into the designated stack slot allocated by b. If we
4486   // return true here, and therefore allow a tail call between b and c, that
4487   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4488   // pointer into the stack slot allocated by a (where the a -> b stub saved
4489   // a's TOC base pointer). If we're not considering a tail call, but rather,
4490   // whether a nop is needed after the call instruction in b, because the linker
4491   // will insert a stub, it might complain about a missing nop if we omit it
4492   // (although many don't complain in this case).
4493   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4494     return false;
4495 
4496   return true;
4497 }
4498 
4499 static bool
4500 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4501                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4502   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4503 
4504   const unsigned PtrByteSize = 8;
4505   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4506 
4507   static const MCPhysReg GPR[] = {
4508     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4509     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4510   };
4511   static const MCPhysReg VR[] = {
4512     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4513     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4514   };
4515 
4516   const unsigned NumGPRs = array_lengthof(GPR);
4517   const unsigned NumFPRs = 13;
4518   const unsigned NumVRs = array_lengthof(VR);
4519   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4520 
4521   unsigned NumBytes = LinkageSize;
4522   unsigned AvailableFPRs = NumFPRs;
4523   unsigned AvailableVRs = NumVRs;
4524 
4525   for (const ISD::OutputArg& Param : Outs) {
4526     if (Param.Flags.isNest()) continue;
4527 
4528     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4529                                PtrByteSize, LinkageSize, ParamAreaSize,
4530                                NumBytes, AvailableFPRs, AvailableVRs,
4531                                Subtarget.hasQPX()))
4532       return true;
4533   }
4534   return false;
4535 }
4536 
4537 static bool
4538 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4539   if (CS.arg_size() != CallerFn->arg_size())
4540     return false;
4541 
4542   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4543   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4544   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4545 
4546   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4547     const Value* CalleeArg = *CalleeArgIter;
4548     const Value* CallerArg = &(*CallerArgIter);
4549     if (CalleeArg == CallerArg)
4550       continue;
4551 
4552     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4553     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4554     //      }
4555     // 1st argument of callee is undef and has the same type as caller.
4556     if (CalleeArg->getType() == CallerArg->getType() &&
4557         isa<UndefValue>(CalleeArg))
4558       continue;
4559 
4560     return false;
4561   }
4562 
4563   return true;
4564 }
4565 
4566 // Returns true if TCO is possible between the callers and callees
4567 // calling conventions.
4568 static bool
4569 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4570                                     CallingConv::ID CalleeCC) {
4571   // Tail calls are possible with fastcc and ccc.
4572   auto isTailCallableCC  = [] (CallingConv::ID CC){
4573       return  CC == CallingConv::C || CC == CallingConv::Fast;
4574   };
4575   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4576     return false;
4577 
4578   // We can safely tail call both fastcc and ccc callees from a c calling
4579   // convention caller. If the caller is fastcc, we may have less stack space
4580   // than a non-fastcc caller with the same signature so disable tail-calls in
4581   // that case.
4582   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4583 }
4584 
4585 bool
4586 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4587                                     SDValue Callee,
4588                                     CallingConv::ID CalleeCC,
4589                                     ImmutableCallSite CS,
4590                                     bool isVarArg,
4591                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4592                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4593                                     SelectionDAG& DAG) const {
4594   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4595 
4596   if (DisableSCO && !TailCallOpt) return false;
4597 
4598   // Variadic argument functions are not supported.
4599   if (isVarArg) return false;
4600 
4601   auto &Caller = DAG.getMachineFunction().getFunction();
4602   // Check that the calling conventions are compatible for tco.
4603   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4604     return false;
4605 
4606   // Caller contains any byval parameter is not supported.
4607   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4608     return false;
4609 
4610   // Callee contains any byval parameter is not supported, too.
4611   // Note: This is a quick work around, because in some cases, e.g.
4612   // caller's stack size > callee's stack size, we are still able to apply
4613   // sibling call optimization. For example, gcc is able to do SCO for caller1
4614   // in the following example, but not for caller2.
4615   //   struct test {
4616   //     long int a;
4617   //     char ary[56];
4618   //   } gTest;
4619   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4620   //     b->a = v.a;
4621   //     return 0;
4622   //   }
4623   //   void caller1(struct test a, struct test c, struct test *b) {
4624   //     callee(gTest, b); }
4625   //   void caller2(struct test *b) { callee(gTest, b); }
4626   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4627     return false;
4628 
4629   // If callee and caller use different calling conventions, we cannot pass
4630   // parameters on stack since offsets for the parameter area may be different.
4631   if (Caller.getCallingConv() != CalleeCC &&
4632       needStackSlotPassParameters(Subtarget, Outs))
4633     return false;
4634 
4635   // No TCO/SCO on indirect call because Caller have to restore its TOC
4636   if (!isFunctionGlobalAddress(Callee) &&
4637       !isa<ExternalSymbolSDNode>(Callee))
4638     return false;
4639 
4640   // If the caller and callee potentially have different TOC bases then we
4641   // cannot tail call since we need to restore the TOC pointer after the call.
4642   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4643   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4644     return false;
4645 
4646   // TCO allows altering callee ABI, so we don't have to check further.
4647   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4648     return true;
4649 
4650   if (DisableSCO) return false;
4651 
4652   // If callee use the same argument list that caller is using, then we can
4653   // apply SCO on this case. If it is not, then we need to check if callee needs
4654   // stack for passing arguments.
4655   if (!hasSameArgumentList(&Caller, CS) &&
4656       needStackSlotPassParameters(Subtarget, Outs)) {
4657     return false;
4658   }
4659 
4660   return true;
4661 }
4662 
4663 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4664 /// for tail call optimization. Targets which want to do tail call
4665 /// optimization should implement this function.
4666 bool
4667 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4668                                                      CallingConv::ID CalleeCC,
4669                                                      bool isVarArg,
4670                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4671                                                      SelectionDAG& DAG) const {
4672   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4673     return false;
4674 
4675   // Variable argument functions are not supported.
4676   if (isVarArg)
4677     return false;
4678 
4679   MachineFunction &MF = DAG.getMachineFunction();
4680   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4681   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4682     // Functions containing by val parameters are not supported.
4683     for (unsigned i = 0; i != Ins.size(); i++) {
4684        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4685        if (Flags.isByVal()) return false;
4686     }
4687 
4688     // Non-PIC/GOT tail calls are supported.
4689     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4690       return true;
4691 
4692     // At the moment we can only do local tail calls (in same module, hidden
4693     // or protected) if we are generating PIC.
4694     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4695       return G->getGlobal()->hasHiddenVisibility()
4696           || G->getGlobal()->hasProtectedVisibility();
4697   }
4698 
4699   return false;
4700 }
4701 
4702 /// isCallCompatibleAddress - Return the immediate to use if the specified
4703 /// 32-bit value is representable in the immediate field of a BxA instruction.
4704 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4705   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4706   if (!C) return nullptr;
4707 
4708   int Addr = C->getZExtValue();
4709   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4710       SignExtend32<26>(Addr) != Addr)
4711     return nullptr;  // Top 6 bits have to be sext of immediate.
4712 
4713   return DAG
4714       .getConstant(
4715           (int)C->getZExtValue() >> 2, SDLoc(Op),
4716           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4717       .getNode();
4718 }
4719 
4720 namespace {
4721 
4722 struct TailCallArgumentInfo {
4723   SDValue Arg;
4724   SDValue FrameIdxOp;
4725   int FrameIdx = 0;
4726 
4727   TailCallArgumentInfo() = default;
4728 };
4729 
4730 } // end anonymous namespace
4731 
4732 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4733 static void StoreTailCallArgumentsToStackSlot(
4734     SelectionDAG &DAG, SDValue Chain,
4735     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4736     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4737   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4738     SDValue Arg = TailCallArgs[i].Arg;
4739     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4740     int FI = TailCallArgs[i].FrameIdx;
4741     // Store relative to framepointer.
4742     MemOpChains.push_back(DAG.getStore(
4743         Chain, dl, Arg, FIN,
4744         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4745   }
4746 }
4747 
4748 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4749 /// the appropriate stack slot for the tail call optimized function call.
4750 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4751                                              SDValue OldRetAddr, SDValue OldFP,
4752                                              int SPDiff, const SDLoc &dl) {
4753   if (SPDiff) {
4754     // Calculate the new stack slot for the return address.
4755     MachineFunction &MF = DAG.getMachineFunction();
4756     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4757     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4758     bool isPPC64 = Subtarget.isPPC64();
4759     int SlotSize = isPPC64 ? 8 : 4;
4760     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4761     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4762                                                          NewRetAddrLoc, true);
4763     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4764     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4765     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4766                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4767 
4768     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4769     // slot as the FP is never overwritten.
4770     if (Subtarget.isDarwinABI()) {
4771       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4772       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4773                                                          true);
4774       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4775       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4776                            MachinePointerInfo::getFixedStack(
4777                                DAG.getMachineFunction(), NewFPIdx));
4778     }
4779   }
4780   return Chain;
4781 }
4782 
4783 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4784 /// the position of the argument.
4785 static void
4786 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4787                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4788                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4789   int Offset = ArgOffset + SPDiff;
4790   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4791   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4792   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4793   SDValue FIN = DAG.getFrameIndex(FI, VT);
4794   TailCallArgumentInfo Info;
4795   Info.Arg = Arg;
4796   Info.FrameIdxOp = FIN;
4797   Info.FrameIdx = FI;
4798   TailCallArguments.push_back(Info);
4799 }
4800 
4801 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4802 /// stack slot. Returns the chain as result and the loaded frame pointers in
4803 /// LROpOut/FPOpout. Used when tail calling.
4804 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4805     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4806     SDValue &FPOpOut, const SDLoc &dl) const {
4807   if (SPDiff) {
4808     // Load the LR and FP stack slot for later adjusting.
4809     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4810     LROpOut = getReturnAddrFrameIndex(DAG);
4811     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4812     Chain = SDValue(LROpOut.getNode(), 1);
4813 
4814     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4815     // slot as the FP is never overwritten.
4816     if (Subtarget.isDarwinABI()) {
4817       FPOpOut = getFramePointerFrameIndex(DAG);
4818       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4819       Chain = SDValue(FPOpOut.getNode(), 1);
4820     }
4821   }
4822   return Chain;
4823 }
4824 
4825 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4826 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4827 /// specified by the specific parameter attribute. The copy will be passed as
4828 /// a byval function parameter.
4829 /// Sometimes what we are copying is the end of a larger object, the part that
4830 /// does not fit in registers.
4831 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4832                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4833                                          SelectionDAG &DAG, const SDLoc &dl) {
4834   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4835   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4836                        false, false, false, MachinePointerInfo(),
4837                        MachinePointerInfo());
4838 }
4839 
4840 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4841 /// tail calls.
4842 static void LowerMemOpCallTo(
4843     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4844     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4845     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4846     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4847   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4848   if (!isTailCall) {
4849     if (isVector) {
4850       SDValue StackPtr;
4851       if (isPPC64)
4852         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4853       else
4854         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4855       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4856                            DAG.getConstant(ArgOffset, dl, PtrVT));
4857     }
4858     MemOpChains.push_back(
4859         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4860     // Calculate and remember argument location.
4861   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4862                                   TailCallArguments);
4863 }
4864 
4865 static void
4866 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4867                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4868                 SDValue FPOp,
4869                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4870   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4871   // might overwrite each other in case of tail call optimization.
4872   SmallVector<SDValue, 8> MemOpChains2;
4873   // Do not flag preceding copytoreg stuff together with the following stuff.
4874   InFlag = SDValue();
4875   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4876                                     MemOpChains2, dl);
4877   if (!MemOpChains2.empty())
4878     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4879 
4880   // Store the return address to the appropriate stack slot.
4881   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4882 
4883   // Emit callseq_end just before tailcall node.
4884   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4885                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4886   InFlag = Chain.getValue(1);
4887 }
4888 
4889 // Is this global address that of a function that can be called by name? (as
4890 // opposed to something that must hold a descriptor for an indirect call).
4891 static bool isFunctionGlobalAddress(SDValue Callee) {
4892   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4893     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4894         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4895       return false;
4896 
4897     return G->getGlobal()->getValueType()->isFunctionTy();
4898   }
4899 
4900   return false;
4901 }
4902 
4903 static unsigned
4904 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4905             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4906             bool isPatchPoint, bool hasNest,
4907             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4908             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4909             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4910   bool isPPC64 = Subtarget.isPPC64();
4911   bool isSVR4ABI = Subtarget.isSVR4ABI();
4912   bool isELFv2ABI = Subtarget.isELFv2ABI();
4913 
4914   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4915   NodeTys.push_back(MVT::Other);   // Returns a chain
4916   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4917 
4918   unsigned CallOpc = PPCISD::CALL;
4919 
4920   bool needIndirectCall = true;
4921   if (!isSVR4ABI || !isPPC64)
4922     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4923       // If this is an absolute destination address, use the munged value.
4924       Callee = SDValue(Dest, 0);
4925       needIndirectCall = false;
4926     }
4927 
4928   // PC-relative references to external symbols should go through $stub, unless
4929   // we're building with the leopard linker or later, which automatically
4930   // synthesizes these stubs.
4931   const TargetMachine &TM = DAG.getTarget();
4932   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4933   const GlobalValue *GV = nullptr;
4934   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4935     GV = G->getGlobal();
4936   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4937   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4938 
4939   if (isFunctionGlobalAddress(Callee)) {
4940     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4941     // A call to a TLS address is actually an indirect call to a
4942     // thread-specific pointer.
4943     unsigned OpFlags = 0;
4944     if (UsePlt)
4945       OpFlags = PPCII::MO_PLT;
4946 
4947     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4948     // every direct call is) turn it into a TargetGlobalAddress /
4949     // TargetExternalSymbol node so that legalize doesn't hack it.
4950     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4951                                         Callee.getValueType(), 0, OpFlags);
4952     needIndirectCall = false;
4953   }
4954 
4955   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4956     unsigned char OpFlags = 0;
4957 
4958     if (UsePlt)
4959       OpFlags = PPCII::MO_PLT;
4960 
4961     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4962                                          OpFlags);
4963     needIndirectCall = false;
4964   }
4965 
4966   if (isPatchPoint) {
4967     // We'll form an invalid direct call when lowering a patchpoint; the full
4968     // sequence for an indirect call is complicated, and many of the
4969     // instructions introduced might have side effects (and, thus, can't be
4970     // removed later). The call itself will be removed as soon as the
4971     // argument/return lowering is complete, so the fact that it has the wrong
4972     // kind of operands should not really matter.
4973     needIndirectCall = false;
4974   }
4975 
4976   if (needIndirectCall) {
4977     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4978     // to do the call, we can't use PPCISD::CALL.
4979     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4980 
4981     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4982       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4983       // entry point, but to the function descriptor (the function entry point
4984       // address is part of the function descriptor though).
4985       // The function descriptor is a three doubleword structure with the
4986       // following fields: function entry point, TOC base address and
4987       // environment pointer.
4988       // Thus for a call through a function pointer, the following actions need
4989       // to be performed:
4990       //   1. Save the TOC of the caller in the TOC save area of its stack
4991       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4992       //   2. Load the address of the function entry point from the function
4993       //      descriptor.
4994       //   3. Load the TOC of the callee from the function descriptor into r2.
4995       //   4. Load the environment pointer from the function descriptor into
4996       //      r11.
4997       //   5. Branch to the function entry point address.
4998       //   6. On return of the callee, the TOC of the caller needs to be
4999       //      restored (this is done in FinishCall()).
5000       //
5001       // The loads are scheduled at the beginning of the call sequence, and the
5002       // register copies are flagged together to ensure that no other
5003       // operations can be scheduled in between. E.g. without flagging the
5004       // copies together, a TOC access in the caller could be scheduled between
5005       // the assignment of the callee TOC and the branch to the callee, which
5006       // results in the TOC access going through the TOC of the callee instead
5007       // of going through the TOC of the caller, which leads to incorrect code.
5008 
5009       // Load the address of the function entry point from the function
5010       // descriptor.
5011       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
5012       if (LDChain.getValueType() == MVT::Glue)
5013         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
5014 
5015       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5016                           ? (MachineMemOperand::MODereferenceable |
5017                              MachineMemOperand::MOInvariant)
5018                           : MachineMemOperand::MONone;
5019 
5020       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5021       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
5022                                         /* Alignment = */ 8, MMOFlags);
5023 
5024       // Load environment pointer into r11.
5025       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
5026       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
5027       SDValue LoadEnvPtr =
5028           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
5029                       /* Alignment = */ 8, MMOFlags);
5030 
5031       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
5032       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
5033       SDValue TOCPtr =
5034           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
5035                       /* Alignment = */ 8, MMOFlags);
5036 
5037       setUsesTOCBasePtr(DAG);
5038       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
5039                                         InFlag);
5040       Chain = TOCVal.getValue(0);
5041       InFlag = TOCVal.getValue(1);
5042 
5043       // If the function call has an explicit 'nest' parameter, it takes the
5044       // place of the environment pointer.
5045       if (!hasNest) {
5046         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
5047                                           InFlag);
5048 
5049         Chain = EnvVal.getValue(0);
5050         InFlag = EnvVal.getValue(1);
5051       }
5052 
5053       MTCTROps[0] = Chain;
5054       MTCTROps[1] = LoadFuncPtr;
5055       MTCTROps[2] = InFlag;
5056     }
5057 
5058     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
5059                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
5060     InFlag = Chain.getValue(1);
5061 
5062     NodeTys.clear();
5063     NodeTys.push_back(MVT::Other);
5064     NodeTys.push_back(MVT::Glue);
5065     Ops.push_back(Chain);
5066     CallOpc = PPCISD::BCTRL;
5067     Callee.setNode(nullptr);
5068     // Add use of X11 (holding environment pointer)
5069     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
5070       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
5071     // Add CTR register as callee so a bctr can be emitted later.
5072     if (isTailCall)
5073       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
5074   }
5075 
5076   // If this is a direct call, pass the chain and the callee.
5077   if (Callee.getNode()) {
5078     Ops.push_back(Chain);
5079     Ops.push_back(Callee);
5080   }
5081   // If this is a tail call add stack pointer delta.
5082   if (isTailCall)
5083     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5084 
5085   // Add argument registers to the end of the list so that they are known live
5086   // into the call.
5087   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5088     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5089                                   RegsToPass[i].second.getValueType()));
5090 
5091   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
5092   // into the call.
5093   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
5094     setUsesTOCBasePtr(DAG);
5095     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
5096   }
5097 
5098   return CallOpc;
5099 }
5100 
5101 SDValue PPCTargetLowering::LowerCallResult(
5102     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5103     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5104     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5105   SmallVector<CCValAssign, 16> RVLocs;
5106   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5107                     *DAG.getContext());
5108 
5109   CCRetInfo.AnalyzeCallResult(
5110       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5111                ? RetCC_PPC_Cold
5112                : RetCC_PPC);
5113 
5114   // Copy all of the result registers out of their specified physreg.
5115   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5116     CCValAssign &VA = RVLocs[i];
5117     assert(VA.isRegLoc() && "Can only return in registers!");
5118 
5119     SDValue Val = DAG.getCopyFromReg(Chain, dl,
5120                                      VA.getLocReg(), VA.getLocVT(), InFlag);
5121     Chain = Val.getValue(1);
5122     InFlag = Val.getValue(2);
5123 
5124     switch (VA.getLocInfo()) {
5125     default: llvm_unreachable("Unknown loc info!");
5126     case CCValAssign::Full: break;
5127     case CCValAssign::AExt:
5128       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5129       break;
5130     case CCValAssign::ZExt:
5131       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5132                         DAG.getValueType(VA.getValVT()));
5133       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5134       break;
5135     case CCValAssign::SExt:
5136       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5137                         DAG.getValueType(VA.getValVT()));
5138       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5139       break;
5140     }
5141 
5142     InVals.push_back(Val);
5143   }
5144 
5145   return Chain;
5146 }
5147 
5148 SDValue PPCTargetLowering::FinishCall(
5149     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5150     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5151     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5152     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5153     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5154     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5155   std::vector<EVT> NodeTys;
5156   SmallVector<SDValue, 8> Ops;
5157   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5158                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5159                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5160 
5161   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5162   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5163     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5164 
5165   // When performing tail call optimization the callee pops its arguments off
5166   // the stack. Account for this here so these bytes can be pushed back on in
5167   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5168   int BytesCalleePops =
5169     (CallConv == CallingConv::Fast &&
5170      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5171 
5172   // Add a register mask operand representing the call-preserved registers.
5173   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5174   const uint32_t *Mask =
5175       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5176   assert(Mask && "Missing call preserved mask for calling convention");
5177   Ops.push_back(DAG.getRegisterMask(Mask));
5178 
5179   if (InFlag.getNode())
5180     Ops.push_back(InFlag);
5181 
5182   // Emit tail call.
5183   if (isTailCall) {
5184     assert(((Callee.getOpcode() == ISD::Register &&
5185              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5186             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5187             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5188             isa<ConstantSDNode>(Callee)) &&
5189     "Expecting an global address, external symbol, absolute value or register");
5190 
5191     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5192     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5193   }
5194 
5195   // Add a NOP immediately after the branch instruction when using the 64-bit
5196   // SVR4 ABI. At link time, if caller and callee are in a different module and
5197   // thus have a different TOC, the call will be replaced with a call to a stub
5198   // function which saves the current TOC, loads the TOC of the callee and
5199   // branches to the callee. The NOP will be replaced with a load instruction
5200   // which restores the TOC of the caller from the TOC save slot of the current
5201   // stack frame. If caller and callee belong to the same module (and have the
5202   // same TOC), the NOP will remain unchanged.
5203 
5204   MachineFunction &MF = DAG.getMachineFunction();
5205   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
5206       !isPatchPoint) {
5207     if (CallOpc == PPCISD::BCTRL) {
5208       // This is a call through a function pointer.
5209       // Restore the caller TOC from the save area into R2.
5210       // See PrepareCall() for more information about calls through function
5211       // pointers in the 64-bit SVR4 ABI.
5212       // We are using a target-specific load with r2 hard coded, because the
5213       // result of a target-independent load would never go directly into r2,
5214       // since r2 is a reserved register (which prevents the register allocator
5215       // from allocating it), resulting in an additional register being
5216       // allocated and an unnecessary move instruction being generated.
5217       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5218 
5219       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5220       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5221       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5222       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5223       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5224 
5225       // The address needs to go after the chain input but before the flag (or
5226       // any other variadic arguments).
5227       Ops.insert(std::next(Ops.begin()), AddTOC);
5228     } else if (CallOpc == PPCISD::CALL &&
5229       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5230       // Otherwise insert NOP for non-local calls.
5231       CallOpc = PPCISD::CALL_NOP;
5232     }
5233   }
5234 
5235   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5236   InFlag = Chain.getValue(1);
5237 
5238   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5239                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5240                              InFlag, dl);
5241   if (!Ins.empty())
5242     InFlag = Chain.getValue(1);
5243 
5244   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5245                          Ins, dl, DAG, InVals);
5246 }
5247 
5248 SDValue
5249 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5250                              SmallVectorImpl<SDValue> &InVals) const {
5251   SelectionDAG &DAG                     = CLI.DAG;
5252   SDLoc &dl                             = CLI.DL;
5253   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5254   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5255   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5256   SDValue Chain                         = CLI.Chain;
5257   SDValue Callee                        = CLI.Callee;
5258   bool &isTailCall                      = CLI.IsTailCall;
5259   CallingConv::ID CallConv              = CLI.CallConv;
5260   bool isVarArg                         = CLI.IsVarArg;
5261   bool isPatchPoint                     = CLI.IsPatchPoint;
5262   ImmutableCallSite CS                  = CLI.CS;
5263 
5264   if (isTailCall) {
5265     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5266       isTailCall = false;
5267     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5268       isTailCall =
5269         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5270                                                  isVarArg, Outs, Ins, DAG);
5271     else
5272       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5273                                                      Ins, DAG);
5274     if (isTailCall) {
5275       ++NumTailCalls;
5276       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5277         ++NumSiblingCalls;
5278 
5279       assert(isa<GlobalAddressSDNode>(Callee) &&
5280              "Callee should be an llvm::Function object.");
5281       LLVM_DEBUG(
5282           const GlobalValue *GV =
5283               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5284           const unsigned Width =
5285               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5286           dbgs() << "TCO caller: "
5287                  << left_justify(DAG.getMachineFunction().getName(), Width)
5288                  << ", callee linkage: " << GV->getVisibility() << ", "
5289                  << GV->getLinkage() << "\n");
5290     }
5291   }
5292 
5293   if (!isTailCall && CS && CS.isMustTailCall())
5294     report_fatal_error("failed to perform tail call elimination on a call "
5295                        "site marked musttail");
5296 
5297   // When long calls (i.e. indirect calls) are always used, calls are always
5298   // made via function pointer. If we have a function name, first translate it
5299   // into a pointer.
5300   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5301       !isTailCall)
5302     Callee = LowerGlobalAddress(Callee, DAG);
5303 
5304   if (Subtarget.isSVR4ABI()) {
5305     if (Subtarget.isPPC64())
5306       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5307                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5308                               dl, DAG, InVals, CS);
5309     else
5310       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5311                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5312                               dl, DAG, InVals, CS);
5313   }
5314 
5315   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5316                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5317                           dl, DAG, InVals, CS);
5318 }
5319 
5320 SDValue PPCTargetLowering::LowerCall_32SVR4(
5321     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5322     bool isTailCall, bool isPatchPoint,
5323     const SmallVectorImpl<ISD::OutputArg> &Outs,
5324     const SmallVectorImpl<SDValue> &OutVals,
5325     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5326     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5327     ImmutableCallSite CS) const {
5328   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5329   // of the 32-bit SVR4 ABI stack frame layout.
5330 
5331   assert((CallConv == CallingConv::C ||
5332           CallConv == CallingConv::Cold ||
5333           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5334 
5335   unsigned PtrByteSize = 4;
5336 
5337   MachineFunction &MF = DAG.getMachineFunction();
5338 
5339   // Mark this function as potentially containing a function that contains a
5340   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5341   // and restoring the callers stack pointer in this functions epilog. This is
5342   // done because by tail calling the called function might overwrite the value
5343   // in this function's (MF) stack pointer stack slot 0(SP).
5344   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5345       CallConv == CallingConv::Fast)
5346     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5347 
5348   // Count how many bytes are to be pushed on the stack, including the linkage
5349   // area, parameter list area and the part of the local variable space which
5350   // contains copies of aggregates which are passed by value.
5351 
5352   // Assign locations to all of the outgoing arguments.
5353   SmallVector<CCValAssign, 16> ArgLocs;
5354   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5355 
5356   // Reserve space for the linkage area on the stack.
5357   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5358                        PtrByteSize);
5359   if (useSoftFloat())
5360     CCInfo.PreAnalyzeCallOperands(Outs);
5361 
5362   if (isVarArg) {
5363     // Handle fixed and variable vector arguments differently.
5364     // Fixed vector arguments go into registers as long as registers are
5365     // available. Variable vector arguments always go into memory.
5366     unsigned NumArgs = Outs.size();
5367 
5368     for (unsigned i = 0; i != NumArgs; ++i) {
5369       MVT ArgVT = Outs[i].VT;
5370       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5371       bool Result;
5372 
5373       if (Outs[i].IsFixed) {
5374         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5375                                CCInfo);
5376       } else {
5377         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5378                                       ArgFlags, CCInfo);
5379       }
5380 
5381       if (Result) {
5382 #ifndef NDEBUG
5383         errs() << "Call operand #" << i << " has unhandled type "
5384              << EVT(ArgVT).getEVTString() << "\n";
5385 #endif
5386         llvm_unreachable(nullptr);
5387       }
5388     }
5389   } else {
5390     // All arguments are treated the same.
5391     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5392   }
5393   CCInfo.clearWasPPCF128();
5394 
5395   // Assign locations to all of the outgoing aggregate by value arguments.
5396   SmallVector<CCValAssign, 16> ByValArgLocs;
5397   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5398 
5399   // Reserve stack space for the allocations in CCInfo.
5400   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5401 
5402   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5403 
5404   // Size of the linkage area, parameter list area and the part of the local
5405   // space variable where copies of aggregates which are passed by value are
5406   // stored.
5407   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5408 
5409   // Calculate by how many bytes the stack has to be adjusted in case of tail
5410   // call optimization.
5411   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5412 
5413   // Adjust the stack pointer for the new arguments...
5414   // These operations are automatically eliminated by the prolog/epilog pass
5415   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5416   SDValue CallSeqStart = Chain;
5417 
5418   // Load the return address and frame pointer so it can be moved somewhere else
5419   // later.
5420   SDValue LROp, FPOp;
5421   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5422 
5423   // Set up a copy of the stack pointer for use loading and storing any
5424   // arguments that may not fit in the registers available for argument
5425   // passing.
5426   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5427 
5428   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5429   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5430   SmallVector<SDValue, 8> MemOpChains;
5431 
5432   bool seenFloatArg = false;
5433   // Walk the register/memloc assignments, inserting copies/loads.
5434   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5435        i != e;
5436        ++i) {
5437     CCValAssign &VA = ArgLocs[i];
5438     SDValue Arg = OutVals[i];
5439     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5440 
5441     if (Flags.isByVal()) {
5442       // Argument is an aggregate which is passed by value, thus we need to
5443       // create a copy of it in the local variable space of the current stack
5444       // frame (which is the stack frame of the caller) and pass the address of
5445       // this copy to the callee.
5446       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5447       CCValAssign &ByValVA = ByValArgLocs[j++];
5448       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5449 
5450       // Memory reserved in the local variable space of the callers stack frame.
5451       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5452 
5453       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5454       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5455                            StackPtr, PtrOff);
5456 
5457       // Create a copy of the argument in the local area of the current
5458       // stack frame.
5459       SDValue MemcpyCall =
5460         CreateCopyOfByValArgument(Arg, PtrOff,
5461                                   CallSeqStart.getNode()->getOperand(0),
5462                                   Flags, DAG, dl);
5463 
5464       // This must go outside the CALLSEQ_START..END.
5465       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5466                                                      SDLoc(MemcpyCall));
5467       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5468                              NewCallSeqStart.getNode());
5469       Chain = CallSeqStart = NewCallSeqStart;
5470 
5471       // Pass the address of the aggregate copy on the stack either in a
5472       // physical register or in the parameter list area of the current stack
5473       // frame to the callee.
5474       Arg = PtrOff;
5475     }
5476 
5477     // When useCRBits() is true, there can be i1 arguments.
5478     // It is because getRegisterType(MVT::i1) => MVT::i1,
5479     // and for other integer types getRegisterType() => MVT::i32.
5480     // Extend i1 and ensure callee will get i32.
5481     if (Arg.getValueType() == MVT::i1)
5482       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5483                         dl, MVT::i32, Arg);
5484 
5485     if (VA.isRegLoc()) {
5486       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5487       // Put argument in a physical register.
5488       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5489     } else {
5490       // Put argument in the parameter list area of the current stack frame.
5491       assert(VA.isMemLoc());
5492       unsigned LocMemOffset = VA.getLocMemOffset();
5493 
5494       if (!isTailCall) {
5495         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5496         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5497                              StackPtr, PtrOff);
5498 
5499         MemOpChains.push_back(
5500             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5501       } else {
5502         // Calculate and remember argument location.
5503         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5504                                  TailCallArguments);
5505       }
5506     }
5507   }
5508 
5509   if (!MemOpChains.empty())
5510     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5511 
5512   // Build a sequence of copy-to-reg nodes chained together with token chain
5513   // and flag operands which copy the outgoing args into the appropriate regs.
5514   SDValue InFlag;
5515   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5516     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5517                              RegsToPass[i].second, InFlag);
5518     InFlag = Chain.getValue(1);
5519   }
5520 
5521   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5522   // registers.
5523   if (isVarArg) {
5524     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5525     SDValue Ops[] = { Chain, InFlag };
5526 
5527     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5528                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5529 
5530     InFlag = Chain.getValue(1);
5531   }
5532 
5533   if (isTailCall)
5534     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5535                     TailCallArguments);
5536 
5537   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5538                     /* unused except on PPC64 ELFv1 */ false, DAG,
5539                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5540                     NumBytes, Ins, InVals, CS);
5541 }
5542 
5543 // Copy an argument into memory, being careful to do this outside the
5544 // call sequence for the call to which the argument belongs.
5545 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5546     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5547     SelectionDAG &DAG, const SDLoc &dl) const {
5548   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5549                         CallSeqStart.getNode()->getOperand(0),
5550                         Flags, DAG, dl);
5551   // The MEMCPY must go outside the CALLSEQ_START..END.
5552   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5553   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5554                                                  SDLoc(MemcpyCall));
5555   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5556                          NewCallSeqStart.getNode());
5557   return NewCallSeqStart;
5558 }
5559 
5560 SDValue PPCTargetLowering::LowerCall_64SVR4(
5561     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5562     bool isTailCall, bool isPatchPoint,
5563     const SmallVectorImpl<ISD::OutputArg> &Outs,
5564     const SmallVectorImpl<SDValue> &OutVals,
5565     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5566     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5567     ImmutableCallSite CS) const {
5568   bool isELFv2ABI = Subtarget.isELFv2ABI();
5569   bool isLittleEndian = Subtarget.isLittleEndian();
5570   unsigned NumOps = Outs.size();
5571   bool hasNest = false;
5572   bool IsSibCall = false;
5573 
5574   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5575   unsigned PtrByteSize = 8;
5576 
5577   MachineFunction &MF = DAG.getMachineFunction();
5578 
5579   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5580     IsSibCall = true;
5581 
5582   // Mark this function as potentially containing a function that contains a
5583   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5584   // and restoring the callers stack pointer in this functions epilog. This is
5585   // done because by tail calling the called function might overwrite the value
5586   // in this function's (MF) stack pointer stack slot 0(SP).
5587   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5588       CallConv == CallingConv::Fast)
5589     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5590 
5591   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5592          "fastcc not supported on varargs functions");
5593 
5594   // Count how many bytes are to be pushed on the stack, including the linkage
5595   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5596   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5597   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5598   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5599   unsigned NumBytes = LinkageSize;
5600   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5601   unsigned &QFPR_idx = FPR_idx;
5602 
5603   static const MCPhysReg GPR[] = {
5604     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5605     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5606   };
5607   static const MCPhysReg VR[] = {
5608     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5609     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5610   };
5611 
5612   const unsigned NumGPRs = array_lengthof(GPR);
5613   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5614   const unsigned NumVRs  = array_lengthof(VR);
5615   const unsigned NumQFPRs = NumFPRs;
5616 
5617   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5618   // can be passed to the callee in registers.
5619   // For the fast calling convention, there is another check below.
5620   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5621   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5622   if (!HasParameterArea) {
5623     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5624     unsigned AvailableFPRs = NumFPRs;
5625     unsigned AvailableVRs = NumVRs;
5626     unsigned NumBytesTmp = NumBytes;
5627     for (unsigned i = 0; i != NumOps; ++i) {
5628       if (Outs[i].Flags.isNest()) continue;
5629       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5630                                 PtrByteSize, LinkageSize, ParamAreaSize,
5631                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5632                                 Subtarget.hasQPX()))
5633         HasParameterArea = true;
5634     }
5635   }
5636 
5637   // When using the fast calling convention, we don't provide backing for
5638   // arguments that will be in registers.
5639   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5640 
5641   // Avoid allocating parameter area for fastcc functions if all the arguments
5642   // can be passed in the registers.
5643   if (CallConv == CallingConv::Fast)
5644     HasParameterArea = false;
5645 
5646   // Add up all the space actually used.
5647   for (unsigned i = 0; i != NumOps; ++i) {
5648     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5649     EVT ArgVT = Outs[i].VT;
5650     EVT OrigVT = Outs[i].ArgVT;
5651 
5652     if (Flags.isNest())
5653       continue;
5654 
5655     if (CallConv == CallingConv::Fast) {
5656       if (Flags.isByVal()) {
5657         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5658         if (NumGPRsUsed > NumGPRs)
5659           HasParameterArea = true;
5660       } else {
5661         switch (ArgVT.getSimpleVT().SimpleTy) {
5662         default: llvm_unreachable("Unexpected ValueType for argument!");
5663         case MVT::i1:
5664         case MVT::i32:
5665         case MVT::i64:
5666           if (++NumGPRsUsed <= NumGPRs)
5667             continue;
5668           break;
5669         case MVT::v4i32:
5670         case MVT::v8i16:
5671         case MVT::v16i8:
5672         case MVT::v2f64:
5673         case MVT::v2i64:
5674         case MVT::v1i128:
5675         case MVT::f128:
5676           if (++NumVRsUsed <= NumVRs)
5677             continue;
5678           break;
5679         case MVT::v4f32:
5680           // When using QPX, this is handled like a FP register, otherwise, it
5681           // is an Altivec register.
5682           if (Subtarget.hasQPX()) {
5683             if (++NumFPRsUsed <= NumFPRs)
5684               continue;
5685           } else {
5686             if (++NumVRsUsed <= NumVRs)
5687               continue;
5688           }
5689           break;
5690         case MVT::f32:
5691         case MVT::f64:
5692         case MVT::v4f64: // QPX
5693         case MVT::v4i1:  // QPX
5694           if (++NumFPRsUsed <= NumFPRs)
5695             continue;
5696           break;
5697         }
5698         HasParameterArea = true;
5699       }
5700     }
5701 
5702     /* Respect alignment of argument on the stack.  */
5703     unsigned Align =
5704       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5705     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5706 
5707     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5708     if (Flags.isInConsecutiveRegsLast())
5709       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5710   }
5711 
5712   unsigned NumBytesActuallyUsed = NumBytes;
5713 
5714   // In the old ELFv1 ABI,
5715   // the prolog code of the callee may store up to 8 GPR argument registers to
5716   // the stack, allowing va_start to index over them in memory if its varargs.
5717   // Because we cannot tell if this is needed on the caller side, we have to
5718   // conservatively assume that it is needed.  As such, make sure we have at
5719   // least enough stack space for the caller to store the 8 GPRs.
5720   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5721   // really requires memory operands, e.g. a vararg function.
5722   if (HasParameterArea)
5723     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5724   else
5725     NumBytes = LinkageSize;
5726 
5727   // Tail call needs the stack to be aligned.
5728   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5729       CallConv == CallingConv::Fast)
5730     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5731 
5732   int SPDiff = 0;
5733 
5734   // Calculate by how many bytes the stack has to be adjusted in case of tail
5735   // call optimization.
5736   if (!IsSibCall)
5737     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5738 
5739   // To protect arguments on the stack from being clobbered in a tail call,
5740   // force all the loads to happen before doing any other lowering.
5741   if (isTailCall)
5742     Chain = DAG.getStackArgumentTokenFactor(Chain);
5743 
5744   // Adjust the stack pointer for the new arguments...
5745   // These operations are automatically eliminated by the prolog/epilog pass
5746   if (!IsSibCall)
5747     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5748   SDValue CallSeqStart = Chain;
5749 
5750   // Load the return address and frame pointer so it can be move somewhere else
5751   // later.
5752   SDValue LROp, FPOp;
5753   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5754 
5755   // Set up a copy of the stack pointer for use loading and storing any
5756   // arguments that may not fit in the registers available for argument
5757   // passing.
5758   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5759 
5760   // Figure out which arguments are going to go in registers, and which in
5761   // memory.  Also, if this is a vararg function, floating point operations
5762   // must be stored to our stack, and loaded into integer regs as well, if
5763   // any integer regs are available for argument passing.
5764   unsigned ArgOffset = LinkageSize;
5765 
5766   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5767   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5768 
5769   SmallVector<SDValue, 8> MemOpChains;
5770   for (unsigned i = 0; i != NumOps; ++i) {
5771     SDValue Arg = OutVals[i];
5772     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5773     EVT ArgVT = Outs[i].VT;
5774     EVT OrigVT = Outs[i].ArgVT;
5775 
5776     // PtrOff will be used to store the current argument to the stack if a
5777     // register cannot be found for it.
5778     SDValue PtrOff;
5779 
5780     // We re-align the argument offset for each argument, except when using the
5781     // fast calling convention, when we need to make sure we do that only when
5782     // we'll actually use a stack slot.
5783     auto ComputePtrOff = [&]() {
5784       /* Respect alignment of argument on the stack.  */
5785       unsigned Align =
5786         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5787       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5788 
5789       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5790 
5791       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5792     };
5793 
5794     if (CallConv != CallingConv::Fast) {
5795       ComputePtrOff();
5796 
5797       /* Compute GPR index associated with argument offset.  */
5798       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5799       GPR_idx = std::min(GPR_idx, NumGPRs);
5800     }
5801 
5802     // Promote integers to 64-bit values.
5803     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5804       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5805       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5806       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5807     }
5808 
5809     // FIXME memcpy is used way more than necessary.  Correctness first.
5810     // Note: "by value" is code for passing a structure by value, not
5811     // basic types.
5812     if (Flags.isByVal()) {
5813       // Note: Size includes alignment padding, so
5814       //   struct x { short a; char b; }
5815       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5816       // These are the proper values we need for right-justifying the
5817       // aggregate in a parameter register.
5818       unsigned Size = Flags.getByValSize();
5819 
5820       // An empty aggregate parameter takes up no storage and no
5821       // registers.
5822       if (Size == 0)
5823         continue;
5824 
5825       if (CallConv == CallingConv::Fast)
5826         ComputePtrOff();
5827 
5828       // All aggregates smaller than 8 bytes must be passed right-justified.
5829       if (Size==1 || Size==2 || Size==4) {
5830         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5831         if (GPR_idx != NumGPRs) {
5832           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5833                                         MachinePointerInfo(), VT);
5834           MemOpChains.push_back(Load.getValue(1));
5835           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5836 
5837           ArgOffset += PtrByteSize;
5838           continue;
5839         }
5840       }
5841 
5842       if (GPR_idx == NumGPRs && Size < 8) {
5843         SDValue AddPtr = PtrOff;
5844         if (!isLittleEndian) {
5845           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5846                                           PtrOff.getValueType());
5847           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5848         }
5849         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5850                                                           CallSeqStart,
5851                                                           Flags, DAG, dl);
5852         ArgOffset += PtrByteSize;
5853         continue;
5854       }
5855       // Copy entire object into memory.  There are cases where gcc-generated
5856       // code assumes it is there, even if it could be put entirely into
5857       // registers.  (This is not what the doc says.)
5858 
5859       // FIXME: The above statement is likely due to a misunderstanding of the
5860       // documents.  All arguments must be copied into the parameter area BY
5861       // THE CALLEE in the event that the callee takes the address of any
5862       // formal argument.  That has not yet been implemented.  However, it is
5863       // reasonable to use the stack area as a staging area for the register
5864       // load.
5865 
5866       // Skip this for small aggregates, as we will use the same slot for a
5867       // right-justified copy, below.
5868       if (Size >= 8)
5869         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5870                                                           CallSeqStart,
5871                                                           Flags, DAG, dl);
5872 
5873       // When a register is available, pass a small aggregate right-justified.
5874       if (Size < 8 && GPR_idx != NumGPRs) {
5875         // The easiest way to get this right-justified in a register
5876         // is to copy the structure into the rightmost portion of a
5877         // local variable slot, then load the whole slot into the
5878         // register.
5879         // FIXME: The memcpy seems to produce pretty awful code for
5880         // small aggregates, particularly for packed ones.
5881         // FIXME: It would be preferable to use the slot in the
5882         // parameter save area instead of a new local variable.
5883         SDValue AddPtr = PtrOff;
5884         if (!isLittleEndian) {
5885           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5886           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5887         }
5888         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5889                                                           CallSeqStart,
5890                                                           Flags, DAG, dl);
5891 
5892         // Load the slot into the register.
5893         SDValue Load =
5894             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5895         MemOpChains.push_back(Load.getValue(1));
5896         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5897 
5898         // Done with this argument.
5899         ArgOffset += PtrByteSize;
5900         continue;
5901       }
5902 
5903       // For aggregates larger than PtrByteSize, copy the pieces of the
5904       // object that fit into registers from the parameter save area.
5905       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5906         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5907         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5908         if (GPR_idx != NumGPRs) {
5909           SDValue Load =
5910               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5911           MemOpChains.push_back(Load.getValue(1));
5912           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5913           ArgOffset += PtrByteSize;
5914         } else {
5915           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5916           break;
5917         }
5918       }
5919       continue;
5920     }
5921 
5922     switch (Arg.getSimpleValueType().SimpleTy) {
5923     default: llvm_unreachable("Unexpected ValueType for argument!");
5924     case MVT::i1:
5925     case MVT::i32:
5926     case MVT::i64:
5927       if (Flags.isNest()) {
5928         // The 'nest' parameter, if any, is passed in R11.
5929         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5930         hasNest = true;
5931         break;
5932       }
5933 
5934       // These can be scalar arguments or elements of an integer array type
5935       // passed directly.  Clang may use those instead of "byval" aggregate
5936       // types to avoid forcing arguments to memory unnecessarily.
5937       if (GPR_idx != NumGPRs) {
5938         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5939       } else {
5940         if (CallConv == CallingConv::Fast)
5941           ComputePtrOff();
5942 
5943         assert(HasParameterArea &&
5944                "Parameter area must exist to pass an argument in memory.");
5945         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5946                          true, isTailCall, false, MemOpChains,
5947                          TailCallArguments, dl);
5948         if (CallConv == CallingConv::Fast)
5949           ArgOffset += PtrByteSize;
5950       }
5951       if (CallConv != CallingConv::Fast)
5952         ArgOffset += PtrByteSize;
5953       break;
5954     case MVT::f32:
5955     case MVT::f64: {
5956       // These can be scalar arguments or elements of a float array type
5957       // passed directly.  The latter are used to implement ELFv2 homogenous
5958       // float aggregates.
5959 
5960       // Named arguments go into FPRs first, and once they overflow, the
5961       // remaining arguments go into GPRs and then the parameter save area.
5962       // Unnamed arguments for vararg functions always go to GPRs and
5963       // then the parameter save area.  For now, put all arguments to vararg
5964       // routines always in both locations (FPR *and* GPR or stack slot).
5965       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5966       bool NeededLoad = false;
5967 
5968       // First load the argument into the next available FPR.
5969       if (FPR_idx != NumFPRs)
5970         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5971 
5972       // Next, load the argument into GPR or stack slot if needed.
5973       if (!NeedGPROrStack)
5974         ;
5975       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5976         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5977         // once we support fp <-> gpr moves.
5978 
5979         // In the non-vararg case, this can only ever happen in the
5980         // presence of f32 array types, since otherwise we never run
5981         // out of FPRs before running out of GPRs.
5982         SDValue ArgVal;
5983 
5984         // Double values are always passed in a single GPR.
5985         if (Arg.getValueType() != MVT::f32) {
5986           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5987 
5988         // Non-array float values are extended and passed in a GPR.
5989         } else if (!Flags.isInConsecutiveRegs()) {
5990           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5991           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5992 
5993         // If we have an array of floats, we collect every odd element
5994         // together with its predecessor into one GPR.
5995         } else if (ArgOffset % PtrByteSize != 0) {
5996           SDValue Lo, Hi;
5997           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5998           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5999           if (!isLittleEndian)
6000             std::swap(Lo, Hi);
6001           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6002 
6003         // The final element, if even, goes into the first half of a GPR.
6004         } else if (Flags.isInConsecutiveRegsLast()) {
6005           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6006           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6007           if (!isLittleEndian)
6008             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6009                                  DAG.getConstant(32, dl, MVT::i32));
6010 
6011         // Non-final even elements are skipped; they will be handled
6012         // together the with subsequent argument on the next go-around.
6013         } else
6014           ArgVal = SDValue();
6015 
6016         if (ArgVal.getNode())
6017           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6018       } else {
6019         if (CallConv == CallingConv::Fast)
6020           ComputePtrOff();
6021 
6022         // Single-precision floating-point values are mapped to the
6023         // second (rightmost) word of the stack doubleword.
6024         if (Arg.getValueType() == MVT::f32 &&
6025             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6026           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6027           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6028         }
6029 
6030         assert(HasParameterArea &&
6031                "Parameter area must exist to pass an argument in memory.");
6032         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6033                          true, isTailCall, false, MemOpChains,
6034                          TailCallArguments, dl);
6035 
6036         NeededLoad = true;
6037       }
6038       // When passing an array of floats, the array occupies consecutive
6039       // space in the argument area; only round up to the next doubleword
6040       // at the end of the array.  Otherwise, each float takes 8 bytes.
6041       if (CallConv != CallingConv::Fast || NeededLoad) {
6042         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6043                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6044         if (Flags.isInConsecutiveRegsLast())
6045           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6046       }
6047       break;
6048     }
6049     case MVT::v4f32:
6050     case MVT::v4i32:
6051     case MVT::v8i16:
6052     case MVT::v16i8:
6053     case MVT::v2f64:
6054     case MVT::v2i64:
6055     case MVT::v1i128:
6056     case MVT::f128:
6057       if (!Subtarget.hasQPX()) {
6058       // These can be scalar arguments or elements of a vector array type
6059       // passed directly.  The latter are used to implement ELFv2 homogenous
6060       // vector aggregates.
6061 
6062       // For a varargs call, named arguments go into VRs or on the stack as
6063       // usual; unnamed arguments always go to the stack or the corresponding
6064       // GPRs when within range.  For now, we always put the value in both
6065       // locations (or even all three).
6066       if (isVarArg) {
6067         assert(HasParameterArea &&
6068                "Parameter area must exist if we have a varargs call.");
6069         // We could elide this store in the case where the object fits
6070         // entirely in R registers.  Maybe later.
6071         SDValue Store =
6072             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6073         MemOpChains.push_back(Store);
6074         if (VR_idx != NumVRs) {
6075           SDValue Load =
6076               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6077           MemOpChains.push_back(Load.getValue(1));
6078           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6079         }
6080         ArgOffset += 16;
6081         for (unsigned i=0; i<16; i+=PtrByteSize) {
6082           if (GPR_idx == NumGPRs)
6083             break;
6084           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6085                                    DAG.getConstant(i, dl, PtrVT));
6086           SDValue Load =
6087               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6088           MemOpChains.push_back(Load.getValue(1));
6089           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6090         }
6091         break;
6092       }
6093 
6094       // Non-varargs Altivec params go into VRs or on the stack.
6095       if (VR_idx != NumVRs) {
6096         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6097       } else {
6098         if (CallConv == CallingConv::Fast)
6099           ComputePtrOff();
6100 
6101         assert(HasParameterArea &&
6102                "Parameter area must exist to pass an argument in memory.");
6103         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6104                          true, isTailCall, true, MemOpChains,
6105                          TailCallArguments, dl);
6106         if (CallConv == CallingConv::Fast)
6107           ArgOffset += 16;
6108       }
6109 
6110       if (CallConv != CallingConv::Fast)
6111         ArgOffset += 16;
6112       break;
6113       } // not QPX
6114 
6115       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6116              "Invalid QPX parameter type");
6117 
6118       /* fall through */
6119     case MVT::v4f64:
6120     case MVT::v4i1: {
6121       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6122       if (isVarArg) {
6123         assert(HasParameterArea &&
6124                "Parameter area must exist if we have a varargs call.");
6125         // We could elide this store in the case where the object fits
6126         // entirely in R registers.  Maybe later.
6127         SDValue Store =
6128             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6129         MemOpChains.push_back(Store);
6130         if (QFPR_idx != NumQFPRs) {
6131           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6132                                      PtrOff, MachinePointerInfo());
6133           MemOpChains.push_back(Load.getValue(1));
6134           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6135         }
6136         ArgOffset += (IsF32 ? 16 : 32);
6137         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6138           if (GPR_idx == NumGPRs)
6139             break;
6140           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6141                                    DAG.getConstant(i, dl, PtrVT));
6142           SDValue Load =
6143               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6144           MemOpChains.push_back(Load.getValue(1));
6145           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6146         }
6147         break;
6148       }
6149 
6150       // Non-varargs QPX params go into registers or on the stack.
6151       if (QFPR_idx != NumQFPRs) {
6152         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6153       } else {
6154         if (CallConv == CallingConv::Fast)
6155           ComputePtrOff();
6156 
6157         assert(HasParameterArea &&
6158                "Parameter area must exist to pass an argument in memory.");
6159         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6160                          true, isTailCall, true, MemOpChains,
6161                          TailCallArguments, dl);
6162         if (CallConv == CallingConv::Fast)
6163           ArgOffset += (IsF32 ? 16 : 32);
6164       }
6165 
6166       if (CallConv != CallingConv::Fast)
6167         ArgOffset += (IsF32 ? 16 : 32);
6168       break;
6169       }
6170     }
6171   }
6172 
6173   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6174          "mismatch in size of parameter area");
6175   (void)NumBytesActuallyUsed;
6176 
6177   if (!MemOpChains.empty())
6178     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6179 
6180   // Check if this is an indirect call (MTCTR/BCTRL).
6181   // See PrepareCall() for more information about calls through function
6182   // pointers in the 64-bit SVR4 ABI.
6183   if (!isTailCall && !isPatchPoint &&
6184       !isFunctionGlobalAddress(Callee) &&
6185       !isa<ExternalSymbolSDNode>(Callee)) {
6186     // Load r2 into a virtual register and store it to the TOC save area.
6187     setUsesTOCBasePtr(DAG);
6188     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6189     // TOC save area offset.
6190     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6191     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6192     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6193     Chain = DAG.getStore(
6194         Val.getValue(1), dl, Val, AddPtr,
6195         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6196     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6197     // This does not mean the MTCTR instruction must use R12; it's easier
6198     // to model this as an extra parameter, so do that.
6199     if (isELFv2ABI && !isPatchPoint)
6200       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6201   }
6202 
6203   // Build a sequence of copy-to-reg nodes chained together with token chain
6204   // and flag operands which copy the outgoing args into the appropriate regs.
6205   SDValue InFlag;
6206   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6207     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6208                              RegsToPass[i].second, InFlag);
6209     InFlag = Chain.getValue(1);
6210   }
6211 
6212   if (isTailCall && !IsSibCall)
6213     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6214                     TailCallArguments);
6215 
6216   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6217                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6218                     SPDiff, NumBytes, Ins, InVals, CS);
6219 }
6220 
6221 SDValue PPCTargetLowering::LowerCall_Darwin(
6222     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6223     bool isTailCall, bool isPatchPoint,
6224     const SmallVectorImpl<ISD::OutputArg> &Outs,
6225     const SmallVectorImpl<SDValue> &OutVals,
6226     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6227     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6228     ImmutableCallSite CS) const {
6229   unsigned NumOps = Outs.size();
6230 
6231   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6232   bool isPPC64 = PtrVT == MVT::i64;
6233   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6234 
6235   MachineFunction &MF = DAG.getMachineFunction();
6236 
6237   // Mark this function as potentially containing a function that contains a
6238   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6239   // and restoring the callers stack pointer in this functions epilog. This is
6240   // done because by tail calling the called function might overwrite the value
6241   // in this function's (MF) stack pointer stack slot 0(SP).
6242   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6243       CallConv == CallingConv::Fast)
6244     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6245 
6246   // Count how many bytes are to be pushed on the stack, including the linkage
6247   // area, and parameter passing area.  We start with 24/48 bytes, which is
6248   // prereserved space for [SP][CR][LR][3 x unused].
6249   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6250   unsigned NumBytes = LinkageSize;
6251 
6252   // Add up all the space actually used.
6253   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6254   // they all go in registers, but we must reserve stack space for them for
6255   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6256   // assigned stack space in order, with padding so Altivec parameters are
6257   // 16-byte aligned.
6258   unsigned nAltivecParamsAtEnd = 0;
6259   for (unsigned i = 0; i != NumOps; ++i) {
6260     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6261     EVT ArgVT = Outs[i].VT;
6262     // Varargs Altivec parameters are padded to a 16 byte boundary.
6263     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6264         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6265         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6266       if (!isVarArg && !isPPC64) {
6267         // Non-varargs Altivec parameters go after all the non-Altivec
6268         // parameters; handle those later so we know how much padding we need.
6269         nAltivecParamsAtEnd++;
6270         continue;
6271       }
6272       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6273       NumBytes = ((NumBytes+15)/16)*16;
6274     }
6275     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6276   }
6277 
6278   // Allow for Altivec parameters at the end, if needed.
6279   if (nAltivecParamsAtEnd) {
6280     NumBytes = ((NumBytes+15)/16)*16;
6281     NumBytes += 16*nAltivecParamsAtEnd;
6282   }
6283 
6284   // The prolog code of the callee may store up to 8 GPR argument registers to
6285   // the stack, allowing va_start to index over them in memory if its varargs.
6286   // Because we cannot tell if this is needed on the caller side, we have to
6287   // conservatively assume that it is needed.  As such, make sure we have at
6288   // least enough stack space for the caller to store the 8 GPRs.
6289   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6290 
6291   // Tail call needs the stack to be aligned.
6292   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6293       CallConv == CallingConv::Fast)
6294     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6295 
6296   // Calculate by how many bytes the stack has to be adjusted in case of tail
6297   // call optimization.
6298   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6299 
6300   // To protect arguments on the stack from being clobbered in a tail call,
6301   // force all the loads to happen before doing any other lowering.
6302   if (isTailCall)
6303     Chain = DAG.getStackArgumentTokenFactor(Chain);
6304 
6305   // Adjust the stack pointer for the new arguments...
6306   // These operations are automatically eliminated by the prolog/epilog pass
6307   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6308   SDValue CallSeqStart = Chain;
6309 
6310   // Load the return address and frame pointer so it can be move somewhere else
6311   // later.
6312   SDValue LROp, FPOp;
6313   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6314 
6315   // Set up a copy of the stack pointer for use loading and storing any
6316   // arguments that may not fit in the registers available for argument
6317   // passing.
6318   SDValue StackPtr;
6319   if (isPPC64)
6320     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6321   else
6322     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6323 
6324   // Figure out which arguments are going to go in registers, and which in
6325   // memory.  Also, if this is a vararg function, floating point operations
6326   // must be stored to our stack, and loaded into integer regs as well, if
6327   // any integer regs are available for argument passing.
6328   unsigned ArgOffset = LinkageSize;
6329   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6330 
6331   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6332     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6333     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6334   };
6335   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6336     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6337     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6338   };
6339   static const MCPhysReg VR[] = {
6340     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6341     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6342   };
6343   const unsigned NumGPRs = array_lengthof(GPR_32);
6344   const unsigned NumFPRs = 13;
6345   const unsigned NumVRs  = array_lengthof(VR);
6346 
6347   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6348 
6349   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6350   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6351 
6352   SmallVector<SDValue, 8> MemOpChains;
6353   for (unsigned i = 0; i != NumOps; ++i) {
6354     SDValue Arg = OutVals[i];
6355     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6356 
6357     // PtrOff will be used to store the current argument to the stack if a
6358     // register cannot be found for it.
6359     SDValue PtrOff;
6360 
6361     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6362 
6363     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6364 
6365     // On PPC64, promote integers to 64-bit values.
6366     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6367       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6368       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6369       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6370     }
6371 
6372     // FIXME memcpy is used way more than necessary.  Correctness first.
6373     // Note: "by value" is code for passing a structure by value, not
6374     // basic types.
6375     if (Flags.isByVal()) {
6376       unsigned Size = Flags.getByValSize();
6377       // Very small objects are passed right-justified.  Everything else is
6378       // passed left-justified.
6379       if (Size==1 || Size==2) {
6380         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6381         if (GPR_idx != NumGPRs) {
6382           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6383                                         MachinePointerInfo(), VT);
6384           MemOpChains.push_back(Load.getValue(1));
6385           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6386 
6387           ArgOffset += PtrByteSize;
6388         } else {
6389           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6390                                           PtrOff.getValueType());
6391           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6392           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6393                                                             CallSeqStart,
6394                                                             Flags, DAG, dl);
6395           ArgOffset += PtrByteSize;
6396         }
6397         continue;
6398       }
6399       // Copy entire object into memory.  There are cases where gcc-generated
6400       // code assumes it is there, even if it could be put entirely into
6401       // registers.  (This is not what the doc says.)
6402       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6403                                                         CallSeqStart,
6404                                                         Flags, DAG, dl);
6405 
6406       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6407       // copy the pieces of the object that fit into registers from the
6408       // parameter save area.
6409       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6410         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6411         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6412         if (GPR_idx != NumGPRs) {
6413           SDValue Load =
6414               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6415           MemOpChains.push_back(Load.getValue(1));
6416           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6417           ArgOffset += PtrByteSize;
6418         } else {
6419           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6420           break;
6421         }
6422       }
6423       continue;
6424     }
6425 
6426     switch (Arg.getSimpleValueType().SimpleTy) {
6427     default: llvm_unreachable("Unexpected ValueType for argument!");
6428     case MVT::i1:
6429     case MVT::i32:
6430     case MVT::i64:
6431       if (GPR_idx != NumGPRs) {
6432         if (Arg.getValueType() == MVT::i1)
6433           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6434 
6435         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6436       } else {
6437         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6438                          isPPC64, isTailCall, false, MemOpChains,
6439                          TailCallArguments, dl);
6440       }
6441       ArgOffset += PtrByteSize;
6442       break;
6443     case MVT::f32:
6444     case MVT::f64:
6445       if (FPR_idx != NumFPRs) {
6446         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6447 
6448         if (isVarArg) {
6449           SDValue Store =
6450               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6451           MemOpChains.push_back(Store);
6452 
6453           // Float varargs are always shadowed in available integer registers
6454           if (GPR_idx != NumGPRs) {
6455             SDValue Load =
6456                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6457             MemOpChains.push_back(Load.getValue(1));
6458             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6459           }
6460           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6461             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6462             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6463             SDValue Load =
6464                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6465             MemOpChains.push_back(Load.getValue(1));
6466             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6467           }
6468         } else {
6469           // If we have any FPRs remaining, we may also have GPRs remaining.
6470           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6471           // GPRs.
6472           if (GPR_idx != NumGPRs)
6473             ++GPR_idx;
6474           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6475               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6476             ++GPR_idx;
6477         }
6478       } else
6479         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6480                          isPPC64, isTailCall, false, MemOpChains,
6481                          TailCallArguments, dl);
6482       if (isPPC64)
6483         ArgOffset += 8;
6484       else
6485         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6486       break;
6487     case MVT::v4f32:
6488     case MVT::v4i32:
6489     case MVT::v8i16:
6490     case MVT::v16i8:
6491       if (isVarArg) {
6492         // These go aligned on the stack, or in the corresponding R registers
6493         // when within range.  The Darwin PPC ABI doc claims they also go in
6494         // V registers; in fact gcc does this only for arguments that are
6495         // prototyped, not for those that match the ...  We do it for all
6496         // arguments, seems to work.
6497         while (ArgOffset % 16 !=0) {
6498           ArgOffset += PtrByteSize;
6499           if (GPR_idx != NumGPRs)
6500             GPR_idx++;
6501         }
6502         // We could elide this store in the case where the object fits
6503         // entirely in R registers.  Maybe later.
6504         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6505                              DAG.getConstant(ArgOffset, dl, PtrVT));
6506         SDValue Store =
6507             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6508         MemOpChains.push_back(Store);
6509         if (VR_idx != NumVRs) {
6510           SDValue Load =
6511               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6512           MemOpChains.push_back(Load.getValue(1));
6513           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6514         }
6515         ArgOffset += 16;
6516         for (unsigned i=0; i<16; i+=PtrByteSize) {
6517           if (GPR_idx == NumGPRs)
6518             break;
6519           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6520                                    DAG.getConstant(i, dl, PtrVT));
6521           SDValue Load =
6522               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6523           MemOpChains.push_back(Load.getValue(1));
6524           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6525         }
6526         break;
6527       }
6528 
6529       // Non-varargs Altivec params generally go in registers, but have
6530       // stack space allocated at the end.
6531       if (VR_idx != NumVRs) {
6532         // Doesn't have GPR space allocated.
6533         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6534       } else if (nAltivecParamsAtEnd==0) {
6535         // We are emitting Altivec params in order.
6536         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6537                          isPPC64, isTailCall, true, MemOpChains,
6538                          TailCallArguments, dl);
6539         ArgOffset += 16;
6540       }
6541       break;
6542     }
6543   }
6544   // If all Altivec parameters fit in registers, as they usually do,
6545   // they get stack space following the non-Altivec parameters.  We
6546   // don't track this here because nobody below needs it.
6547   // If there are more Altivec parameters than fit in registers emit
6548   // the stores here.
6549   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6550     unsigned j = 0;
6551     // Offset is aligned; skip 1st 12 params which go in V registers.
6552     ArgOffset = ((ArgOffset+15)/16)*16;
6553     ArgOffset += 12*16;
6554     for (unsigned i = 0; i != NumOps; ++i) {
6555       SDValue Arg = OutVals[i];
6556       EVT ArgType = Outs[i].VT;
6557       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6558           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6559         if (++j > NumVRs) {
6560           SDValue PtrOff;
6561           // We are emitting Altivec params in order.
6562           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6563                            isPPC64, isTailCall, true, MemOpChains,
6564                            TailCallArguments, dl);
6565           ArgOffset += 16;
6566         }
6567       }
6568     }
6569   }
6570 
6571   if (!MemOpChains.empty())
6572     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6573 
6574   // On Darwin, R12 must contain the address of an indirect callee.  This does
6575   // not mean the MTCTR instruction must use R12; it's easier to model this as
6576   // an extra parameter, so do that.
6577   if (!isTailCall &&
6578       !isFunctionGlobalAddress(Callee) &&
6579       !isa<ExternalSymbolSDNode>(Callee) &&
6580       !isBLACompatibleAddress(Callee, DAG))
6581     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6582                                                    PPC::R12), Callee));
6583 
6584   // Build a sequence of copy-to-reg nodes chained together with token chain
6585   // and flag operands which copy the outgoing args into the appropriate regs.
6586   SDValue InFlag;
6587   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6588     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6589                              RegsToPass[i].second, InFlag);
6590     InFlag = Chain.getValue(1);
6591   }
6592 
6593   if (isTailCall)
6594     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6595                     TailCallArguments);
6596 
6597   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6598                     /* unused except on PPC64 ELFv1 */ false, DAG,
6599                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6600                     NumBytes, Ins, InVals, CS);
6601 }
6602 
6603 bool
6604 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6605                                   MachineFunction &MF, bool isVarArg,
6606                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6607                                   LLVMContext &Context) const {
6608   SmallVector<CCValAssign, 16> RVLocs;
6609   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6610   return CCInfo.CheckReturn(
6611       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6612                 ? RetCC_PPC_Cold
6613                 : RetCC_PPC);
6614 }
6615 
6616 SDValue
6617 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6618                                bool isVarArg,
6619                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6620                                const SmallVectorImpl<SDValue> &OutVals,
6621                                const SDLoc &dl, SelectionDAG &DAG) const {
6622   SmallVector<CCValAssign, 16> RVLocs;
6623   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6624                  *DAG.getContext());
6625   CCInfo.AnalyzeReturn(Outs,
6626                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6627                            ? RetCC_PPC_Cold
6628                            : RetCC_PPC);
6629 
6630   SDValue Flag;
6631   SmallVector<SDValue, 4> RetOps(1, Chain);
6632 
6633   // Copy the result values into the output registers.
6634   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6635     CCValAssign &VA = RVLocs[i];
6636     assert(VA.isRegLoc() && "Can only return in registers!");
6637 
6638     SDValue Arg = OutVals[i];
6639 
6640     switch (VA.getLocInfo()) {
6641     default: llvm_unreachable("Unknown loc info!");
6642     case CCValAssign::Full: break;
6643     case CCValAssign::AExt:
6644       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6645       break;
6646     case CCValAssign::ZExt:
6647       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6648       break;
6649     case CCValAssign::SExt:
6650       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6651       break;
6652     }
6653 
6654     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6655     Flag = Chain.getValue(1);
6656     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6657   }
6658 
6659   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6660   const MCPhysReg *I =
6661     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6662   if (I) {
6663     for (; *I; ++I) {
6664 
6665       if (PPC::G8RCRegClass.contains(*I))
6666         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6667       else if (PPC::F8RCRegClass.contains(*I))
6668         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6669       else if (PPC::CRRCRegClass.contains(*I))
6670         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6671       else if (PPC::VRRCRegClass.contains(*I))
6672         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6673       else
6674         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6675     }
6676   }
6677 
6678   RetOps[0] = Chain;  // Update chain.
6679 
6680   // Add the flag if we have it.
6681   if (Flag.getNode())
6682     RetOps.push_back(Flag);
6683 
6684   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6685 }
6686 
6687 SDValue
6688 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6689                                                 SelectionDAG &DAG) const {
6690   SDLoc dl(Op);
6691 
6692   // Get the correct type for integers.
6693   EVT IntVT = Op.getValueType();
6694 
6695   // Get the inputs.
6696   SDValue Chain = Op.getOperand(0);
6697   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6698   // Build a DYNAREAOFFSET node.
6699   SDValue Ops[2] = {Chain, FPSIdx};
6700   SDVTList VTs = DAG.getVTList(IntVT);
6701   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6702 }
6703 
6704 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6705                                              SelectionDAG &DAG) const {
6706   // When we pop the dynamic allocation we need to restore the SP link.
6707   SDLoc dl(Op);
6708 
6709   // Get the correct type for pointers.
6710   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6711 
6712   // Construct the stack pointer operand.
6713   bool isPPC64 = Subtarget.isPPC64();
6714   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6715   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6716 
6717   // Get the operands for the STACKRESTORE.
6718   SDValue Chain = Op.getOperand(0);
6719   SDValue SaveSP = Op.getOperand(1);
6720 
6721   // Load the old link SP.
6722   SDValue LoadLinkSP =
6723       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6724 
6725   // Restore the stack pointer.
6726   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6727 
6728   // Store the old link SP.
6729   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6730 }
6731 
6732 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6733   MachineFunction &MF = DAG.getMachineFunction();
6734   bool isPPC64 = Subtarget.isPPC64();
6735   EVT PtrVT = getPointerTy(MF.getDataLayout());
6736 
6737   // Get current frame pointer save index.  The users of this index will be
6738   // primarily DYNALLOC instructions.
6739   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6740   int RASI = FI->getReturnAddrSaveIndex();
6741 
6742   // If the frame pointer save index hasn't been defined yet.
6743   if (!RASI) {
6744     // Find out what the fix offset of the frame pointer save area.
6745     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6746     // Allocate the frame index for frame pointer save area.
6747     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6748     // Save the result.
6749     FI->setReturnAddrSaveIndex(RASI);
6750   }
6751   return DAG.getFrameIndex(RASI, PtrVT);
6752 }
6753 
6754 SDValue
6755 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6756   MachineFunction &MF = DAG.getMachineFunction();
6757   bool isPPC64 = Subtarget.isPPC64();
6758   EVT PtrVT = getPointerTy(MF.getDataLayout());
6759 
6760   // Get current frame pointer save index.  The users of this index will be
6761   // primarily DYNALLOC instructions.
6762   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6763   int FPSI = FI->getFramePointerSaveIndex();
6764 
6765   // If the frame pointer save index hasn't been defined yet.
6766   if (!FPSI) {
6767     // Find out what the fix offset of the frame pointer save area.
6768     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6769     // Allocate the frame index for frame pointer save area.
6770     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6771     // Save the result.
6772     FI->setFramePointerSaveIndex(FPSI);
6773   }
6774   return DAG.getFrameIndex(FPSI, PtrVT);
6775 }
6776 
6777 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6778                                                    SelectionDAG &DAG) const {
6779   // Get the inputs.
6780   SDValue Chain = Op.getOperand(0);
6781   SDValue Size  = Op.getOperand(1);
6782   SDLoc dl(Op);
6783 
6784   // Get the correct type for pointers.
6785   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6786   // Negate the size.
6787   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6788                                 DAG.getConstant(0, dl, PtrVT), Size);
6789   // Construct a node for the frame pointer save index.
6790   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6791   // Build a DYNALLOC node.
6792   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6793   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6794   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6795 }
6796 
6797 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6798                                                      SelectionDAG &DAG) const {
6799   MachineFunction &MF = DAG.getMachineFunction();
6800 
6801   bool isPPC64 = Subtarget.isPPC64();
6802   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6803 
6804   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6805   return DAG.getFrameIndex(FI, PtrVT);
6806 }
6807 
6808 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6809                                                SelectionDAG &DAG) const {
6810   SDLoc DL(Op);
6811   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6812                      DAG.getVTList(MVT::i32, MVT::Other),
6813                      Op.getOperand(0), Op.getOperand(1));
6814 }
6815 
6816 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6817                                                 SelectionDAG &DAG) const {
6818   SDLoc DL(Op);
6819   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6820                      Op.getOperand(0), Op.getOperand(1));
6821 }
6822 
6823 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6824   if (Op.getValueType().isVector())
6825     return LowerVectorLoad(Op, DAG);
6826 
6827   assert(Op.getValueType() == MVT::i1 &&
6828          "Custom lowering only for i1 loads");
6829 
6830   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6831 
6832   SDLoc dl(Op);
6833   LoadSDNode *LD = cast<LoadSDNode>(Op);
6834 
6835   SDValue Chain = LD->getChain();
6836   SDValue BasePtr = LD->getBasePtr();
6837   MachineMemOperand *MMO = LD->getMemOperand();
6838 
6839   SDValue NewLD =
6840       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6841                      BasePtr, MVT::i8, MMO);
6842   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6843 
6844   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6845   return DAG.getMergeValues(Ops, dl);
6846 }
6847 
6848 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6849   if (Op.getOperand(1).getValueType().isVector())
6850     return LowerVectorStore(Op, DAG);
6851 
6852   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6853          "Custom lowering only for i1 stores");
6854 
6855   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6856 
6857   SDLoc dl(Op);
6858   StoreSDNode *ST = cast<StoreSDNode>(Op);
6859 
6860   SDValue Chain = ST->getChain();
6861   SDValue BasePtr = ST->getBasePtr();
6862   SDValue Value = ST->getValue();
6863   MachineMemOperand *MMO = ST->getMemOperand();
6864 
6865   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6866                       Value);
6867   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6868 }
6869 
6870 // FIXME: Remove this once the ANDI glue bug is fixed:
6871 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6872   assert(Op.getValueType() == MVT::i1 &&
6873          "Custom lowering only for i1 results");
6874 
6875   SDLoc DL(Op);
6876   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6877                      Op.getOperand(0));
6878 }
6879 
6880 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6881 /// possible.
6882 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6883   // Not FP? Not a fsel.
6884   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6885       !Op.getOperand(2).getValueType().isFloatingPoint())
6886     return Op;
6887 
6888   // We might be able to do better than this under some circumstances, but in
6889   // general, fsel-based lowering of select is a finite-math-only optimization.
6890   // For more information, see section F.3 of the 2.06 ISA specification.
6891   if (!DAG.getTarget().Options.NoInfsFPMath ||
6892       !DAG.getTarget().Options.NoNaNsFPMath)
6893     return Op;
6894   // TODO: Propagate flags from the select rather than global settings.
6895   SDNodeFlags Flags;
6896   Flags.setNoInfs(true);
6897   Flags.setNoNaNs(true);
6898 
6899   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6900 
6901   EVT ResVT = Op.getValueType();
6902   EVT CmpVT = Op.getOperand(0).getValueType();
6903   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6904   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6905   SDLoc dl(Op);
6906 
6907   // If the RHS of the comparison is a 0.0, we don't need to do the
6908   // subtraction at all.
6909   SDValue Sel1;
6910   if (isFloatingPointZero(RHS))
6911     switch (CC) {
6912     default: break;       // SETUO etc aren't handled by fsel.
6913     case ISD::SETNE:
6914       std::swap(TV, FV);
6915       LLVM_FALLTHROUGH;
6916     case ISD::SETEQ:
6917       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6918         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6919       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6920       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6921         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6922       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6923                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6924     case ISD::SETULT:
6925     case ISD::SETLT:
6926       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6927       LLVM_FALLTHROUGH;
6928     case ISD::SETOGE:
6929     case ISD::SETGE:
6930       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6931         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6932       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6933     case ISD::SETUGT:
6934     case ISD::SETGT:
6935       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6936       LLVM_FALLTHROUGH;
6937     case ISD::SETOLE:
6938     case ISD::SETLE:
6939       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6940         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6941       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6942                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6943     }
6944 
6945   SDValue Cmp;
6946   switch (CC) {
6947   default: break;       // SETUO etc aren't handled by fsel.
6948   case ISD::SETNE:
6949     std::swap(TV, FV);
6950     LLVM_FALLTHROUGH;
6951   case ISD::SETEQ:
6952     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6953     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6954       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6955     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6956     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6957       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6958     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6959                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6960   case ISD::SETULT:
6961   case ISD::SETLT:
6962     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6963     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6964       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6965     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6966   case ISD::SETOGE:
6967   case ISD::SETGE:
6968     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6969     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6970       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6971     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6972   case ISD::SETUGT:
6973   case ISD::SETGT:
6974     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6975     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6976       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6977     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6978   case ISD::SETOLE:
6979   case ISD::SETLE:
6980     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6981     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6982       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6983     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6984   }
6985   return Op;
6986 }
6987 
6988 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6989                                                SelectionDAG &DAG,
6990                                                const SDLoc &dl) const {
6991   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6992   SDValue Src = Op.getOperand(0);
6993   if (Src.getValueType() == MVT::f32)
6994     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6995 
6996   SDValue Tmp;
6997   switch (Op.getSimpleValueType().SimpleTy) {
6998   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6999   case MVT::i32:
7000     Tmp = DAG.getNode(
7001         Op.getOpcode() == ISD::FP_TO_SINT
7002             ? PPCISD::FCTIWZ
7003             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7004         dl, MVT::f64, Src);
7005     break;
7006   case MVT::i64:
7007     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7008            "i64 FP_TO_UINT is supported only with FPCVT");
7009     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7010                                                         PPCISD::FCTIDUZ,
7011                       dl, MVT::f64, Src);
7012     break;
7013   }
7014 
7015   // Convert the FP value to an int value through memory.
7016   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7017     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7018   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7019   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7020   MachinePointerInfo MPI =
7021       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7022 
7023   // Emit a store to the stack slot.
7024   SDValue Chain;
7025   if (i32Stack) {
7026     MachineFunction &MF = DAG.getMachineFunction();
7027     MachineMemOperand *MMO =
7028       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7029     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7030     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7031               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7032   } else
7033     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7034 
7035   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7036   // add in a bias on big endian.
7037   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7038     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7039                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7040     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7041   }
7042 
7043   RLI.Chain = Chain;
7044   RLI.Ptr = FIPtr;
7045   RLI.MPI = MPI;
7046 }
7047 
7048 /// Custom lowers floating point to integer conversions to use
7049 /// the direct move instructions available in ISA 2.07 to avoid the
7050 /// need for load/store combinations.
7051 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7052                                                     SelectionDAG &DAG,
7053                                                     const SDLoc &dl) const {
7054   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7055   SDValue Src = Op.getOperand(0);
7056 
7057   if (Src.getValueType() == MVT::f32)
7058     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7059 
7060   SDValue Tmp;
7061   switch (Op.getSimpleValueType().SimpleTy) {
7062   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7063   case MVT::i32:
7064     Tmp = DAG.getNode(
7065         Op.getOpcode() == ISD::FP_TO_SINT
7066             ? PPCISD::FCTIWZ
7067             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7068         dl, MVT::f64, Src);
7069     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7070     break;
7071   case MVT::i64:
7072     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7073            "i64 FP_TO_UINT is supported only with FPCVT");
7074     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7075                                                         PPCISD::FCTIDUZ,
7076                       dl, MVT::f64, Src);
7077     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7078     break;
7079   }
7080   return Tmp;
7081 }
7082 
7083 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7084                                           const SDLoc &dl) const {
7085 
7086   // FP to INT conversions are legal for f128.
7087   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7088     return Op;
7089 
7090   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7091   // PPC (the libcall is not available).
7092   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7093     if (Op.getValueType() == MVT::i32) {
7094       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7095         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7096                                  MVT::f64, Op.getOperand(0),
7097                                  DAG.getIntPtrConstant(0, dl));
7098         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7099                                  MVT::f64, Op.getOperand(0),
7100                                  DAG.getIntPtrConstant(1, dl));
7101 
7102         // Add the two halves of the long double in round-to-zero mode.
7103         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7104 
7105         // Now use a smaller FP_TO_SINT.
7106         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7107       }
7108       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7109         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7110         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7111         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7112         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7113         // FIXME: generated code sucks.
7114         // TODO: Are there fast-math-flags to propagate to this FSUB?
7115         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7116                                    Op.getOperand(0), Tmp);
7117         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7118         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7119                            DAG.getConstant(0x80000000, dl, MVT::i32));
7120         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7121                                     Op.getOperand(0));
7122         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7123                                ISD::SETGE);
7124       }
7125     }
7126 
7127     return SDValue();
7128   }
7129 
7130   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7131     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7132 
7133   ReuseLoadInfo RLI;
7134   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7135 
7136   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7137                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7138 }
7139 
7140 // We're trying to insert a regular store, S, and then a load, L. If the
7141 // incoming value, O, is a load, we might just be able to have our load use the
7142 // address used by O. However, we don't know if anything else will store to
7143 // that address before we can load from it. To prevent this situation, we need
7144 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7145 // the same chain operand as O, we create a token factor from the chain results
7146 // of O and L, and we replace all uses of O's chain result with that token
7147 // factor (see spliceIntoChain below for this last part).
7148 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7149                                             ReuseLoadInfo &RLI,
7150                                             SelectionDAG &DAG,
7151                                             ISD::LoadExtType ET) const {
7152   SDLoc dl(Op);
7153   if (ET == ISD::NON_EXTLOAD &&
7154       (Op.getOpcode() == ISD::FP_TO_UINT ||
7155        Op.getOpcode() == ISD::FP_TO_SINT) &&
7156       isOperationLegalOrCustom(Op.getOpcode(),
7157                                Op.getOperand(0).getValueType())) {
7158 
7159     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7160     return true;
7161   }
7162 
7163   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7164   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7165       LD->isNonTemporal())
7166     return false;
7167   if (LD->getMemoryVT() != MemVT)
7168     return false;
7169 
7170   RLI.Ptr = LD->getBasePtr();
7171   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7172     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7173            "Non-pre-inc AM on PPC?");
7174     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7175                           LD->getOffset());
7176   }
7177 
7178   RLI.Chain = LD->getChain();
7179   RLI.MPI = LD->getPointerInfo();
7180   RLI.IsDereferenceable = LD->isDereferenceable();
7181   RLI.IsInvariant = LD->isInvariant();
7182   RLI.Alignment = LD->getAlignment();
7183   RLI.AAInfo = LD->getAAInfo();
7184   RLI.Ranges = LD->getRanges();
7185 
7186   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7187   return true;
7188 }
7189 
7190 // Given the head of the old chain, ResChain, insert a token factor containing
7191 // it and NewResChain, and make users of ResChain now be users of that token
7192 // factor.
7193 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7194 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7195                                         SDValue NewResChain,
7196                                         SelectionDAG &DAG) const {
7197   if (!ResChain)
7198     return;
7199 
7200   SDLoc dl(NewResChain);
7201 
7202   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7203                            NewResChain, DAG.getUNDEF(MVT::Other));
7204   assert(TF.getNode() != NewResChain.getNode() &&
7205          "A new TF really is required here");
7206 
7207   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7208   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7209 }
7210 
7211 /// Analyze profitability of direct move
7212 /// prefer float load to int load plus direct move
7213 /// when there is no integer use of int load
7214 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7215   SDNode *Origin = Op.getOperand(0).getNode();
7216   if (Origin->getOpcode() != ISD::LOAD)
7217     return true;
7218 
7219   // If there is no LXSIBZX/LXSIHZX, like Power8,
7220   // prefer direct move if the memory size is 1 or 2 bytes.
7221   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7222   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7223     return true;
7224 
7225   for (SDNode::use_iterator UI = Origin->use_begin(),
7226                             UE = Origin->use_end();
7227        UI != UE; ++UI) {
7228 
7229     // Only look at the users of the loaded value.
7230     if (UI.getUse().get().getResNo() != 0)
7231       continue;
7232 
7233     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7234         UI->getOpcode() != ISD::UINT_TO_FP)
7235       return true;
7236   }
7237 
7238   return false;
7239 }
7240 
7241 /// Custom lowers integer to floating point conversions to use
7242 /// the direct move instructions available in ISA 2.07 to avoid the
7243 /// need for load/store combinations.
7244 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7245                                                     SelectionDAG &DAG,
7246                                                     const SDLoc &dl) const {
7247   assert((Op.getValueType() == MVT::f32 ||
7248           Op.getValueType() == MVT::f64) &&
7249          "Invalid floating point type as target of conversion");
7250   assert(Subtarget.hasFPCVT() &&
7251          "Int to FP conversions with direct moves require FPCVT");
7252   SDValue FP;
7253   SDValue Src = Op.getOperand(0);
7254   bool SinglePrec = Op.getValueType() == MVT::f32;
7255   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7256   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7257   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7258                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7259 
7260   if (WordInt) {
7261     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7262                      dl, MVT::f64, Src);
7263     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7264   }
7265   else {
7266     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7267     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7268   }
7269 
7270   return FP;
7271 }
7272 
7273 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7274                                           SelectionDAG &DAG) const {
7275   SDLoc dl(Op);
7276 
7277   // Conversions to f128 are legal.
7278   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7279     return Op;
7280 
7281   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7282     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7283       return SDValue();
7284 
7285     SDValue Value = Op.getOperand(0);
7286     // The values are now known to be -1 (false) or 1 (true). To convert this
7287     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7288     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7289     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7290 
7291     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7292 
7293     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7294 
7295     if (Op.getValueType() != MVT::v4f64)
7296       Value = DAG.getNode(ISD::FP_ROUND, dl,
7297                           Op.getValueType(), Value,
7298                           DAG.getIntPtrConstant(1, dl));
7299     return Value;
7300   }
7301 
7302   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7303   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7304     return SDValue();
7305 
7306   if (Op.getOperand(0).getValueType() == MVT::i1)
7307     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7308                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7309                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7310 
7311   // If we have direct moves, we can do all the conversion, skip the store/load
7312   // however, without FPCVT we can't do most conversions.
7313   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7314       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7315     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7316 
7317   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7318          "UINT_TO_FP is supported only with FPCVT");
7319 
7320   // If we have FCFIDS, then use it when converting to single-precision.
7321   // Otherwise, convert to double-precision and then round.
7322   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7323                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7324                                                             : PPCISD::FCFIDS)
7325                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7326                                                             : PPCISD::FCFID);
7327   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7328                   ? MVT::f32
7329                   : MVT::f64;
7330 
7331   if (Op.getOperand(0).getValueType() == MVT::i64) {
7332     SDValue SINT = Op.getOperand(0);
7333     // When converting to single-precision, we actually need to convert
7334     // to double-precision first and then round to single-precision.
7335     // To avoid double-rounding effects during that operation, we have
7336     // to prepare the input operand.  Bits that might be truncated when
7337     // converting to double-precision are replaced by a bit that won't
7338     // be lost at this stage, but is below the single-precision rounding
7339     // position.
7340     //
7341     // However, if -enable-unsafe-fp-math is in effect, accept double
7342     // rounding to avoid the extra overhead.
7343     if (Op.getValueType() == MVT::f32 &&
7344         !Subtarget.hasFPCVT() &&
7345         !DAG.getTarget().Options.UnsafeFPMath) {
7346 
7347       // Twiddle input to make sure the low 11 bits are zero.  (If this
7348       // is the case, we are guaranteed the value will fit into the 53 bit
7349       // mantissa of an IEEE double-precision value without rounding.)
7350       // If any of those low 11 bits were not zero originally, make sure
7351       // bit 12 (value 2048) is set instead, so that the final rounding
7352       // to single-precision gets the correct result.
7353       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7354                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7355       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7356                           Round, DAG.getConstant(2047, dl, MVT::i64));
7357       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7358       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7359                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7360 
7361       // However, we cannot use that value unconditionally: if the magnitude
7362       // of the input value is small, the bit-twiddling we did above might
7363       // end up visibly changing the output.  Fortunately, in that case, we
7364       // don't need to twiddle bits since the original input will convert
7365       // exactly to double-precision floating-point already.  Therefore,
7366       // construct a conditional to use the original value if the top 11
7367       // bits are all sign-bit copies, and use the rounded value computed
7368       // above otherwise.
7369       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7370                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7371       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7372                          Cond, DAG.getConstant(1, dl, MVT::i64));
7373       Cond = DAG.getSetCC(dl, MVT::i32,
7374                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7375 
7376       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7377     }
7378 
7379     ReuseLoadInfo RLI;
7380     SDValue Bits;
7381 
7382     MachineFunction &MF = DAG.getMachineFunction();
7383     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7384       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7385                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7386       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7387     } else if (Subtarget.hasLFIWAX() &&
7388                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7389       MachineMemOperand *MMO =
7390         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7391                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7392       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7393       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7394                                      DAG.getVTList(MVT::f64, MVT::Other),
7395                                      Ops, MVT::i32, MMO);
7396       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7397     } else if (Subtarget.hasFPCVT() &&
7398                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7399       MachineMemOperand *MMO =
7400         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7401                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7402       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7403       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7404                                      DAG.getVTList(MVT::f64, MVT::Other),
7405                                      Ops, MVT::i32, MMO);
7406       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7407     } else if (((Subtarget.hasLFIWAX() &&
7408                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7409                 (Subtarget.hasFPCVT() &&
7410                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7411                SINT.getOperand(0).getValueType() == MVT::i32) {
7412       MachineFrameInfo &MFI = MF.getFrameInfo();
7413       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7414 
7415       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7416       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7417 
7418       SDValue Store =
7419           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7420                        MachinePointerInfo::getFixedStack(
7421                            DAG.getMachineFunction(), FrameIdx));
7422 
7423       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7424              "Expected an i32 store");
7425 
7426       RLI.Ptr = FIdx;
7427       RLI.Chain = Store;
7428       RLI.MPI =
7429           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7430       RLI.Alignment = 4;
7431 
7432       MachineMemOperand *MMO =
7433         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7434                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7435       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7436       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7437                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7438                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7439                                      Ops, MVT::i32, MMO);
7440     } else
7441       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7442 
7443     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7444 
7445     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7446       FP = DAG.getNode(ISD::FP_ROUND, dl,
7447                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7448     return FP;
7449   }
7450 
7451   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7452          "Unhandled INT_TO_FP type in custom expander!");
7453   // Since we only generate this in 64-bit mode, we can take advantage of
7454   // 64-bit registers.  In particular, sign extend the input value into the
7455   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7456   // then lfd it and fcfid it.
7457   MachineFunction &MF = DAG.getMachineFunction();
7458   MachineFrameInfo &MFI = MF.getFrameInfo();
7459   EVT PtrVT = getPointerTy(MF.getDataLayout());
7460 
7461   SDValue Ld;
7462   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7463     ReuseLoadInfo RLI;
7464     bool ReusingLoad;
7465     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7466                                             DAG))) {
7467       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7468       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7469 
7470       SDValue Store =
7471           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7472                        MachinePointerInfo::getFixedStack(
7473                            DAG.getMachineFunction(), FrameIdx));
7474 
7475       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7476              "Expected an i32 store");
7477 
7478       RLI.Ptr = FIdx;
7479       RLI.Chain = Store;
7480       RLI.MPI =
7481           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7482       RLI.Alignment = 4;
7483     }
7484 
7485     MachineMemOperand *MMO =
7486       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7487                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7488     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7489     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7490                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7491                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7492                                  Ops, MVT::i32, MMO);
7493     if (ReusingLoad)
7494       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7495   } else {
7496     assert(Subtarget.isPPC64() &&
7497            "i32->FP without LFIWAX supported only on PPC64");
7498 
7499     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7500     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7501 
7502     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7503                                 Op.getOperand(0));
7504 
7505     // STD the extended value into the stack slot.
7506     SDValue Store = DAG.getStore(
7507         DAG.getEntryNode(), dl, Ext64, FIdx,
7508         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7509 
7510     // Load the value as a double.
7511     Ld = DAG.getLoad(
7512         MVT::f64, dl, Store, FIdx,
7513         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7514   }
7515 
7516   // FCFID it and return it.
7517   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7518   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7519     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7520                      DAG.getIntPtrConstant(0, dl));
7521   return FP;
7522 }
7523 
7524 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7525                                             SelectionDAG &DAG) const {
7526   SDLoc dl(Op);
7527   /*
7528    The rounding mode is in bits 30:31 of FPSR, and has the following
7529    settings:
7530      00 Round to nearest
7531      01 Round to 0
7532      10 Round to +inf
7533      11 Round to -inf
7534 
7535   FLT_ROUNDS, on the other hand, expects the following:
7536     -1 Undefined
7537      0 Round to 0
7538      1 Round to nearest
7539      2 Round to +inf
7540      3 Round to -inf
7541 
7542   To perform the conversion, we do:
7543     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7544   */
7545 
7546   MachineFunction &MF = DAG.getMachineFunction();
7547   EVT VT = Op.getValueType();
7548   EVT PtrVT = getPointerTy(MF.getDataLayout());
7549 
7550   // Save FP Control Word to register
7551   EVT NodeTys[] = {
7552     MVT::f64,    // return register
7553     MVT::Glue    // unused in this context
7554   };
7555   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7556 
7557   // Save FP register to stack slot
7558   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7559   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7560   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7561                                MachinePointerInfo());
7562 
7563   // Load FP Control Word from low 32 bits of stack slot.
7564   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7565   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7566   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7567 
7568   // Transform as necessary
7569   SDValue CWD1 =
7570     DAG.getNode(ISD::AND, dl, MVT::i32,
7571                 CWD, DAG.getConstant(3, dl, MVT::i32));
7572   SDValue CWD2 =
7573     DAG.getNode(ISD::SRL, dl, MVT::i32,
7574                 DAG.getNode(ISD::AND, dl, MVT::i32,
7575                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7576                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7577                             DAG.getConstant(3, dl, MVT::i32)),
7578                 DAG.getConstant(1, dl, MVT::i32));
7579 
7580   SDValue RetVal =
7581     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7582 
7583   return DAG.getNode((VT.getSizeInBits() < 16 ?
7584                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7585 }
7586 
7587 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7588   EVT VT = Op.getValueType();
7589   unsigned BitWidth = VT.getSizeInBits();
7590   SDLoc dl(Op);
7591   assert(Op.getNumOperands() == 3 &&
7592          VT == Op.getOperand(1).getValueType() &&
7593          "Unexpected SHL!");
7594 
7595   // Expand into a bunch of logical ops.  Note that these ops
7596   // depend on the PPC behavior for oversized shift amounts.
7597   SDValue Lo = Op.getOperand(0);
7598   SDValue Hi = Op.getOperand(1);
7599   SDValue Amt = Op.getOperand(2);
7600   EVT AmtVT = Amt.getValueType();
7601 
7602   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7603                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7604   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7605   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7606   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7607   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7608                              DAG.getConstant(-BitWidth, dl, AmtVT));
7609   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7610   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7611   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7612   SDValue OutOps[] = { OutLo, OutHi };
7613   return DAG.getMergeValues(OutOps, dl);
7614 }
7615 
7616 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7617   EVT VT = Op.getValueType();
7618   SDLoc dl(Op);
7619   unsigned BitWidth = VT.getSizeInBits();
7620   assert(Op.getNumOperands() == 3 &&
7621          VT == Op.getOperand(1).getValueType() &&
7622          "Unexpected SRL!");
7623 
7624   // Expand into a bunch of logical ops.  Note that these ops
7625   // depend on the PPC behavior for oversized shift amounts.
7626   SDValue Lo = Op.getOperand(0);
7627   SDValue Hi = Op.getOperand(1);
7628   SDValue Amt = Op.getOperand(2);
7629   EVT AmtVT = Amt.getValueType();
7630 
7631   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7632                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7633   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7634   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7635   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7636   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7637                              DAG.getConstant(-BitWidth, dl, AmtVT));
7638   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7639   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7640   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7641   SDValue OutOps[] = { OutLo, OutHi };
7642   return DAG.getMergeValues(OutOps, dl);
7643 }
7644 
7645 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7646   SDLoc dl(Op);
7647   EVT VT = Op.getValueType();
7648   unsigned BitWidth = VT.getSizeInBits();
7649   assert(Op.getNumOperands() == 3 &&
7650          VT == Op.getOperand(1).getValueType() &&
7651          "Unexpected SRA!");
7652 
7653   // Expand into a bunch of logical ops, followed by a select_cc.
7654   SDValue Lo = Op.getOperand(0);
7655   SDValue Hi = Op.getOperand(1);
7656   SDValue Amt = Op.getOperand(2);
7657   EVT AmtVT = Amt.getValueType();
7658 
7659   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7660                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7661   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7662   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7663   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7664   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7665                              DAG.getConstant(-BitWidth, dl, AmtVT));
7666   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7667   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7668   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7669                                   Tmp4, Tmp6, ISD::SETLE);
7670   SDValue OutOps[] = { OutLo, OutHi };
7671   return DAG.getMergeValues(OutOps, dl);
7672 }
7673 
7674 //===----------------------------------------------------------------------===//
7675 // Vector related lowering.
7676 //
7677 
7678 /// BuildSplatI - Build a canonical splati of Val with an element size of
7679 /// SplatSize.  Cast the result to VT.
7680 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7681                            SelectionDAG &DAG, const SDLoc &dl) {
7682   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7683 
7684   static const MVT VTys[] = { // canonical VT to use for each size.
7685     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7686   };
7687 
7688   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7689 
7690   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7691   if (Val == -1)
7692     SplatSize = 1;
7693 
7694   EVT CanonicalVT = VTys[SplatSize-1];
7695 
7696   // Build a canonical splat for this value.
7697   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7698 }
7699 
7700 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7701 /// specified intrinsic ID.
7702 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7703                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7704   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7705   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7706                      DAG.getConstant(IID, dl, MVT::i32), Op);
7707 }
7708 
7709 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7710 /// specified intrinsic ID.
7711 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7712                                 SelectionDAG &DAG, const SDLoc &dl,
7713                                 EVT DestVT = MVT::Other) {
7714   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7715   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7716                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7717 }
7718 
7719 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7720 /// specified intrinsic ID.
7721 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7722                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7723                                 EVT DestVT = MVT::Other) {
7724   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7725   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7726                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7727 }
7728 
7729 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7730 /// amount.  The result has the specified value type.
7731 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7732                            SelectionDAG &DAG, const SDLoc &dl) {
7733   // Force LHS/RHS to be the right type.
7734   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7735   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7736 
7737   int Ops[16];
7738   for (unsigned i = 0; i != 16; ++i)
7739     Ops[i] = i + Amt;
7740   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7741   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7742 }
7743 
7744 /// Do we have an efficient pattern in a .td file for this node?
7745 ///
7746 /// \param V - pointer to the BuildVectorSDNode being matched
7747 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7748 ///
7749 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7750 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7751 /// the opposite is true (expansion is beneficial) are:
7752 /// - The node builds a vector out of integers that are not 32 or 64-bits
7753 /// - The node builds a vector out of constants
7754 /// - The node is a "load-and-splat"
7755 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7756 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7757                                             bool HasDirectMove,
7758                                             bool HasP8Vector) {
7759   EVT VecVT = V->getValueType(0);
7760   bool RightType = VecVT == MVT::v2f64 ||
7761     (HasP8Vector && VecVT == MVT::v4f32) ||
7762     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7763   if (!RightType)
7764     return false;
7765 
7766   bool IsSplat = true;
7767   bool IsLoad = false;
7768   SDValue Op0 = V->getOperand(0);
7769 
7770   // This function is called in a block that confirms the node is not a constant
7771   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7772   // different constants.
7773   if (V->isConstant())
7774     return false;
7775   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7776     if (V->getOperand(i).isUndef())
7777       return false;
7778     // We want to expand nodes that represent load-and-splat even if the
7779     // loaded value is a floating point truncation or conversion to int.
7780     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7781         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7782          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7783         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7784          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7785         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7786          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7787       IsLoad = true;
7788     // If the operands are different or the input is not a load and has more
7789     // uses than just this BV node, then it isn't a splat.
7790     if (V->getOperand(i) != Op0 ||
7791         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7792       IsSplat = false;
7793   }
7794   return !(IsSplat && IsLoad);
7795 }
7796 
7797 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
7798 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
7799 
7800   SDLoc dl(Op);
7801   SDValue Op0 = Op->getOperand(0);
7802 
7803   if (!EnableQuadPrecision ||
7804       (Op.getValueType() != MVT::f128 ) ||
7805       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
7806       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
7807       (Op0.getOperand(1).getValueType() != MVT::i64))
7808     return SDValue();
7809 
7810   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
7811                      Op0.getOperand(1));
7812 }
7813 
7814 // If this is a case we can't handle, return null and let the default
7815 // expansion code take care of it.  If we CAN select this case, and if it
7816 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7817 // this case more efficiently than a constant pool load, lower it to the
7818 // sequence of ops that should be used.
7819 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7820                                              SelectionDAG &DAG) const {
7821   SDLoc dl(Op);
7822   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7823   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7824 
7825   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7826     // We first build an i32 vector, load it into a QPX register,
7827     // then convert it to a floating-point vector and compare it
7828     // to a zero vector to get the boolean result.
7829     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7830     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7831     MachinePointerInfo PtrInfo =
7832         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7833     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7834     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7835 
7836     assert(BVN->getNumOperands() == 4 &&
7837       "BUILD_VECTOR for v4i1 does not have 4 operands");
7838 
7839     bool IsConst = true;
7840     for (unsigned i = 0; i < 4; ++i) {
7841       if (BVN->getOperand(i).isUndef()) continue;
7842       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7843         IsConst = false;
7844         break;
7845       }
7846     }
7847 
7848     if (IsConst) {
7849       Constant *One =
7850         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7851       Constant *NegOne =
7852         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7853 
7854       Constant *CV[4];
7855       for (unsigned i = 0; i < 4; ++i) {
7856         if (BVN->getOperand(i).isUndef())
7857           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7858         else if (isNullConstant(BVN->getOperand(i)))
7859           CV[i] = NegOne;
7860         else
7861           CV[i] = One;
7862       }
7863 
7864       Constant *CP = ConstantVector::get(CV);
7865       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7866                                           16 /* alignment */);
7867 
7868       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7869       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7870       return DAG.getMemIntrinsicNode(
7871           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7872           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7873     }
7874 
7875     SmallVector<SDValue, 4> Stores;
7876     for (unsigned i = 0; i < 4; ++i) {
7877       if (BVN->getOperand(i).isUndef()) continue;
7878 
7879       unsigned Offset = 4*i;
7880       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7881       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7882 
7883       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7884       if (StoreSize > 4) {
7885         Stores.push_back(
7886             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7887                               PtrInfo.getWithOffset(Offset), MVT::i32));
7888       } else {
7889         SDValue StoreValue = BVN->getOperand(i);
7890         if (StoreSize < 4)
7891           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7892 
7893         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7894                                       PtrInfo.getWithOffset(Offset)));
7895       }
7896     }
7897 
7898     SDValue StoreChain;
7899     if (!Stores.empty())
7900       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7901     else
7902       StoreChain = DAG.getEntryNode();
7903 
7904     // Now load from v4i32 into the QPX register; this will extend it to
7905     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7906     // is typed as v4f64 because the QPX register integer states are not
7907     // explicitly represented.
7908 
7909     SDValue Ops[] = {StoreChain,
7910                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7911                      FIdx};
7912     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7913 
7914     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7915       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7916     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7917       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7918       LoadedVect);
7919 
7920     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7921 
7922     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7923   }
7924 
7925   // All other QPX vectors are handled by generic code.
7926   if (Subtarget.hasQPX())
7927     return SDValue();
7928 
7929   // Check if this is a splat of a constant value.
7930   APInt APSplatBits, APSplatUndef;
7931   unsigned SplatBitSize;
7932   bool HasAnyUndefs;
7933   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7934                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7935       SplatBitSize > 32) {
7936     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7937     // lowered to VSX instructions under certain conditions.
7938     // Without VSX, there is no pattern more efficient than expanding the node.
7939     if (Subtarget.hasVSX() &&
7940         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
7941                                         Subtarget.hasP8Vector()))
7942       return Op;
7943     return SDValue();
7944   }
7945 
7946   unsigned SplatBits = APSplatBits.getZExtValue();
7947   unsigned SplatUndef = APSplatUndef.getZExtValue();
7948   unsigned SplatSize = SplatBitSize / 8;
7949 
7950   // First, handle single instruction cases.
7951 
7952   // All zeros?
7953   if (SplatBits == 0) {
7954     // Canonicalize all zero vectors to be v4i32.
7955     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7956       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7957       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7958     }
7959     return Op;
7960   }
7961 
7962   // We have XXSPLTIB for constant splats one byte wide
7963   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7964     // This is a splat of 1-byte elements with some elements potentially undef.
7965     // Rather than trying to match undef in the SDAG patterns, ensure that all
7966     // elements are the same constant.
7967     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7968       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7969                                                        dl, MVT::i32));
7970       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7971       if (Op.getValueType() != MVT::v16i8)
7972         return DAG.getBitcast(Op.getValueType(), NewBV);
7973       return NewBV;
7974     }
7975 
7976     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
7977     // detect that constant splats like v8i16: 0xABAB are really just splats
7978     // of a 1-byte constant. In this case, we need to convert the node to a
7979     // splat of v16i8 and a bitcast.
7980     if (Op.getValueType() != MVT::v16i8)
7981       return DAG.getBitcast(Op.getValueType(),
7982                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
7983 
7984     return Op;
7985   }
7986 
7987   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7988   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7989                     (32-SplatBitSize));
7990   if (SextVal >= -16 && SextVal <= 15)
7991     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7992 
7993   // Two instruction sequences.
7994 
7995   // If this value is in the range [-32,30] and is even, use:
7996   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7997   // If this value is in the range [17,31] and is odd, use:
7998   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7999   // If this value is in the range [-31,-17] and is odd, use:
8000   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8001   // Note the last two are three-instruction sequences.
8002   if (SextVal >= -32 && SextVal <= 31) {
8003     // To avoid having these optimizations undone by constant folding,
8004     // we convert to a pseudo that will be expanded later into one of
8005     // the above forms.
8006     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8007     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8008               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8009     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8010     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8011     if (VT == Op.getValueType())
8012       return RetVal;
8013     else
8014       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8015   }
8016 
8017   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8018   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8019   // for fneg/fabs.
8020   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8021     // Make -1 and vspltisw -1:
8022     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8023 
8024     // Make the VSLW intrinsic, computing 0x8000_0000.
8025     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8026                                    OnesV, DAG, dl);
8027 
8028     // xor by OnesV to invert it.
8029     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8030     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8031   }
8032 
8033   // Check to see if this is a wide variety of vsplti*, binop self cases.
8034   static const signed char SplatCsts[] = {
8035     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8036     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8037   };
8038 
8039   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8040     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8041     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8042     int i = SplatCsts[idx];
8043 
8044     // Figure out what shift amount will be used by altivec if shifted by i in
8045     // this splat size.
8046     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8047 
8048     // vsplti + shl self.
8049     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8050       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8051       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8052         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8053         Intrinsic::ppc_altivec_vslw
8054       };
8055       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8056       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8057     }
8058 
8059     // vsplti + srl self.
8060     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8061       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8062       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8063         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8064         Intrinsic::ppc_altivec_vsrw
8065       };
8066       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8067       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8068     }
8069 
8070     // vsplti + sra self.
8071     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8072       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8073       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8074         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8075         Intrinsic::ppc_altivec_vsraw
8076       };
8077       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8078       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8079     }
8080 
8081     // vsplti + rol self.
8082     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8083                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8084       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8085       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8086         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8087         Intrinsic::ppc_altivec_vrlw
8088       };
8089       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8090       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8091     }
8092 
8093     // t = vsplti c, result = vsldoi t, t, 1
8094     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8095       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8096       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8097       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8098     }
8099     // t = vsplti c, result = vsldoi t, t, 2
8100     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8101       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8102       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8103       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8104     }
8105     // t = vsplti c, result = vsldoi t, t, 3
8106     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8107       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8108       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8109       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8110     }
8111   }
8112 
8113   return SDValue();
8114 }
8115 
8116 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8117 /// the specified operations to build the shuffle.
8118 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8119                                       SDValue RHS, SelectionDAG &DAG,
8120                                       const SDLoc &dl) {
8121   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8122   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8123   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8124 
8125   enum {
8126     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8127     OP_VMRGHW,
8128     OP_VMRGLW,
8129     OP_VSPLTISW0,
8130     OP_VSPLTISW1,
8131     OP_VSPLTISW2,
8132     OP_VSPLTISW3,
8133     OP_VSLDOI4,
8134     OP_VSLDOI8,
8135     OP_VSLDOI12
8136   };
8137 
8138   if (OpNum == OP_COPY) {
8139     if (LHSID == (1*9+2)*9+3) return LHS;
8140     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8141     return RHS;
8142   }
8143 
8144   SDValue OpLHS, OpRHS;
8145   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8146   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8147 
8148   int ShufIdxs[16];
8149   switch (OpNum) {
8150   default: llvm_unreachable("Unknown i32 permute!");
8151   case OP_VMRGHW:
8152     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8153     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8154     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8155     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8156     break;
8157   case OP_VMRGLW:
8158     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8159     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8160     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8161     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8162     break;
8163   case OP_VSPLTISW0:
8164     for (unsigned i = 0; i != 16; ++i)
8165       ShufIdxs[i] = (i&3)+0;
8166     break;
8167   case OP_VSPLTISW1:
8168     for (unsigned i = 0; i != 16; ++i)
8169       ShufIdxs[i] = (i&3)+4;
8170     break;
8171   case OP_VSPLTISW2:
8172     for (unsigned i = 0; i != 16; ++i)
8173       ShufIdxs[i] = (i&3)+8;
8174     break;
8175   case OP_VSPLTISW3:
8176     for (unsigned i = 0; i != 16; ++i)
8177       ShufIdxs[i] = (i&3)+12;
8178     break;
8179   case OP_VSLDOI4:
8180     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8181   case OP_VSLDOI8:
8182     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8183   case OP_VSLDOI12:
8184     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8185   }
8186   EVT VT = OpLHS.getValueType();
8187   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8188   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8189   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8190   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8191 }
8192 
8193 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8194 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8195 /// SDValue.
8196 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8197                                            SelectionDAG &DAG) const {
8198   const unsigned BytesInVector = 16;
8199   bool IsLE = Subtarget.isLittleEndian();
8200   SDLoc dl(N);
8201   SDValue V1 = N->getOperand(0);
8202   SDValue V2 = N->getOperand(1);
8203   unsigned ShiftElts = 0, InsertAtByte = 0;
8204   bool Swap = false;
8205 
8206   // Shifts required to get the byte we want at element 7.
8207   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8208                                    0, 15, 14, 13, 12, 11, 10, 9};
8209   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8210                                 1, 2,  3,  4,  5,  6,  7,  8};
8211 
8212   ArrayRef<int> Mask = N->getMask();
8213   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8214 
8215   // For each mask element, find out if we're just inserting something
8216   // from V2 into V1 or vice versa.
8217   // Possible permutations inserting an element from V2 into V1:
8218   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8219   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8220   //   ...
8221   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8222   // Inserting from V1 into V2 will be similar, except mask range will be
8223   // [16,31].
8224 
8225   bool FoundCandidate = false;
8226   // If both vector operands for the shuffle are the same vector, the mask
8227   // will contain only elements from the first one and the second one will be
8228   // undef.
8229   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8230   // Go through the mask of half-words to find an element that's being moved
8231   // from one vector to the other.
8232   for (unsigned i = 0; i < BytesInVector; ++i) {
8233     unsigned CurrentElement = Mask[i];
8234     // If 2nd operand is undefined, we should only look for element 7 in the
8235     // Mask.
8236     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8237       continue;
8238 
8239     bool OtherElementsInOrder = true;
8240     // Examine the other elements in the Mask to see if they're in original
8241     // order.
8242     for (unsigned j = 0; j < BytesInVector; ++j) {
8243       if (j == i)
8244         continue;
8245       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8246       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8247       // in which we always assume we're always picking from the 1st operand.
8248       int MaskOffset =
8249           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8250       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8251         OtherElementsInOrder = false;
8252         break;
8253       }
8254     }
8255     // If other elements are in original order, we record the number of shifts
8256     // we need to get the element we want into element 7. Also record which byte
8257     // in the vector we should insert into.
8258     if (OtherElementsInOrder) {
8259       // If 2nd operand is undefined, we assume no shifts and no swapping.
8260       if (V2.isUndef()) {
8261         ShiftElts = 0;
8262         Swap = false;
8263       } else {
8264         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8265         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8266                          : BigEndianShifts[CurrentElement & 0xF];
8267         Swap = CurrentElement < BytesInVector;
8268       }
8269       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8270       FoundCandidate = true;
8271       break;
8272     }
8273   }
8274 
8275   if (!FoundCandidate)
8276     return SDValue();
8277 
8278   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8279   // optionally with VECSHL if shift is required.
8280   if (Swap)
8281     std::swap(V1, V2);
8282   if (V2.isUndef())
8283     V2 = V1;
8284   if (ShiftElts) {
8285     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8286                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8287     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8288                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8289   }
8290   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8291                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8292 }
8293 
8294 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8295 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8296 /// SDValue.
8297 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8298                                            SelectionDAG &DAG) const {
8299   const unsigned NumHalfWords = 8;
8300   const unsigned BytesInVector = NumHalfWords * 2;
8301   // Check that the shuffle is on half-words.
8302   if (!isNByteElemShuffleMask(N, 2, 1))
8303     return SDValue();
8304 
8305   bool IsLE = Subtarget.isLittleEndian();
8306   SDLoc dl(N);
8307   SDValue V1 = N->getOperand(0);
8308   SDValue V2 = N->getOperand(1);
8309   unsigned ShiftElts = 0, InsertAtByte = 0;
8310   bool Swap = false;
8311 
8312   // Shifts required to get the half-word we want at element 3.
8313   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8314   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8315 
8316   uint32_t Mask = 0;
8317   uint32_t OriginalOrderLow = 0x1234567;
8318   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8319   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8320   // 32-bit space, only need 4-bit nibbles per element.
8321   for (unsigned i = 0; i < NumHalfWords; ++i) {
8322     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8323     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8324   }
8325 
8326   // For each mask element, find out if we're just inserting something
8327   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8328   // from V2 into V1:
8329   //   X, 1, 2, 3, 4, 5, 6, 7
8330   //   0, X, 2, 3, 4, 5, 6, 7
8331   //   0, 1, X, 3, 4, 5, 6, 7
8332   //   0, 1, 2, X, 4, 5, 6, 7
8333   //   0, 1, 2, 3, X, 5, 6, 7
8334   //   0, 1, 2, 3, 4, X, 6, 7
8335   //   0, 1, 2, 3, 4, 5, X, 7
8336   //   0, 1, 2, 3, 4, 5, 6, X
8337   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8338 
8339   bool FoundCandidate = false;
8340   // Go through the mask of half-words to find an element that's being moved
8341   // from one vector to the other.
8342   for (unsigned i = 0; i < NumHalfWords; ++i) {
8343     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8344     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8345     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8346     uint32_t TargetOrder = 0x0;
8347 
8348     // If both vector operands for the shuffle are the same vector, the mask
8349     // will contain only elements from the first one and the second one will be
8350     // undef.
8351     if (V2.isUndef()) {
8352       ShiftElts = 0;
8353       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8354       TargetOrder = OriginalOrderLow;
8355       Swap = false;
8356       // Skip if not the correct element or mask of other elements don't equal
8357       // to our expected order.
8358       if (MaskOneElt == VINSERTHSrcElem &&
8359           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8360         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8361         FoundCandidate = true;
8362         break;
8363       }
8364     } else { // If both operands are defined.
8365       // Target order is [8,15] if the current mask is between [0,7].
8366       TargetOrder =
8367           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8368       // Skip if mask of other elements don't equal our expected order.
8369       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8370         // We only need the last 3 bits for the number of shifts.
8371         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8372                          : BigEndianShifts[MaskOneElt & 0x7];
8373         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8374         Swap = MaskOneElt < NumHalfWords;
8375         FoundCandidate = true;
8376         break;
8377       }
8378     }
8379   }
8380 
8381   if (!FoundCandidate)
8382     return SDValue();
8383 
8384   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8385   // optionally with VECSHL if shift is required.
8386   if (Swap)
8387     std::swap(V1, V2);
8388   if (V2.isUndef())
8389     V2 = V1;
8390   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8391   if (ShiftElts) {
8392     // Double ShiftElts because we're left shifting on v16i8 type.
8393     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8394                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8395     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8396     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8397                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8398     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8399   }
8400   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8401   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8402                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8403   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8404 }
8405 
8406 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8407 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8408 /// return the code it can be lowered into.  Worst case, it can always be
8409 /// lowered into a vperm.
8410 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8411                                                SelectionDAG &DAG) const {
8412   SDLoc dl(Op);
8413   SDValue V1 = Op.getOperand(0);
8414   SDValue V2 = Op.getOperand(1);
8415   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8416   EVT VT = Op.getValueType();
8417   bool isLittleEndian = Subtarget.isLittleEndian();
8418 
8419   unsigned ShiftElts, InsertAtByte;
8420   bool Swap = false;
8421   if (Subtarget.hasP9Vector() &&
8422       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8423                            isLittleEndian)) {
8424     if (Swap)
8425       std::swap(V1, V2);
8426     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8427     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8428     if (ShiftElts) {
8429       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8430                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8431       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8432                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8433       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8434     }
8435     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8436                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8437     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8438   }
8439 
8440   if (Subtarget.hasP9Altivec()) {
8441     SDValue NewISDNode;
8442     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8443       return NewISDNode;
8444 
8445     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8446       return NewISDNode;
8447   }
8448 
8449   if (Subtarget.hasVSX() &&
8450       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8451     if (Swap)
8452       std::swap(V1, V2);
8453     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8454     SDValue Conv2 =
8455         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8456 
8457     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8458                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8459     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8460   }
8461 
8462   if (Subtarget.hasVSX() &&
8463     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8464     if (Swap)
8465       std::swap(V1, V2);
8466     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8467     SDValue Conv2 =
8468         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8469 
8470     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8471                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8472     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8473   }
8474 
8475   if (Subtarget.hasP9Vector()) {
8476      if (PPC::isXXBRHShuffleMask(SVOp)) {
8477       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8478       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8479       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8480     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8481       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8482       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8483       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8484     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8485       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8486       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8487       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8488     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8489       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8490       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8491       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8492     }
8493   }
8494 
8495   if (Subtarget.hasVSX()) {
8496     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8497       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8498 
8499       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8500       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8501                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8502       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8503     }
8504 
8505     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8506     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8507       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8508       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8509       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8510     }
8511   }
8512 
8513   if (Subtarget.hasQPX()) {
8514     if (VT.getVectorNumElements() != 4)
8515       return SDValue();
8516 
8517     if (V2.isUndef()) V2 = V1;
8518 
8519     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8520     if (AlignIdx != -1) {
8521       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8522                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8523     } else if (SVOp->isSplat()) {
8524       int SplatIdx = SVOp->getSplatIndex();
8525       if (SplatIdx >= 4) {
8526         std::swap(V1, V2);
8527         SplatIdx -= 4;
8528       }
8529 
8530       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8531                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8532     }
8533 
8534     // Lower this into a qvgpci/qvfperm pair.
8535 
8536     // Compute the qvgpci literal
8537     unsigned idx = 0;
8538     for (unsigned i = 0; i < 4; ++i) {
8539       int m = SVOp->getMaskElt(i);
8540       unsigned mm = m >= 0 ? (unsigned) m : i;
8541       idx |= mm << (3-i)*3;
8542     }
8543 
8544     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8545                              DAG.getConstant(idx, dl, MVT::i32));
8546     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8547   }
8548 
8549   // Cases that are handled by instructions that take permute immediates
8550   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8551   // selected by the instruction selector.
8552   if (V2.isUndef()) {
8553     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8554         PPC::isSplatShuffleMask(SVOp, 2) ||
8555         PPC::isSplatShuffleMask(SVOp, 4) ||
8556         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8557         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8558         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8559         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8560         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8561         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8562         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8563         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8564         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8565         (Subtarget.hasP8Altivec() && (
8566          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8567          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8568          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8569       return Op;
8570     }
8571   }
8572 
8573   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8574   // and produce a fixed permutation.  If any of these match, do not lower to
8575   // VPERM.
8576   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8577   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8578       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8579       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8580       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8581       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8582       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8583       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8584       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8585       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8586       (Subtarget.hasP8Altivec() && (
8587        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8588        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8589        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8590     return Op;
8591 
8592   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8593   // perfect shuffle table to emit an optimal matching sequence.
8594   ArrayRef<int> PermMask = SVOp->getMask();
8595 
8596   unsigned PFIndexes[4];
8597   bool isFourElementShuffle = true;
8598   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8599     unsigned EltNo = 8;   // Start out undef.
8600     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8601       if (PermMask[i*4+j] < 0)
8602         continue;   // Undef, ignore it.
8603 
8604       unsigned ByteSource = PermMask[i*4+j];
8605       if ((ByteSource & 3) != j) {
8606         isFourElementShuffle = false;
8607         break;
8608       }
8609 
8610       if (EltNo == 8) {
8611         EltNo = ByteSource/4;
8612       } else if (EltNo != ByteSource/4) {
8613         isFourElementShuffle = false;
8614         break;
8615       }
8616     }
8617     PFIndexes[i] = EltNo;
8618   }
8619 
8620   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8621   // perfect shuffle vector to determine if it is cost effective to do this as
8622   // discrete instructions, or whether we should use a vperm.
8623   // For now, we skip this for little endian until such time as we have a
8624   // little-endian perfect shuffle table.
8625   if (isFourElementShuffle && !isLittleEndian) {
8626     // Compute the index in the perfect shuffle table.
8627     unsigned PFTableIndex =
8628       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8629 
8630     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8631     unsigned Cost  = (PFEntry >> 30);
8632 
8633     // Determining when to avoid vperm is tricky.  Many things affect the cost
8634     // of vperm, particularly how many times the perm mask needs to be computed.
8635     // For example, if the perm mask can be hoisted out of a loop or is already
8636     // used (perhaps because there are multiple permutes with the same shuffle
8637     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8638     // the loop requires an extra register.
8639     //
8640     // As a compromise, we only emit discrete instructions if the shuffle can be
8641     // generated in 3 or fewer operations.  When we have loop information
8642     // available, if this block is within a loop, we should avoid using vperm
8643     // for 3-operation perms and use a constant pool load instead.
8644     if (Cost < 3)
8645       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8646   }
8647 
8648   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8649   // vector that will get spilled to the constant pool.
8650   if (V2.isUndef()) V2 = V1;
8651 
8652   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8653   // that it is in input element units, not in bytes.  Convert now.
8654 
8655   // For little endian, the order of the input vectors is reversed, and
8656   // the permutation mask is complemented with respect to 31.  This is
8657   // necessary to produce proper semantics with the big-endian-biased vperm
8658   // instruction.
8659   EVT EltVT = V1.getValueType().getVectorElementType();
8660   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8661 
8662   SmallVector<SDValue, 16> ResultMask;
8663   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8664     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8665 
8666     for (unsigned j = 0; j != BytesPerElement; ++j)
8667       if (isLittleEndian)
8668         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8669                                              dl, MVT::i32));
8670       else
8671         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8672                                              MVT::i32));
8673   }
8674 
8675   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8676   if (isLittleEndian)
8677     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8678                        V2, V1, VPermMask);
8679   else
8680     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8681                        V1, V2, VPermMask);
8682 }
8683 
8684 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8685 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8686 /// information about the intrinsic.
8687 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8688                                  bool &isDot, const PPCSubtarget &Subtarget) {
8689   unsigned IntrinsicID =
8690       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8691   CompareOpc = -1;
8692   isDot = false;
8693   switch (IntrinsicID) {
8694   default:
8695     return false;
8696   // Comparison predicates.
8697   case Intrinsic::ppc_altivec_vcmpbfp_p:
8698     CompareOpc = 966;
8699     isDot = true;
8700     break;
8701   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8702     CompareOpc = 198;
8703     isDot = true;
8704     break;
8705   case Intrinsic::ppc_altivec_vcmpequb_p:
8706     CompareOpc = 6;
8707     isDot = true;
8708     break;
8709   case Intrinsic::ppc_altivec_vcmpequh_p:
8710     CompareOpc = 70;
8711     isDot = true;
8712     break;
8713   case Intrinsic::ppc_altivec_vcmpequw_p:
8714     CompareOpc = 134;
8715     isDot = true;
8716     break;
8717   case Intrinsic::ppc_altivec_vcmpequd_p:
8718     if (Subtarget.hasP8Altivec()) {
8719       CompareOpc = 199;
8720       isDot = true;
8721     } else
8722       return false;
8723     break;
8724   case Intrinsic::ppc_altivec_vcmpneb_p:
8725   case Intrinsic::ppc_altivec_vcmpneh_p:
8726   case Intrinsic::ppc_altivec_vcmpnew_p:
8727   case Intrinsic::ppc_altivec_vcmpnezb_p:
8728   case Intrinsic::ppc_altivec_vcmpnezh_p:
8729   case Intrinsic::ppc_altivec_vcmpnezw_p:
8730     if (Subtarget.hasP9Altivec()) {
8731       switch (IntrinsicID) {
8732       default:
8733         llvm_unreachable("Unknown comparison intrinsic.");
8734       case Intrinsic::ppc_altivec_vcmpneb_p:
8735         CompareOpc = 7;
8736         break;
8737       case Intrinsic::ppc_altivec_vcmpneh_p:
8738         CompareOpc = 71;
8739         break;
8740       case Intrinsic::ppc_altivec_vcmpnew_p:
8741         CompareOpc = 135;
8742         break;
8743       case Intrinsic::ppc_altivec_vcmpnezb_p:
8744         CompareOpc = 263;
8745         break;
8746       case Intrinsic::ppc_altivec_vcmpnezh_p:
8747         CompareOpc = 327;
8748         break;
8749       case Intrinsic::ppc_altivec_vcmpnezw_p:
8750         CompareOpc = 391;
8751         break;
8752       }
8753       isDot = true;
8754     } else
8755       return false;
8756     break;
8757   case Intrinsic::ppc_altivec_vcmpgefp_p:
8758     CompareOpc = 454;
8759     isDot = true;
8760     break;
8761   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8762     CompareOpc = 710;
8763     isDot = true;
8764     break;
8765   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8766     CompareOpc = 774;
8767     isDot = true;
8768     break;
8769   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8770     CompareOpc = 838;
8771     isDot = true;
8772     break;
8773   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8774     CompareOpc = 902;
8775     isDot = true;
8776     break;
8777   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8778     if (Subtarget.hasP8Altivec()) {
8779       CompareOpc = 967;
8780       isDot = true;
8781     } else
8782       return false;
8783     break;
8784   case Intrinsic::ppc_altivec_vcmpgtub_p:
8785     CompareOpc = 518;
8786     isDot = true;
8787     break;
8788   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8789     CompareOpc = 582;
8790     isDot = true;
8791     break;
8792   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8793     CompareOpc = 646;
8794     isDot = true;
8795     break;
8796   case Intrinsic::ppc_altivec_vcmpgtud_p:
8797     if (Subtarget.hasP8Altivec()) {
8798       CompareOpc = 711;
8799       isDot = true;
8800     } else
8801       return false;
8802     break;
8803 
8804   // VSX predicate comparisons use the same infrastructure
8805   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8806   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8807   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8808   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8809   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8810   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8811     if (Subtarget.hasVSX()) {
8812       switch (IntrinsicID) {
8813       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8814         CompareOpc = 99;
8815         break;
8816       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8817         CompareOpc = 115;
8818         break;
8819       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8820         CompareOpc = 107;
8821         break;
8822       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8823         CompareOpc = 67;
8824         break;
8825       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8826         CompareOpc = 83;
8827         break;
8828       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8829         CompareOpc = 75;
8830         break;
8831       }
8832       isDot = true;
8833     } else
8834       return false;
8835     break;
8836 
8837   // Normal Comparisons.
8838   case Intrinsic::ppc_altivec_vcmpbfp:
8839     CompareOpc = 966;
8840     break;
8841   case Intrinsic::ppc_altivec_vcmpeqfp:
8842     CompareOpc = 198;
8843     break;
8844   case Intrinsic::ppc_altivec_vcmpequb:
8845     CompareOpc = 6;
8846     break;
8847   case Intrinsic::ppc_altivec_vcmpequh:
8848     CompareOpc = 70;
8849     break;
8850   case Intrinsic::ppc_altivec_vcmpequw:
8851     CompareOpc = 134;
8852     break;
8853   case Intrinsic::ppc_altivec_vcmpequd:
8854     if (Subtarget.hasP8Altivec())
8855       CompareOpc = 199;
8856     else
8857       return false;
8858     break;
8859   case Intrinsic::ppc_altivec_vcmpneb:
8860   case Intrinsic::ppc_altivec_vcmpneh:
8861   case Intrinsic::ppc_altivec_vcmpnew:
8862   case Intrinsic::ppc_altivec_vcmpnezb:
8863   case Intrinsic::ppc_altivec_vcmpnezh:
8864   case Intrinsic::ppc_altivec_vcmpnezw:
8865     if (Subtarget.hasP9Altivec())
8866       switch (IntrinsicID) {
8867       default:
8868         llvm_unreachable("Unknown comparison intrinsic.");
8869       case Intrinsic::ppc_altivec_vcmpneb:
8870         CompareOpc = 7;
8871         break;
8872       case Intrinsic::ppc_altivec_vcmpneh:
8873         CompareOpc = 71;
8874         break;
8875       case Intrinsic::ppc_altivec_vcmpnew:
8876         CompareOpc = 135;
8877         break;
8878       case Intrinsic::ppc_altivec_vcmpnezb:
8879         CompareOpc = 263;
8880         break;
8881       case Intrinsic::ppc_altivec_vcmpnezh:
8882         CompareOpc = 327;
8883         break;
8884       case Intrinsic::ppc_altivec_vcmpnezw:
8885         CompareOpc = 391;
8886         break;
8887       }
8888     else
8889       return false;
8890     break;
8891   case Intrinsic::ppc_altivec_vcmpgefp:
8892     CompareOpc = 454;
8893     break;
8894   case Intrinsic::ppc_altivec_vcmpgtfp:
8895     CompareOpc = 710;
8896     break;
8897   case Intrinsic::ppc_altivec_vcmpgtsb:
8898     CompareOpc = 774;
8899     break;
8900   case Intrinsic::ppc_altivec_vcmpgtsh:
8901     CompareOpc = 838;
8902     break;
8903   case Intrinsic::ppc_altivec_vcmpgtsw:
8904     CompareOpc = 902;
8905     break;
8906   case Intrinsic::ppc_altivec_vcmpgtsd:
8907     if (Subtarget.hasP8Altivec())
8908       CompareOpc = 967;
8909     else
8910       return false;
8911     break;
8912   case Intrinsic::ppc_altivec_vcmpgtub:
8913     CompareOpc = 518;
8914     break;
8915   case Intrinsic::ppc_altivec_vcmpgtuh:
8916     CompareOpc = 582;
8917     break;
8918   case Intrinsic::ppc_altivec_vcmpgtuw:
8919     CompareOpc = 646;
8920     break;
8921   case Intrinsic::ppc_altivec_vcmpgtud:
8922     if (Subtarget.hasP8Altivec())
8923       CompareOpc = 711;
8924     else
8925       return false;
8926     break;
8927   }
8928   return true;
8929 }
8930 
8931 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8932 /// lower, do it, otherwise return null.
8933 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8934                                                    SelectionDAG &DAG) const {
8935   unsigned IntrinsicID =
8936     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8937 
8938   SDLoc dl(Op);
8939 
8940   if (IntrinsicID == Intrinsic::thread_pointer) {
8941     // Reads the thread pointer register, used for __builtin_thread_pointer.
8942     if (Subtarget.isPPC64())
8943       return DAG.getRegister(PPC::X13, MVT::i64);
8944     return DAG.getRegister(PPC::R2, MVT::i32);
8945   }
8946 
8947   // We are looking for absolute values here.
8948   // The idea is to try to fit one of two patterns:
8949   //  max (a, (0-a))  OR  max ((0-a), a)
8950   if (Subtarget.hasP9Vector() &&
8951       (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw ||
8952        IntrinsicID == Intrinsic::ppc_altivec_vmaxsh ||
8953        IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) {
8954     SDValue V1 = Op.getOperand(1);
8955     SDValue V2 = Op.getOperand(2);
8956     if (V1.getSimpleValueType() == V2.getSimpleValueType() &&
8957         (V1.getSimpleValueType() == MVT::v4i32 ||
8958          V1.getSimpleValueType() == MVT::v8i16 ||
8959          V1.getSimpleValueType() == MVT::v16i8)) {
8960       if ( V1.getOpcode() == ISD::SUB &&
8961            ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
8962            V1.getOperand(1) == V2 ) {
8963         // Generate the abs instruction with the operands
8964         return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2);
8965       }
8966 
8967       if ( V2.getOpcode() == ISD::SUB &&
8968            ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
8969            V2.getOperand(1) == V1 ) {
8970         // Generate the abs instruction with the operands
8971         return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1);
8972       }
8973     }
8974   }
8975 
8976   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8977   // opcode number of the comparison.
8978   int CompareOpc;
8979   bool isDot;
8980   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8981     return SDValue();    // Don't custom lower most intrinsics.
8982 
8983   // If this is a non-dot comparison, make the VCMP node and we are done.
8984   if (!isDot) {
8985     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8986                               Op.getOperand(1), Op.getOperand(2),
8987                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8988     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8989   }
8990 
8991   // Create the PPCISD altivec 'dot' comparison node.
8992   SDValue Ops[] = {
8993     Op.getOperand(2),  // LHS
8994     Op.getOperand(3),  // RHS
8995     DAG.getConstant(CompareOpc, dl, MVT::i32)
8996   };
8997   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8998   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8999 
9000   // Now that we have the comparison, emit a copy from the CR to a GPR.
9001   // This is flagged to the above dot comparison.
9002   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9003                                 DAG.getRegister(PPC::CR6, MVT::i32),
9004                                 CompNode.getValue(1));
9005 
9006   // Unpack the result based on how the target uses it.
9007   unsigned BitNo;   // Bit # of CR6.
9008   bool InvertBit;   // Invert result?
9009   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9010   default:  // Can't happen, don't crash on invalid number though.
9011   case 0:   // Return the value of the EQ bit of CR6.
9012     BitNo = 0; InvertBit = false;
9013     break;
9014   case 1:   // Return the inverted value of the EQ bit of CR6.
9015     BitNo = 0; InvertBit = true;
9016     break;
9017   case 2:   // Return the value of the LT bit of CR6.
9018     BitNo = 2; InvertBit = false;
9019     break;
9020   case 3:   // Return the inverted value of the LT bit of CR6.
9021     BitNo = 2; InvertBit = true;
9022     break;
9023   }
9024 
9025   // Shift the bit into the low position.
9026   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9027                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9028   // Isolate the bit.
9029   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9030                       DAG.getConstant(1, dl, MVT::i32));
9031 
9032   // If we are supposed to, toggle the bit.
9033   if (InvertBit)
9034     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9035                         DAG.getConstant(1, dl, MVT::i32));
9036   return Flags;
9037 }
9038 
9039 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9040                                                SelectionDAG &DAG) const {
9041   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9042   // the beginning of the argument list.
9043   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9044   SDLoc DL(Op);
9045   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9046   case Intrinsic::ppc_cfence: {
9047     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9048     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9049     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9050                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9051                                                   Op.getOperand(ArgStart + 1)),
9052                                       Op.getOperand(0)),
9053                    0);
9054   }
9055   default:
9056     break;
9057   }
9058   return SDValue();
9059 }
9060 
9061 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9062   // Check for a DIV with the same operands as this REM.
9063   for (auto UI : Op.getOperand(1)->uses()) {
9064     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9065         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9066       if (UI->getOperand(0) == Op.getOperand(0) &&
9067           UI->getOperand(1) == Op.getOperand(1))
9068         return SDValue();
9069   }
9070   return Op;
9071 }
9072 
9073 // Lower scalar BSWAP64 to xxbrd.
9074 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9075   SDLoc dl(Op);
9076   // MTVSRDD
9077   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9078                    Op.getOperand(0));
9079   // XXBRD
9080   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9081   // MFVSRD
9082   int VectorIndex = 0;
9083   if (Subtarget.isLittleEndian())
9084     VectorIndex = 1;
9085   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9086                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9087   return Op;
9088 }
9089 
9090 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9091 // compared to a value that is atomically loaded (atomic loads zero-extend).
9092 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9093                                                 SelectionDAG &DAG) const {
9094   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9095          "Expecting an atomic compare-and-swap here.");
9096   SDLoc dl(Op);
9097   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9098   EVT MemVT = AtomicNode->getMemoryVT();
9099   if (MemVT.getSizeInBits() >= 32)
9100     return Op;
9101 
9102   SDValue CmpOp = Op.getOperand(2);
9103   // If this is already correctly zero-extended, leave it alone.
9104   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9105   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9106     return Op;
9107 
9108   // Clear the high bits of the compare operand.
9109   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9110   SDValue NewCmpOp =
9111     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9112                 DAG.getConstant(MaskVal, dl, MVT::i32));
9113 
9114   // Replace the existing compare operand with the properly zero-extended one.
9115   SmallVector<SDValue, 4> Ops;
9116   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9117     Ops.push_back(AtomicNode->getOperand(i));
9118   Ops[2] = NewCmpOp;
9119   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9120   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9121   auto NodeTy =
9122     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9123   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9124 }
9125 
9126 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
9127                                                   SelectionDAG &DAG) const {
9128   SDLoc dl(Op);
9129   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
9130   // instructions), but for smaller types, we need to first extend up to v2i32
9131   // before doing going farther.
9132   if (Op.getValueType() == MVT::v2i64) {
9133     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
9134     if (ExtVT != MVT::v2i32) {
9135       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
9136       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
9137                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
9138                                         ExtVT.getVectorElementType(), 4)));
9139       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
9140       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
9141                        DAG.getValueType(MVT::v2i32));
9142     }
9143 
9144     return Op;
9145   }
9146 
9147   return SDValue();
9148 }
9149 
9150 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9151                                                  SelectionDAG &DAG) const {
9152   SDLoc dl(Op);
9153   // Create a stack slot that is 16-byte aligned.
9154   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9155   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9156   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9157   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9158 
9159   // Store the input value into Value#0 of the stack slot.
9160   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9161                                MachinePointerInfo());
9162   // Load it out.
9163   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9164 }
9165 
9166 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9167                                                   SelectionDAG &DAG) const {
9168   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9169          "Should only be called for ISD::INSERT_VECTOR_ELT");
9170 
9171   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9172   // We have legal lowering for constant indices but not for variable ones.
9173   if (!C)
9174     return SDValue();
9175 
9176   EVT VT = Op.getValueType();
9177   SDLoc dl(Op);
9178   SDValue V1 = Op.getOperand(0);
9179   SDValue V2 = Op.getOperand(1);
9180   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9181   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9182     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9183     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9184     unsigned InsertAtElement = C->getZExtValue();
9185     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9186     if (Subtarget.isLittleEndian()) {
9187       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9188     }
9189     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9190                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9191   }
9192   return Op;
9193 }
9194 
9195 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9196                                                    SelectionDAG &DAG) const {
9197   SDLoc dl(Op);
9198   SDNode *N = Op.getNode();
9199 
9200   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9201          "Unknown extract_vector_elt type");
9202 
9203   SDValue Value = N->getOperand(0);
9204 
9205   // The first part of this is like the store lowering except that we don't
9206   // need to track the chain.
9207 
9208   // The values are now known to be -1 (false) or 1 (true). To convert this
9209   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9210   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9211   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9212 
9213   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9214   // understand how to form the extending load.
9215   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9216 
9217   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9218 
9219   // Now convert to an integer and store.
9220   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9221     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9222     Value);
9223 
9224   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9225   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9226   MachinePointerInfo PtrInfo =
9227       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9228   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9229   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9230 
9231   SDValue StoreChain = DAG.getEntryNode();
9232   SDValue Ops[] = {StoreChain,
9233                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9234                    Value, FIdx};
9235   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9236 
9237   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9238     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9239 
9240   // Extract the value requested.
9241   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9242   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9243   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9244 
9245   SDValue IntVal =
9246       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9247 
9248   if (!Subtarget.useCRBits())
9249     return IntVal;
9250 
9251   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9252 }
9253 
9254 /// Lowering for QPX v4i1 loads
9255 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9256                                            SelectionDAG &DAG) const {
9257   SDLoc dl(Op);
9258   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9259   SDValue LoadChain = LN->getChain();
9260   SDValue BasePtr = LN->getBasePtr();
9261 
9262   if (Op.getValueType() == MVT::v4f64 ||
9263       Op.getValueType() == MVT::v4f32) {
9264     EVT MemVT = LN->getMemoryVT();
9265     unsigned Alignment = LN->getAlignment();
9266 
9267     // If this load is properly aligned, then it is legal.
9268     if (Alignment >= MemVT.getStoreSize())
9269       return Op;
9270 
9271     EVT ScalarVT = Op.getValueType().getScalarType(),
9272         ScalarMemVT = MemVT.getScalarType();
9273     unsigned Stride = ScalarMemVT.getStoreSize();
9274 
9275     SDValue Vals[4], LoadChains[4];
9276     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9277       SDValue Load;
9278       if (ScalarVT != ScalarMemVT)
9279         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9280                               BasePtr,
9281                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9282                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9283                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9284       else
9285         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9286                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9287                            MinAlign(Alignment, Idx * Stride),
9288                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9289 
9290       if (Idx == 0 && LN->isIndexed()) {
9291         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9292                "Unknown addressing mode on vector load");
9293         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9294                                   LN->getAddressingMode());
9295       }
9296 
9297       Vals[Idx] = Load;
9298       LoadChains[Idx] = Load.getValue(1);
9299 
9300       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9301                             DAG.getConstant(Stride, dl,
9302                                             BasePtr.getValueType()));
9303     }
9304 
9305     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9306     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9307 
9308     if (LN->isIndexed()) {
9309       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9310       return DAG.getMergeValues(RetOps, dl);
9311     }
9312 
9313     SDValue RetOps[] = { Value, TF };
9314     return DAG.getMergeValues(RetOps, dl);
9315   }
9316 
9317   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9318   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9319 
9320   // To lower v4i1 from a byte array, we load the byte elements of the
9321   // vector and then reuse the BUILD_VECTOR logic.
9322 
9323   SDValue VectElmts[4], VectElmtChains[4];
9324   for (unsigned i = 0; i < 4; ++i) {
9325     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9326     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9327 
9328     VectElmts[i] = DAG.getExtLoad(
9329         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9330         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9331         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9332     VectElmtChains[i] = VectElmts[i].getValue(1);
9333   }
9334 
9335   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9336   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9337 
9338   SDValue RVals[] = { Value, LoadChain };
9339   return DAG.getMergeValues(RVals, dl);
9340 }
9341 
9342 /// Lowering for QPX v4i1 stores
9343 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9344                                             SelectionDAG &DAG) const {
9345   SDLoc dl(Op);
9346   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9347   SDValue StoreChain = SN->getChain();
9348   SDValue BasePtr = SN->getBasePtr();
9349   SDValue Value = SN->getValue();
9350 
9351   if (Value.getValueType() == MVT::v4f64 ||
9352       Value.getValueType() == MVT::v4f32) {
9353     EVT MemVT = SN->getMemoryVT();
9354     unsigned Alignment = SN->getAlignment();
9355 
9356     // If this store is properly aligned, then it is legal.
9357     if (Alignment >= MemVT.getStoreSize())
9358       return Op;
9359 
9360     EVT ScalarVT = Value.getValueType().getScalarType(),
9361         ScalarMemVT = MemVT.getScalarType();
9362     unsigned Stride = ScalarMemVT.getStoreSize();
9363 
9364     SDValue Stores[4];
9365     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9366       SDValue Ex = DAG.getNode(
9367           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9368           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9369       SDValue Store;
9370       if (ScalarVT != ScalarMemVT)
9371         Store =
9372             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9373                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9374                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9375                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9376       else
9377         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9378                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9379                              MinAlign(Alignment, Idx * Stride),
9380                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9381 
9382       if (Idx == 0 && SN->isIndexed()) {
9383         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9384                "Unknown addressing mode on vector store");
9385         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9386                                     SN->getAddressingMode());
9387       }
9388 
9389       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9390                             DAG.getConstant(Stride, dl,
9391                                             BasePtr.getValueType()));
9392       Stores[Idx] = Store;
9393     }
9394 
9395     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9396 
9397     if (SN->isIndexed()) {
9398       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9399       return DAG.getMergeValues(RetOps, dl);
9400     }
9401 
9402     return TF;
9403   }
9404 
9405   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9406   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9407 
9408   // The values are now known to be -1 (false) or 1 (true). To convert this
9409   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9410   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9411   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9412 
9413   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9414   // understand how to form the extending load.
9415   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9416 
9417   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9418 
9419   // Now convert to an integer and store.
9420   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9421     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9422     Value);
9423 
9424   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9425   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9426   MachinePointerInfo PtrInfo =
9427       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9428   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9429   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9430 
9431   SDValue Ops[] = {StoreChain,
9432                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9433                    Value, FIdx};
9434   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9435 
9436   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9437     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9438 
9439   // Move data into the byte array.
9440   SDValue Loads[4], LoadChains[4];
9441   for (unsigned i = 0; i < 4; ++i) {
9442     unsigned Offset = 4*i;
9443     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9444     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9445 
9446     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9447                            PtrInfo.getWithOffset(Offset));
9448     LoadChains[i] = Loads[i].getValue(1);
9449   }
9450 
9451   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9452 
9453   SDValue Stores[4];
9454   for (unsigned i = 0; i < 4; ++i) {
9455     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9456     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9457 
9458     Stores[i] = DAG.getTruncStore(
9459         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9460         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9461         SN->getAAInfo());
9462   }
9463 
9464   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9465 
9466   return StoreChain;
9467 }
9468 
9469 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9470   SDLoc dl(Op);
9471   if (Op.getValueType() == MVT::v4i32) {
9472     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9473 
9474     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9475     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9476 
9477     SDValue RHSSwap =   // = vrlw RHS, 16
9478       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9479 
9480     // Shrinkify inputs to v8i16.
9481     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9482     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9483     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9484 
9485     // Low parts multiplied together, generating 32-bit results (we ignore the
9486     // top parts).
9487     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9488                                         LHS, RHS, DAG, dl, MVT::v4i32);
9489 
9490     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9491                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9492     // Shift the high parts up 16 bits.
9493     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9494                               Neg16, DAG, dl);
9495     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9496   } else if (Op.getValueType() == MVT::v8i16) {
9497     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9498 
9499     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9500 
9501     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9502                             LHS, RHS, Zero, DAG, dl);
9503   } else if (Op.getValueType() == MVT::v16i8) {
9504     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9505     bool isLittleEndian = Subtarget.isLittleEndian();
9506 
9507     // Multiply the even 8-bit parts, producing 16-bit sums.
9508     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9509                                            LHS, RHS, DAG, dl, MVT::v8i16);
9510     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9511 
9512     // Multiply the odd 8-bit parts, producing 16-bit sums.
9513     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9514                                           LHS, RHS, DAG, dl, MVT::v8i16);
9515     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9516 
9517     // Merge the results together.  Because vmuleub and vmuloub are
9518     // instructions with a big-endian bias, we must reverse the
9519     // element numbering and reverse the meaning of "odd" and "even"
9520     // when generating little endian code.
9521     int Ops[16];
9522     for (unsigned i = 0; i != 8; ++i) {
9523       if (isLittleEndian) {
9524         Ops[i*2  ] = 2*i;
9525         Ops[i*2+1] = 2*i+16;
9526       } else {
9527         Ops[i*2  ] = 2*i+1;
9528         Ops[i*2+1] = 2*i+1+16;
9529       }
9530     }
9531     if (isLittleEndian)
9532       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9533     else
9534       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9535   } else {
9536     llvm_unreachable("Unknown mul to lower!");
9537   }
9538 }
9539 
9540 /// LowerOperation - Provide custom lowering hooks for some operations.
9541 ///
9542 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9543   switch (Op.getOpcode()) {
9544   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9545   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9546   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9547   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9548   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9549   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9550   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9551   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9552   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9553 
9554   // Variable argument lowering.
9555   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9556   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9557   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9558 
9559   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9560   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9561   case ISD::GET_DYNAMIC_AREA_OFFSET:
9562     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9563 
9564   // Exception handling lowering.
9565   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9566   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9567   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9568 
9569   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9570   case ISD::STORE:              return LowerSTORE(Op, DAG);
9571   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9572   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9573   case ISD::FP_TO_UINT:
9574   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9575   case ISD::UINT_TO_FP:
9576   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9577   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9578 
9579   // Lower 64-bit shifts.
9580   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9581   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9582   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9583 
9584   // Vector-related lowering.
9585   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9586   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9587   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9588   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9589   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
9590   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9591   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9592   case ISD::MUL:                return LowerMUL(Op, DAG);
9593 
9594   // For counter-based loop handling.
9595   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9596 
9597   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9598 
9599   // Frame & Return address.
9600   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9601   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9602 
9603   case ISD::INTRINSIC_VOID:
9604     return LowerINTRINSIC_VOID(Op, DAG);
9605   case ISD::SREM:
9606   case ISD::UREM:
9607     return LowerREM(Op, DAG);
9608   case ISD::BSWAP:
9609     return LowerBSWAP(Op, DAG);
9610   case ISD::ATOMIC_CMP_SWAP:
9611     return LowerATOMIC_CMP_SWAP(Op, DAG);
9612   }
9613 }
9614 
9615 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9616                                            SmallVectorImpl<SDValue>&Results,
9617                                            SelectionDAG &DAG) const {
9618   SDLoc dl(N);
9619   switch (N->getOpcode()) {
9620   default:
9621     llvm_unreachable("Do not know how to custom type legalize this operation!");
9622   case ISD::READCYCLECOUNTER: {
9623     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9624     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9625 
9626     Results.push_back(RTB);
9627     Results.push_back(RTB.getValue(1));
9628     Results.push_back(RTB.getValue(2));
9629     break;
9630   }
9631   case ISD::INTRINSIC_W_CHAIN: {
9632     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9633         Intrinsic::ppc_is_decremented_ctr_nonzero)
9634       break;
9635 
9636     assert(N->getValueType(0) == MVT::i1 &&
9637            "Unexpected result type for CTR decrement intrinsic");
9638     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9639                                  N->getValueType(0));
9640     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9641     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9642                                  N->getOperand(1));
9643 
9644     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
9645     Results.push_back(NewInt.getValue(1));
9646     break;
9647   }
9648   case ISD::VAARG: {
9649     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9650       return;
9651 
9652     EVT VT = N->getValueType(0);
9653 
9654     if (VT == MVT::i64) {
9655       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9656 
9657       Results.push_back(NewNode);
9658       Results.push_back(NewNode.getValue(1));
9659     }
9660     return;
9661   }
9662   case ISD::FP_TO_SINT:
9663   case ISD::FP_TO_UINT:
9664     // LowerFP_TO_INT() can only handle f32 and f64.
9665     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9666       return;
9667     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9668     return;
9669   }
9670 }
9671 
9672 //===----------------------------------------------------------------------===//
9673 //  Other Lowering Code
9674 //===----------------------------------------------------------------------===//
9675 
9676 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9677   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9678   Function *Func = Intrinsic::getDeclaration(M, Id);
9679   return Builder.CreateCall(Func, {});
9680 }
9681 
9682 // The mappings for emitLeading/TrailingFence is taken from
9683 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9684 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9685                                                  Instruction *Inst,
9686                                                  AtomicOrdering Ord) const {
9687   if (Ord == AtomicOrdering::SequentiallyConsistent)
9688     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9689   if (isReleaseOrStronger(Ord))
9690     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9691   return nullptr;
9692 }
9693 
9694 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9695                                                   Instruction *Inst,
9696                                                   AtomicOrdering Ord) const {
9697   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9698     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9699     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9700     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9701     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9702       return Builder.CreateCall(
9703           Intrinsic::getDeclaration(
9704               Builder.GetInsertBlock()->getParent()->getParent(),
9705               Intrinsic::ppc_cfence, {Inst->getType()}),
9706           {Inst});
9707     // FIXME: Can use isync for rmw operation.
9708     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9709   }
9710   return nullptr;
9711 }
9712 
9713 MachineBasicBlock *
9714 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9715                                     unsigned AtomicSize,
9716                                     unsigned BinOpcode,
9717                                     unsigned CmpOpcode,
9718                                     unsigned CmpPred) const {
9719   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9720   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9721 
9722   auto LoadMnemonic = PPC::LDARX;
9723   auto StoreMnemonic = PPC::STDCX;
9724   switch (AtomicSize) {
9725   default:
9726     llvm_unreachable("Unexpected size of atomic entity");
9727   case 1:
9728     LoadMnemonic = PPC::LBARX;
9729     StoreMnemonic = PPC::STBCX;
9730     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9731     break;
9732   case 2:
9733     LoadMnemonic = PPC::LHARX;
9734     StoreMnemonic = PPC::STHCX;
9735     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9736     break;
9737   case 4:
9738     LoadMnemonic = PPC::LWARX;
9739     StoreMnemonic = PPC::STWCX;
9740     break;
9741   case 8:
9742     LoadMnemonic = PPC::LDARX;
9743     StoreMnemonic = PPC::STDCX;
9744     break;
9745   }
9746 
9747   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9748   MachineFunction *F = BB->getParent();
9749   MachineFunction::iterator It = ++BB->getIterator();
9750 
9751   unsigned dest = MI.getOperand(0).getReg();
9752   unsigned ptrA = MI.getOperand(1).getReg();
9753   unsigned ptrB = MI.getOperand(2).getReg();
9754   unsigned incr = MI.getOperand(3).getReg();
9755   DebugLoc dl = MI.getDebugLoc();
9756 
9757   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9758   MachineBasicBlock *loop2MBB =
9759     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9760   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9761   F->insert(It, loopMBB);
9762   if (CmpOpcode)
9763     F->insert(It, loop2MBB);
9764   F->insert(It, exitMBB);
9765   exitMBB->splice(exitMBB->begin(), BB,
9766                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9767   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9768 
9769   MachineRegisterInfo &RegInfo = F->getRegInfo();
9770   unsigned TmpReg = (!BinOpcode) ? incr :
9771     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9772                                            : &PPC::GPRCRegClass);
9773 
9774   //  thisMBB:
9775   //   ...
9776   //   fallthrough --> loopMBB
9777   BB->addSuccessor(loopMBB);
9778 
9779   //  loopMBB:
9780   //   l[wd]arx dest, ptr
9781   //   add r0, dest, incr
9782   //   st[wd]cx. r0, ptr
9783   //   bne- loopMBB
9784   //   fallthrough --> exitMBB
9785 
9786   // For max/min...
9787   //  loopMBB:
9788   //   l[wd]arx dest, ptr
9789   //   cmpl?[wd] incr, dest
9790   //   bgt exitMBB
9791   //  loop2MBB:
9792   //   st[wd]cx. dest, ptr
9793   //   bne- loopMBB
9794   //   fallthrough --> exitMBB
9795 
9796   BB = loopMBB;
9797   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9798     .addReg(ptrA).addReg(ptrB);
9799   if (BinOpcode)
9800     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9801   if (CmpOpcode) {
9802     // Signed comparisons of byte or halfword values must be sign-extended.
9803     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9804       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9805       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9806               ExtReg).addReg(dest);
9807       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9808         .addReg(incr).addReg(ExtReg);
9809     } else
9810       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9811         .addReg(incr).addReg(dest);
9812 
9813     BuildMI(BB, dl, TII->get(PPC::BCC))
9814       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9815     BB->addSuccessor(loop2MBB);
9816     BB->addSuccessor(exitMBB);
9817     BB = loop2MBB;
9818   }
9819   BuildMI(BB, dl, TII->get(StoreMnemonic))
9820     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9821   BuildMI(BB, dl, TII->get(PPC::BCC))
9822     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9823   BB->addSuccessor(loopMBB);
9824   BB->addSuccessor(exitMBB);
9825 
9826   //  exitMBB:
9827   //   ...
9828   BB = exitMBB;
9829   return BB;
9830 }
9831 
9832 MachineBasicBlock *
9833 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9834                                             MachineBasicBlock *BB,
9835                                             bool is8bit, // operation
9836                                             unsigned BinOpcode,
9837                                             unsigned CmpOpcode,
9838                                             unsigned CmpPred) const {
9839   // If we support part-word atomic mnemonics, just use them
9840   if (Subtarget.hasPartwordAtomics())
9841     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9842                             CmpOpcode, CmpPred);
9843 
9844   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9845   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9846   // In 64 bit mode we have to use 64 bits for addresses, even though the
9847   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9848   // registers without caring whether they're 32 or 64, but here we're
9849   // doing actual arithmetic on the addresses.
9850   bool is64bit = Subtarget.isPPC64();
9851   bool isLittleEndian = Subtarget.isLittleEndian();
9852   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9853 
9854   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9855   MachineFunction *F = BB->getParent();
9856   MachineFunction::iterator It = ++BB->getIterator();
9857 
9858   unsigned dest = MI.getOperand(0).getReg();
9859   unsigned ptrA = MI.getOperand(1).getReg();
9860   unsigned ptrB = MI.getOperand(2).getReg();
9861   unsigned incr = MI.getOperand(3).getReg();
9862   DebugLoc dl = MI.getDebugLoc();
9863 
9864   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9865   MachineBasicBlock *loop2MBB =
9866     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9867   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9868   F->insert(It, loopMBB);
9869   if (CmpOpcode)
9870     F->insert(It, loop2MBB);
9871   F->insert(It, exitMBB);
9872   exitMBB->splice(exitMBB->begin(), BB,
9873                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9874   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9875 
9876   MachineRegisterInfo &RegInfo = F->getRegInfo();
9877   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9878                                           : &PPC::GPRCRegClass;
9879   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9880   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9881   unsigned ShiftReg =
9882     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9883   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9884   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9885   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9886   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9887   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9888   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9889   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9890   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9891   unsigned Ptr1Reg;
9892   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9893 
9894   //  thisMBB:
9895   //   ...
9896   //   fallthrough --> loopMBB
9897   BB->addSuccessor(loopMBB);
9898 
9899   // The 4-byte load must be aligned, while a char or short may be
9900   // anywhere in the word.  Hence all this nasty bookkeeping code.
9901   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9902   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9903   //   xori shift, shift1, 24 [16]
9904   //   rlwinm ptr, ptr1, 0, 0, 29
9905   //   slw incr2, incr, shift
9906   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9907   //   slw mask, mask2, shift
9908   //  loopMBB:
9909   //   lwarx tmpDest, ptr
9910   //   add tmp, tmpDest, incr2
9911   //   andc tmp2, tmpDest, mask
9912   //   and tmp3, tmp, mask
9913   //   or tmp4, tmp3, tmp2
9914   //   stwcx. tmp4, ptr
9915   //   bne- loopMBB
9916   //   fallthrough --> exitMBB
9917   //   srw dest, tmpDest, shift
9918   if (ptrA != ZeroReg) {
9919     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9920     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9921       .addReg(ptrA).addReg(ptrB);
9922   } else {
9923     Ptr1Reg = ptrB;
9924   }
9925   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9926       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9927   if (!isLittleEndian)
9928     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9929         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9930   if (is64bit)
9931     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9932       .addReg(Ptr1Reg).addImm(0).addImm(61);
9933   else
9934     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9935       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9936   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9937       .addReg(incr).addReg(ShiftReg);
9938   if (is8bit)
9939     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9940   else {
9941     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9942     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9943   }
9944   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9945       .addReg(Mask2Reg).addReg(ShiftReg);
9946 
9947   BB = loopMBB;
9948   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9949     .addReg(ZeroReg).addReg(PtrReg);
9950   if (BinOpcode)
9951     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9952       .addReg(Incr2Reg).addReg(TmpDestReg);
9953   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9954     .addReg(TmpDestReg).addReg(MaskReg);
9955   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9956     .addReg(TmpReg).addReg(MaskReg);
9957   if (CmpOpcode) {
9958     // For unsigned comparisons, we can directly compare the shifted values.
9959     // For signed comparisons we shift and sign extend.
9960     unsigned SReg = RegInfo.createVirtualRegister(RC);
9961     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9962       .addReg(TmpDestReg).addReg(MaskReg);
9963     unsigned ValueReg = SReg;
9964     unsigned CmpReg = Incr2Reg;
9965     if (CmpOpcode == PPC::CMPW) {
9966       ValueReg = RegInfo.createVirtualRegister(RC);
9967       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9968         .addReg(SReg).addReg(ShiftReg);
9969       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9970       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9971         .addReg(ValueReg);
9972       ValueReg = ValueSReg;
9973       CmpReg = incr;
9974     }
9975     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9976       .addReg(CmpReg).addReg(ValueReg);
9977     BuildMI(BB, dl, TII->get(PPC::BCC))
9978       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9979     BB->addSuccessor(loop2MBB);
9980     BB->addSuccessor(exitMBB);
9981     BB = loop2MBB;
9982   }
9983   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9984     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9985   BuildMI(BB, dl, TII->get(PPC::STWCX))
9986     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9987   BuildMI(BB, dl, TII->get(PPC::BCC))
9988     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9989   BB->addSuccessor(loopMBB);
9990   BB->addSuccessor(exitMBB);
9991 
9992   //  exitMBB:
9993   //   ...
9994   BB = exitMBB;
9995   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9996     .addReg(ShiftReg);
9997   return BB;
9998 }
9999 
10000 llvm::MachineBasicBlock *
10001 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10002                                     MachineBasicBlock *MBB) const {
10003   DebugLoc DL = MI.getDebugLoc();
10004   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10005   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10006 
10007   MachineFunction *MF = MBB->getParent();
10008   MachineRegisterInfo &MRI = MF->getRegInfo();
10009 
10010   const BasicBlock *BB = MBB->getBasicBlock();
10011   MachineFunction::iterator I = ++MBB->getIterator();
10012 
10013   unsigned DstReg = MI.getOperand(0).getReg();
10014   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10015   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10016   unsigned mainDstReg = MRI.createVirtualRegister(RC);
10017   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
10018 
10019   MVT PVT = getPointerTy(MF->getDataLayout());
10020   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10021          "Invalid Pointer Size!");
10022   // For v = setjmp(buf), we generate
10023   //
10024   // thisMBB:
10025   //  SjLjSetup mainMBB
10026   //  bl mainMBB
10027   //  v_restore = 1
10028   //  b sinkMBB
10029   //
10030   // mainMBB:
10031   //  buf[LabelOffset] = LR
10032   //  v_main = 0
10033   //
10034   // sinkMBB:
10035   //  v = phi(main, restore)
10036   //
10037 
10038   MachineBasicBlock *thisMBB = MBB;
10039   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10040   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10041   MF->insert(I, mainMBB);
10042   MF->insert(I, sinkMBB);
10043 
10044   MachineInstrBuilder MIB;
10045 
10046   // Transfer the remainder of BB and its successor edges to sinkMBB.
10047   sinkMBB->splice(sinkMBB->begin(), MBB,
10048                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10049   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10050 
10051   // Note that the structure of the jmp_buf used here is not compatible
10052   // with that used by libc, and is not designed to be. Specifically, it
10053   // stores only those 'reserved' registers that LLVM does not otherwise
10054   // understand how to spill. Also, by convention, by the time this
10055   // intrinsic is called, Clang has already stored the frame address in the
10056   // first slot of the buffer and stack address in the third. Following the
10057   // X86 target code, we'll store the jump address in the second slot. We also
10058   // need to save the TOC pointer (R2) to handle jumps between shared
10059   // libraries, and that will be stored in the fourth slot. The thread
10060   // identifier (R13) is not affected.
10061 
10062   // thisMBB:
10063   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10064   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10065   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10066 
10067   // Prepare IP either in reg.
10068   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10069   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
10070   unsigned BufReg = MI.getOperand(1).getReg();
10071 
10072   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
10073     setUsesTOCBasePtr(*MBB->getParent());
10074     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10075               .addReg(PPC::X2)
10076               .addImm(TOCOffset)
10077               .addReg(BufReg)
10078               .cloneMemRefs(MI);
10079   }
10080 
10081   // Naked functions never have a base pointer, and so we use r1. For all
10082   // other functions, this decision must be delayed until during PEI.
10083   unsigned BaseReg;
10084   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10085     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10086   else
10087     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10088 
10089   MIB = BuildMI(*thisMBB, MI, DL,
10090                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10091             .addReg(BaseReg)
10092             .addImm(BPOffset)
10093             .addReg(BufReg)
10094             .cloneMemRefs(MI);
10095 
10096   // Setup
10097   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10098   MIB.addRegMask(TRI->getNoPreservedMask());
10099 
10100   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10101 
10102   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10103           .addMBB(mainMBB);
10104   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10105 
10106   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10107   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10108 
10109   // mainMBB:
10110   //  mainDstReg = 0
10111   MIB =
10112       BuildMI(mainMBB, DL,
10113               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10114 
10115   // Store IP
10116   if (Subtarget.isPPC64()) {
10117     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10118             .addReg(LabelReg)
10119             .addImm(LabelOffset)
10120             .addReg(BufReg);
10121   } else {
10122     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10123             .addReg(LabelReg)
10124             .addImm(LabelOffset)
10125             .addReg(BufReg);
10126   }
10127   MIB.cloneMemRefs(MI);
10128 
10129   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10130   mainMBB->addSuccessor(sinkMBB);
10131 
10132   // sinkMBB:
10133   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10134           TII->get(PPC::PHI), DstReg)
10135     .addReg(mainDstReg).addMBB(mainMBB)
10136     .addReg(restoreDstReg).addMBB(thisMBB);
10137 
10138   MI.eraseFromParent();
10139   return sinkMBB;
10140 }
10141 
10142 MachineBasicBlock *
10143 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10144                                      MachineBasicBlock *MBB) const {
10145   DebugLoc DL = MI.getDebugLoc();
10146   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10147 
10148   MachineFunction *MF = MBB->getParent();
10149   MachineRegisterInfo &MRI = MF->getRegInfo();
10150 
10151   MVT PVT = getPointerTy(MF->getDataLayout());
10152   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10153          "Invalid Pointer Size!");
10154 
10155   const TargetRegisterClass *RC =
10156     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10157   unsigned Tmp = MRI.createVirtualRegister(RC);
10158   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10159   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10160   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10161   unsigned BP =
10162       (PVT == MVT::i64)
10163           ? PPC::X30
10164           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10165                                                               : PPC::R30);
10166 
10167   MachineInstrBuilder MIB;
10168 
10169   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10170   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10171   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10172   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10173 
10174   unsigned BufReg = MI.getOperand(0).getReg();
10175 
10176   // Reload FP (the jumped-to function may not have had a
10177   // frame pointer, and if so, then its r31 will be restored
10178   // as necessary).
10179   if (PVT == MVT::i64) {
10180     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10181             .addImm(0)
10182             .addReg(BufReg);
10183   } else {
10184     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10185             .addImm(0)
10186             .addReg(BufReg);
10187   }
10188   MIB.cloneMemRefs(MI);
10189 
10190   // Reload IP
10191   if (PVT == MVT::i64) {
10192     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10193             .addImm(LabelOffset)
10194             .addReg(BufReg);
10195   } else {
10196     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10197             .addImm(LabelOffset)
10198             .addReg(BufReg);
10199   }
10200   MIB.cloneMemRefs(MI);
10201 
10202   // Reload SP
10203   if (PVT == MVT::i64) {
10204     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10205             .addImm(SPOffset)
10206             .addReg(BufReg);
10207   } else {
10208     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10209             .addImm(SPOffset)
10210             .addReg(BufReg);
10211   }
10212   MIB.cloneMemRefs(MI);
10213 
10214   // Reload BP
10215   if (PVT == MVT::i64) {
10216     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10217             .addImm(BPOffset)
10218             .addReg(BufReg);
10219   } else {
10220     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10221             .addImm(BPOffset)
10222             .addReg(BufReg);
10223   }
10224   MIB.cloneMemRefs(MI);
10225 
10226   // Reload TOC
10227   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10228     setUsesTOCBasePtr(*MBB->getParent());
10229     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10230               .addImm(TOCOffset)
10231               .addReg(BufReg)
10232               .cloneMemRefs(MI);
10233   }
10234 
10235   // Jump
10236   BuildMI(*MBB, MI, DL,
10237           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10238   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10239 
10240   MI.eraseFromParent();
10241   return MBB;
10242 }
10243 
10244 MachineBasicBlock *
10245 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10246                                                MachineBasicBlock *BB) const {
10247   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10248       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10249     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10250         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10251       // Call lowering should have added an r2 operand to indicate a dependence
10252       // on the TOC base pointer value. It can't however, because there is no
10253       // way to mark the dependence as implicit there, and so the stackmap code
10254       // will confuse it with a regular operand. Instead, add the dependence
10255       // here.
10256       setUsesTOCBasePtr(*BB->getParent());
10257       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10258     }
10259 
10260     return emitPatchPoint(MI, BB);
10261   }
10262 
10263   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10264       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10265     return emitEHSjLjSetJmp(MI, BB);
10266   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10267              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10268     return emitEHSjLjLongJmp(MI, BB);
10269   }
10270 
10271   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10272 
10273   // To "insert" these instructions we actually have to insert their
10274   // control-flow patterns.
10275   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10276   MachineFunction::iterator It = ++BB->getIterator();
10277 
10278   MachineFunction *F = BB->getParent();
10279 
10280   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10281        MI.getOpcode() == PPC::SELECT_CC_I8 ||
10282        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
10283     SmallVector<MachineOperand, 2> Cond;
10284     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10285         MI.getOpcode() == PPC::SELECT_CC_I8)
10286       Cond.push_back(MI.getOperand(4));
10287     else
10288       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10289     Cond.push_back(MI.getOperand(1));
10290 
10291     DebugLoc dl = MI.getDebugLoc();
10292     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10293                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10294   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10295              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10296              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10297              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10298              MI.getOpcode() == PPC::SELECT_CC_F16 ||
10299              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10300              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10301              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10302              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10303              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10304              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10305              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10306              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10307              MI.getOpcode() == PPC::SELECT_CC_SPE ||
10308              MI.getOpcode() == PPC::SELECT_I4 ||
10309              MI.getOpcode() == PPC::SELECT_I8 ||
10310              MI.getOpcode() == PPC::SELECT_F4 ||
10311              MI.getOpcode() == PPC::SELECT_F8 ||
10312              MI.getOpcode() == PPC::SELECT_F16 ||
10313              MI.getOpcode() == PPC::SELECT_QFRC ||
10314              MI.getOpcode() == PPC::SELECT_QSRC ||
10315              MI.getOpcode() == PPC::SELECT_QBRC ||
10316              MI.getOpcode() == PPC::SELECT_SPE ||
10317              MI.getOpcode() == PPC::SELECT_SPE4 ||
10318              MI.getOpcode() == PPC::SELECT_VRRC ||
10319              MI.getOpcode() == PPC::SELECT_VSFRC ||
10320              MI.getOpcode() == PPC::SELECT_VSSRC ||
10321              MI.getOpcode() == PPC::SELECT_VSRC) {
10322     // The incoming instruction knows the destination vreg to set, the
10323     // condition code register to branch on, the true/false values to
10324     // select between, and a branch opcode to use.
10325 
10326     //  thisMBB:
10327     //  ...
10328     //   TrueVal = ...
10329     //   cmpTY ccX, r1, r2
10330     //   bCC copy1MBB
10331     //   fallthrough --> copy0MBB
10332     MachineBasicBlock *thisMBB = BB;
10333     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10334     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10335     DebugLoc dl = MI.getDebugLoc();
10336     F->insert(It, copy0MBB);
10337     F->insert(It, sinkMBB);
10338 
10339     // Transfer the remainder of BB and its successor edges to sinkMBB.
10340     sinkMBB->splice(sinkMBB->begin(), BB,
10341                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10342     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10343 
10344     // Next, add the true and fallthrough blocks as its successors.
10345     BB->addSuccessor(copy0MBB);
10346     BB->addSuccessor(sinkMBB);
10347 
10348     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10349         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10350         MI.getOpcode() == PPC::SELECT_F16 ||
10351         MI.getOpcode() == PPC::SELECT_SPE4 ||
10352         MI.getOpcode() == PPC::SELECT_SPE ||
10353         MI.getOpcode() == PPC::SELECT_QFRC ||
10354         MI.getOpcode() == PPC::SELECT_QSRC ||
10355         MI.getOpcode() == PPC::SELECT_QBRC ||
10356         MI.getOpcode() == PPC::SELECT_VRRC ||
10357         MI.getOpcode() == PPC::SELECT_VSFRC ||
10358         MI.getOpcode() == PPC::SELECT_VSSRC ||
10359         MI.getOpcode() == PPC::SELECT_VSRC) {
10360       BuildMI(BB, dl, TII->get(PPC::BC))
10361           .addReg(MI.getOperand(1).getReg())
10362           .addMBB(sinkMBB);
10363     } else {
10364       unsigned SelectPred = MI.getOperand(4).getImm();
10365       BuildMI(BB, dl, TII->get(PPC::BCC))
10366           .addImm(SelectPred)
10367           .addReg(MI.getOperand(1).getReg())
10368           .addMBB(sinkMBB);
10369     }
10370 
10371     //  copy0MBB:
10372     //   %FalseValue = ...
10373     //   # fallthrough to sinkMBB
10374     BB = copy0MBB;
10375 
10376     // Update machine-CFG edges
10377     BB->addSuccessor(sinkMBB);
10378 
10379     //  sinkMBB:
10380     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10381     //  ...
10382     BB = sinkMBB;
10383     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10384         .addReg(MI.getOperand(3).getReg())
10385         .addMBB(copy0MBB)
10386         .addReg(MI.getOperand(2).getReg())
10387         .addMBB(thisMBB);
10388   } else if (MI.getOpcode() == PPC::ReadTB) {
10389     // To read the 64-bit time-base register on a 32-bit target, we read the
10390     // two halves. Should the counter have wrapped while it was being read, we
10391     // need to try again.
10392     // ...
10393     // readLoop:
10394     // mfspr Rx,TBU # load from TBU
10395     // mfspr Ry,TB  # load from TB
10396     // mfspr Rz,TBU # load from TBU
10397     // cmpw crX,Rx,Rz # check if 'old'='new'
10398     // bne readLoop   # branch if they're not equal
10399     // ...
10400 
10401     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10402     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10403     DebugLoc dl = MI.getDebugLoc();
10404     F->insert(It, readMBB);
10405     F->insert(It, sinkMBB);
10406 
10407     // Transfer the remainder of BB and its successor edges to sinkMBB.
10408     sinkMBB->splice(sinkMBB->begin(), BB,
10409                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10410     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10411 
10412     BB->addSuccessor(readMBB);
10413     BB = readMBB;
10414 
10415     MachineRegisterInfo &RegInfo = F->getRegInfo();
10416     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10417     unsigned LoReg = MI.getOperand(0).getReg();
10418     unsigned HiReg = MI.getOperand(1).getReg();
10419 
10420     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10421     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10422     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10423 
10424     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10425 
10426     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10427       .addReg(HiReg).addReg(ReadAgainReg);
10428     BuildMI(BB, dl, TII->get(PPC::BCC))
10429       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
10430 
10431     BB->addSuccessor(readMBB);
10432     BB->addSuccessor(sinkMBB);
10433   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10434     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10435   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10436     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10437   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10438     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10439   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10440     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10441 
10442   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10443     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10444   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10445     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10446   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10447     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10448   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10449     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10450 
10451   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10452     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10453   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10454     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10455   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10456     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10457   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10458     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10459 
10460   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10461     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10462   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10463     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10464   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10465     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10466   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10467     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10468 
10469   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10470     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10471   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10472     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10473   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10474     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10475   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10476     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10477 
10478   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10479     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10480   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10481     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10482   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10483     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10484   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10485     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10486 
10487   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10488     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10489   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10490     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10491   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10492     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10493   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10494     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10495 
10496   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10497     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10498   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10499     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10500   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10501     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10502   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10503     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10504 
10505   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10506     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10507   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10508     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10509   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10510     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10511   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10512     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10513 
10514   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10515     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10516   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10517     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10518   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10519     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10520   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10521     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10522 
10523   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10524     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10525   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10526     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10527   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10528     BB = EmitAtomicBinary(MI, BB, 4, 0);
10529   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10530     BB = EmitAtomicBinary(MI, BB, 8, 0);
10531   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10532            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10533            (Subtarget.hasPartwordAtomics() &&
10534             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10535            (Subtarget.hasPartwordAtomics() &&
10536             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10537     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10538 
10539     auto LoadMnemonic = PPC::LDARX;
10540     auto StoreMnemonic = PPC::STDCX;
10541     switch (MI.getOpcode()) {
10542     default:
10543       llvm_unreachable("Compare and swap of unknown size");
10544     case PPC::ATOMIC_CMP_SWAP_I8:
10545       LoadMnemonic = PPC::LBARX;
10546       StoreMnemonic = PPC::STBCX;
10547       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10548       break;
10549     case PPC::ATOMIC_CMP_SWAP_I16:
10550       LoadMnemonic = PPC::LHARX;
10551       StoreMnemonic = PPC::STHCX;
10552       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10553       break;
10554     case PPC::ATOMIC_CMP_SWAP_I32:
10555       LoadMnemonic = PPC::LWARX;
10556       StoreMnemonic = PPC::STWCX;
10557       break;
10558     case PPC::ATOMIC_CMP_SWAP_I64:
10559       LoadMnemonic = PPC::LDARX;
10560       StoreMnemonic = PPC::STDCX;
10561       break;
10562     }
10563     unsigned dest = MI.getOperand(0).getReg();
10564     unsigned ptrA = MI.getOperand(1).getReg();
10565     unsigned ptrB = MI.getOperand(2).getReg();
10566     unsigned oldval = MI.getOperand(3).getReg();
10567     unsigned newval = MI.getOperand(4).getReg();
10568     DebugLoc dl = MI.getDebugLoc();
10569 
10570     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10571     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10572     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10573     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10574     F->insert(It, loop1MBB);
10575     F->insert(It, loop2MBB);
10576     F->insert(It, midMBB);
10577     F->insert(It, exitMBB);
10578     exitMBB->splice(exitMBB->begin(), BB,
10579                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10580     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10581 
10582     //  thisMBB:
10583     //   ...
10584     //   fallthrough --> loopMBB
10585     BB->addSuccessor(loop1MBB);
10586 
10587     // loop1MBB:
10588     //   l[bhwd]arx dest, ptr
10589     //   cmp[wd] dest, oldval
10590     //   bne- midMBB
10591     // loop2MBB:
10592     //   st[bhwd]cx. newval, ptr
10593     //   bne- loopMBB
10594     //   b exitBB
10595     // midMBB:
10596     //   st[bhwd]cx. dest, ptr
10597     // exitBB:
10598     BB = loop1MBB;
10599     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10600       .addReg(ptrA).addReg(ptrB);
10601     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10602       .addReg(oldval).addReg(dest);
10603     BuildMI(BB, dl, TII->get(PPC::BCC))
10604       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10605     BB->addSuccessor(loop2MBB);
10606     BB->addSuccessor(midMBB);
10607 
10608     BB = loop2MBB;
10609     BuildMI(BB, dl, TII->get(StoreMnemonic))
10610       .addReg(newval).addReg(ptrA).addReg(ptrB);
10611     BuildMI(BB, dl, TII->get(PPC::BCC))
10612       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10613     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10614     BB->addSuccessor(loop1MBB);
10615     BB->addSuccessor(exitMBB);
10616 
10617     BB = midMBB;
10618     BuildMI(BB, dl, TII->get(StoreMnemonic))
10619       .addReg(dest).addReg(ptrA).addReg(ptrB);
10620     BB->addSuccessor(exitMBB);
10621 
10622     //  exitMBB:
10623     //   ...
10624     BB = exitMBB;
10625   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10626              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10627     // We must use 64-bit registers for addresses when targeting 64-bit,
10628     // since we're actually doing arithmetic on them.  Other registers
10629     // can be 32-bit.
10630     bool is64bit = Subtarget.isPPC64();
10631     bool isLittleEndian = Subtarget.isLittleEndian();
10632     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10633 
10634     unsigned dest = MI.getOperand(0).getReg();
10635     unsigned ptrA = MI.getOperand(1).getReg();
10636     unsigned ptrB = MI.getOperand(2).getReg();
10637     unsigned oldval = MI.getOperand(3).getReg();
10638     unsigned newval = MI.getOperand(4).getReg();
10639     DebugLoc dl = MI.getDebugLoc();
10640 
10641     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10642     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10643     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10644     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10645     F->insert(It, loop1MBB);
10646     F->insert(It, loop2MBB);
10647     F->insert(It, midMBB);
10648     F->insert(It, exitMBB);
10649     exitMBB->splice(exitMBB->begin(), BB,
10650                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10651     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10652 
10653     MachineRegisterInfo &RegInfo = F->getRegInfo();
10654     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
10655                                             : &PPC::GPRCRegClass;
10656     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10657     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
10658     unsigned ShiftReg =
10659       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
10660     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
10661     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
10662     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
10663     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
10664     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
10665     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
10666     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
10667     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
10668     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
10669     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
10670     unsigned Ptr1Reg;
10671     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
10672     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10673     //  thisMBB:
10674     //   ...
10675     //   fallthrough --> loopMBB
10676     BB->addSuccessor(loop1MBB);
10677 
10678     // The 4-byte load must be aligned, while a char or short may be
10679     // anywhere in the word.  Hence all this nasty bookkeeping code.
10680     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10681     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10682     //   xori shift, shift1, 24 [16]
10683     //   rlwinm ptr, ptr1, 0, 0, 29
10684     //   slw newval2, newval, shift
10685     //   slw oldval2, oldval,shift
10686     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10687     //   slw mask, mask2, shift
10688     //   and newval3, newval2, mask
10689     //   and oldval3, oldval2, mask
10690     // loop1MBB:
10691     //   lwarx tmpDest, ptr
10692     //   and tmp, tmpDest, mask
10693     //   cmpw tmp, oldval3
10694     //   bne- midMBB
10695     // loop2MBB:
10696     //   andc tmp2, tmpDest, mask
10697     //   or tmp4, tmp2, newval3
10698     //   stwcx. tmp4, ptr
10699     //   bne- loop1MBB
10700     //   b exitBB
10701     // midMBB:
10702     //   stwcx. tmpDest, ptr
10703     // exitBB:
10704     //   srw dest, tmpDest, shift
10705     if (ptrA != ZeroReg) {
10706       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10707       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10708         .addReg(ptrA).addReg(ptrB);
10709     } else {
10710       Ptr1Reg = ptrB;
10711     }
10712     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
10713         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
10714     if (!isLittleEndian)
10715       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
10716           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
10717     if (is64bit)
10718       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10719         .addReg(Ptr1Reg).addImm(0).addImm(61);
10720     else
10721       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10722         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
10723     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10724         .addReg(newval).addReg(ShiftReg);
10725     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10726         .addReg(oldval).addReg(ShiftReg);
10727     if (is8bit)
10728       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10729     else {
10730       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10731       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10732         .addReg(Mask3Reg).addImm(65535);
10733     }
10734     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10735         .addReg(Mask2Reg).addReg(ShiftReg);
10736     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10737         .addReg(NewVal2Reg).addReg(MaskReg);
10738     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10739         .addReg(OldVal2Reg).addReg(MaskReg);
10740 
10741     BB = loop1MBB;
10742     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10743         .addReg(ZeroReg).addReg(PtrReg);
10744     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
10745         .addReg(TmpDestReg).addReg(MaskReg);
10746     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10747         .addReg(TmpReg).addReg(OldVal3Reg);
10748     BuildMI(BB, dl, TII->get(PPC::BCC))
10749         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10750     BB->addSuccessor(loop2MBB);
10751     BB->addSuccessor(midMBB);
10752 
10753     BB = loop2MBB;
10754     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
10755         .addReg(TmpDestReg).addReg(MaskReg);
10756     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
10757         .addReg(Tmp2Reg).addReg(NewVal3Reg);
10758     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
10759         .addReg(ZeroReg).addReg(PtrReg);
10760     BuildMI(BB, dl, TII->get(PPC::BCC))
10761       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10762     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10763     BB->addSuccessor(loop1MBB);
10764     BB->addSuccessor(exitMBB);
10765 
10766     BB = midMBB;
10767     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
10768       .addReg(ZeroReg).addReg(PtrReg);
10769     BB->addSuccessor(exitMBB);
10770 
10771     //  exitMBB:
10772     //   ...
10773     BB = exitMBB;
10774     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
10775       .addReg(ShiftReg);
10776   } else if (MI.getOpcode() == PPC::FADDrtz) {
10777     // This pseudo performs an FADD with rounding mode temporarily forced
10778     // to round-to-zero.  We emit this via custom inserter since the FPSCR
10779     // is not modeled at the SelectionDAG level.
10780     unsigned Dest = MI.getOperand(0).getReg();
10781     unsigned Src1 = MI.getOperand(1).getReg();
10782     unsigned Src2 = MI.getOperand(2).getReg();
10783     DebugLoc dl = MI.getDebugLoc();
10784 
10785     MachineRegisterInfo &RegInfo = F->getRegInfo();
10786     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10787 
10788     // Save FPSCR value.
10789     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10790 
10791     // Set rounding mode to round-to-zero.
10792     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
10793     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
10794 
10795     // Perform addition.
10796     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
10797 
10798     // Restore FPSCR value.
10799     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
10800   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10801              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
10802              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10803              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
10804     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10805                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
10806                           ? PPC::ANDIo8
10807                           : PPC::ANDIo;
10808     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10809                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
10810 
10811     MachineRegisterInfo &RegInfo = F->getRegInfo();
10812     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
10813                                                   &PPC::GPRCRegClass :
10814                                                   &PPC::G8RCRegClass);
10815 
10816     DebugLoc dl = MI.getDebugLoc();
10817     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10818         .addReg(MI.getOperand(1).getReg())
10819         .addImm(1);
10820     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10821             MI.getOperand(0).getReg())
10822         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10823   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10824     DebugLoc Dl = MI.getDebugLoc();
10825     MachineRegisterInfo &RegInfo = F->getRegInfo();
10826     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10827     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10828     return BB;
10829   } else {
10830     llvm_unreachable("Unexpected instr type to insert");
10831   }
10832 
10833   MI.eraseFromParent(); // The pseudo instruction is gone now.
10834   return BB;
10835 }
10836 
10837 //===----------------------------------------------------------------------===//
10838 // Target Optimization Hooks
10839 //===----------------------------------------------------------------------===//
10840 
10841 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10842   // For the estimates, convergence is quadratic, so we essentially double the
10843   // number of digits correct after every iteration. For both FRE and FRSQRTE,
10844   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10845   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10846   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10847   if (VT.getScalarType() == MVT::f64)
10848     RefinementSteps++;
10849   return RefinementSteps;
10850 }
10851 
10852 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10853                                            int Enabled, int &RefinementSteps,
10854                                            bool &UseOneConstNR,
10855                                            bool Reciprocal) const {
10856   EVT VT = Operand.getValueType();
10857   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10858       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10859       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10860       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10861       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10862       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10863     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10864       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10865 
10866     UseOneConstNR = true;
10867     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10868   }
10869   return SDValue();
10870 }
10871 
10872 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10873                                             int Enabled,
10874                                             int &RefinementSteps) const {
10875   EVT VT = Operand.getValueType();
10876   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10877       (VT == MVT::f64 && Subtarget.hasFRE()) ||
10878       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10879       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10880       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10881       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10882     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10883       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10884     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10885   }
10886   return SDValue();
10887 }
10888 
10889 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10890   // Note: This functionality is used only when unsafe-fp-math is enabled, and
10891   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10892   // enabled for division), this functionality is redundant with the default
10893   // combiner logic (once the division -> reciprocal/multiply transformation
10894   // has taken place). As a result, this matters more for older cores than for
10895   // newer ones.
10896 
10897   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10898   // reciprocal if there are two or more FDIVs (for embedded cores with only
10899   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10900   switch (Subtarget.getDarwinDirective()) {
10901   default:
10902     return 3;
10903   case PPC::DIR_440:
10904   case PPC::DIR_A2:
10905   case PPC::DIR_E500:
10906   case PPC::DIR_E500mc:
10907   case PPC::DIR_E5500:
10908     return 2;
10909   }
10910 }
10911 
10912 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10913 // collapsed, and so we need to look through chains of them.
10914 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10915                                      int64_t& Offset, SelectionDAG &DAG) {
10916   if (DAG.isBaseWithConstantOffset(Loc)) {
10917     Base = Loc.getOperand(0);
10918     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10919 
10920     // The base might itself be a base plus an offset, and if so, accumulate
10921     // that as well.
10922     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10923   }
10924 }
10925 
10926 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10927                             unsigned Bytes, int Dist,
10928                             SelectionDAG &DAG) {
10929   if (VT.getSizeInBits() / 8 != Bytes)
10930     return false;
10931 
10932   SDValue BaseLoc = Base->getBasePtr();
10933   if (Loc.getOpcode() == ISD::FrameIndex) {
10934     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10935       return false;
10936     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10937     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10938     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10939     int FS  = MFI.getObjectSize(FI);
10940     int BFS = MFI.getObjectSize(BFI);
10941     if (FS != BFS || FS != (int)Bytes) return false;
10942     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10943   }
10944 
10945   SDValue Base1 = Loc, Base2 = BaseLoc;
10946   int64_t Offset1 = 0, Offset2 = 0;
10947   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10948   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10949   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10950     return true;
10951 
10952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10953   const GlobalValue *GV1 = nullptr;
10954   const GlobalValue *GV2 = nullptr;
10955   Offset1 = 0;
10956   Offset2 = 0;
10957   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10958   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10959   if (isGA1 && isGA2 && GV1 == GV2)
10960     return Offset1 == (Offset2 + Dist*Bytes);
10961   return false;
10962 }
10963 
10964 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10965 // not enforce equality of the chain operands.
10966 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10967                             unsigned Bytes, int Dist,
10968                             SelectionDAG &DAG) {
10969   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10970     EVT VT = LS->getMemoryVT();
10971     SDValue Loc = LS->getBasePtr();
10972     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10973   }
10974 
10975   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10976     EVT VT;
10977     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10978     default: return false;
10979     case Intrinsic::ppc_qpx_qvlfd:
10980     case Intrinsic::ppc_qpx_qvlfda:
10981       VT = MVT::v4f64;
10982       break;
10983     case Intrinsic::ppc_qpx_qvlfs:
10984     case Intrinsic::ppc_qpx_qvlfsa:
10985       VT = MVT::v4f32;
10986       break;
10987     case Intrinsic::ppc_qpx_qvlfcd:
10988     case Intrinsic::ppc_qpx_qvlfcda:
10989       VT = MVT::v2f64;
10990       break;
10991     case Intrinsic::ppc_qpx_qvlfcs:
10992     case Intrinsic::ppc_qpx_qvlfcsa:
10993       VT = MVT::v2f32;
10994       break;
10995     case Intrinsic::ppc_qpx_qvlfiwa:
10996     case Intrinsic::ppc_qpx_qvlfiwz:
10997     case Intrinsic::ppc_altivec_lvx:
10998     case Intrinsic::ppc_altivec_lvxl:
10999     case Intrinsic::ppc_vsx_lxvw4x:
11000     case Intrinsic::ppc_vsx_lxvw4x_be:
11001       VT = MVT::v4i32;
11002       break;
11003     case Intrinsic::ppc_vsx_lxvd2x:
11004     case Intrinsic::ppc_vsx_lxvd2x_be:
11005       VT = MVT::v2f64;
11006       break;
11007     case Intrinsic::ppc_altivec_lvebx:
11008       VT = MVT::i8;
11009       break;
11010     case Intrinsic::ppc_altivec_lvehx:
11011       VT = MVT::i16;
11012       break;
11013     case Intrinsic::ppc_altivec_lvewx:
11014       VT = MVT::i32;
11015       break;
11016     }
11017 
11018     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11019   }
11020 
11021   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11022     EVT VT;
11023     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11024     default: return false;
11025     case Intrinsic::ppc_qpx_qvstfd:
11026     case Intrinsic::ppc_qpx_qvstfda:
11027       VT = MVT::v4f64;
11028       break;
11029     case Intrinsic::ppc_qpx_qvstfs:
11030     case Intrinsic::ppc_qpx_qvstfsa:
11031       VT = MVT::v4f32;
11032       break;
11033     case Intrinsic::ppc_qpx_qvstfcd:
11034     case Intrinsic::ppc_qpx_qvstfcda:
11035       VT = MVT::v2f64;
11036       break;
11037     case Intrinsic::ppc_qpx_qvstfcs:
11038     case Intrinsic::ppc_qpx_qvstfcsa:
11039       VT = MVT::v2f32;
11040       break;
11041     case Intrinsic::ppc_qpx_qvstfiw:
11042     case Intrinsic::ppc_qpx_qvstfiwa:
11043     case Intrinsic::ppc_altivec_stvx:
11044     case Intrinsic::ppc_altivec_stvxl:
11045     case Intrinsic::ppc_vsx_stxvw4x:
11046       VT = MVT::v4i32;
11047       break;
11048     case Intrinsic::ppc_vsx_stxvd2x:
11049       VT = MVT::v2f64;
11050       break;
11051     case Intrinsic::ppc_vsx_stxvw4x_be:
11052       VT = MVT::v4i32;
11053       break;
11054     case Intrinsic::ppc_vsx_stxvd2x_be:
11055       VT = MVT::v2f64;
11056       break;
11057     case Intrinsic::ppc_altivec_stvebx:
11058       VT = MVT::i8;
11059       break;
11060     case Intrinsic::ppc_altivec_stvehx:
11061       VT = MVT::i16;
11062       break;
11063     case Intrinsic::ppc_altivec_stvewx:
11064       VT = MVT::i32;
11065       break;
11066     }
11067 
11068     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11069   }
11070 
11071   return false;
11072 }
11073 
11074 // Return true is there is a nearyby consecutive load to the one provided
11075 // (regardless of alignment). We search up and down the chain, looking though
11076 // token factors and other loads (but nothing else). As a result, a true result
11077 // indicates that it is safe to create a new consecutive load adjacent to the
11078 // load provided.
11079 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11080   SDValue Chain = LD->getChain();
11081   EVT VT = LD->getMemoryVT();
11082 
11083   SmallSet<SDNode *, 16> LoadRoots;
11084   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11085   SmallSet<SDNode *, 16> Visited;
11086 
11087   // First, search up the chain, branching to follow all token-factor operands.
11088   // If we find a consecutive load, then we're done, otherwise, record all
11089   // nodes just above the top-level loads and token factors.
11090   while (!Queue.empty()) {
11091     SDNode *ChainNext = Queue.pop_back_val();
11092     if (!Visited.insert(ChainNext).second)
11093       continue;
11094 
11095     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11096       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11097         return true;
11098 
11099       if (!Visited.count(ChainLD->getChain().getNode()))
11100         Queue.push_back(ChainLD->getChain().getNode());
11101     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11102       for (const SDUse &O : ChainNext->ops())
11103         if (!Visited.count(O.getNode()))
11104           Queue.push_back(O.getNode());
11105     } else
11106       LoadRoots.insert(ChainNext);
11107   }
11108 
11109   // Second, search down the chain, starting from the top-level nodes recorded
11110   // in the first phase. These top-level nodes are the nodes just above all
11111   // loads and token factors. Starting with their uses, recursively look though
11112   // all loads (just the chain uses) and token factors to find a consecutive
11113   // load.
11114   Visited.clear();
11115   Queue.clear();
11116 
11117   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11118        IE = LoadRoots.end(); I != IE; ++I) {
11119     Queue.push_back(*I);
11120 
11121     while (!Queue.empty()) {
11122       SDNode *LoadRoot = Queue.pop_back_val();
11123       if (!Visited.insert(LoadRoot).second)
11124         continue;
11125 
11126       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11127         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11128           return true;
11129 
11130       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11131            UE = LoadRoot->use_end(); UI != UE; ++UI)
11132         if (((isa<MemSDNode>(*UI) &&
11133             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11134             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11135           Queue.push_back(*UI);
11136     }
11137   }
11138 
11139   return false;
11140 }
11141 
11142 /// This function is called when we have proved that a SETCC node can be replaced
11143 /// by subtraction (and other supporting instructions) so that the result of
11144 /// comparison is kept in a GPR instead of CR. This function is purely for
11145 /// codegen purposes and has some flags to guide the codegen process.
11146 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11147                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11148   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11149 
11150   // Zero extend the operands to the largest legal integer. Originally, they
11151   // must be of a strictly smaller size.
11152   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11153                          DAG.getConstant(Size, DL, MVT::i32));
11154   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11155                          DAG.getConstant(Size, DL, MVT::i32));
11156 
11157   // Swap if needed. Depends on the condition code.
11158   if (Swap)
11159     std::swap(Op0, Op1);
11160 
11161   // Subtract extended integers.
11162   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11163 
11164   // Move the sign bit to the least significant position and zero out the rest.
11165   // Now the least significant bit carries the result of original comparison.
11166   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11167                              DAG.getConstant(Size - 1, DL, MVT::i32));
11168   auto Final = Shifted;
11169 
11170   // Complement the result if needed. Based on the condition code.
11171   if (Complement)
11172     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11173                         DAG.getConstant(1, DL, MVT::i64));
11174 
11175   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11176 }
11177 
11178 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11179                                                   DAGCombinerInfo &DCI) const {
11180   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11181 
11182   SelectionDAG &DAG = DCI.DAG;
11183   SDLoc DL(N);
11184 
11185   // Size of integers being compared has a critical role in the following
11186   // analysis, so we prefer to do this when all types are legal.
11187   if (!DCI.isAfterLegalizeDAG())
11188     return SDValue();
11189 
11190   // If all users of SETCC extend its value to a legal integer type
11191   // then we replace SETCC with a subtraction
11192   for (SDNode::use_iterator UI = N->use_begin(),
11193        UE = N->use_end(); UI != UE; ++UI) {
11194     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11195       return SDValue();
11196   }
11197 
11198   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11199   auto OpSize = N->getOperand(0).getValueSizeInBits();
11200 
11201   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11202 
11203   if (OpSize < Size) {
11204     switch (CC) {
11205     default: break;
11206     case ISD::SETULT:
11207       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11208     case ISD::SETULE:
11209       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11210     case ISD::SETUGT:
11211       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11212     case ISD::SETUGE:
11213       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11214     }
11215   }
11216 
11217   return SDValue();
11218 }
11219 
11220 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11221                                                   DAGCombinerInfo &DCI) const {
11222   SelectionDAG &DAG = DCI.DAG;
11223   SDLoc dl(N);
11224 
11225   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11226   // If we're tracking CR bits, we need to be careful that we don't have:
11227   //   trunc(binary-ops(zext(x), zext(y)))
11228   // or
11229   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11230   // such that we're unnecessarily moving things into GPRs when it would be
11231   // better to keep them in CR bits.
11232 
11233   // Note that trunc here can be an actual i1 trunc, or can be the effective
11234   // truncation that comes from a setcc or select_cc.
11235   if (N->getOpcode() == ISD::TRUNCATE &&
11236       N->getValueType(0) != MVT::i1)
11237     return SDValue();
11238 
11239   if (N->getOperand(0).getValueType() != MVT::i32 &&
11240       N->getOperand(0).getValueType() != MVT::i64)
11241     return SDValue();
11242 
11243   if (N->getOpcode() == ISD::SETCC ||
11244       N->getOpcode() == ISD::SELECT_CC) {
11245     // If we're looking at a comparison, then we need to make sure that the
11246     // high bits (all except for the first) don't matter the result.
11247     ISD::CondCode CC =
11248       cast<CondCodeSDNode>(N->getOperand(
11249         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11250     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11251 
11252     if (ISD::isSignedIntSetCC(CC)) {
11253       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11254           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11255         return SDValue();
11256     } else if (ISD::isUnsignedIntSetCC(CC)) {
11257       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11258                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11259           !DAG.MaskedValueIsZero(N->getOperand(1),
11260                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11261         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11262                                              : SDValue());
11263     } else {
11264       // This is neither a signed nor an unsigned comparison, just make sure
11265       // that the high bits are equal.
11266       KnownBits Op1Known, Op2Known;
11267       DAG.computeKnownBits(N->getOperand(0), Op1Known);
11268       DAG.computeKnownBits(N->getOperand(1), Op2Known);
11269 
11270       // We don't really care about what is known about the first bit (if
11271       // anything), so clear it in all masks prior to comparing them.
11272       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11273       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11274 
11275       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11276         return SDValue();
11277     }
11278   }
11279 
11280   // We now know that the higher-order bits are irrelevant, we just need to
11281   // make sure that all of the intermediate operations are bit operations, and
11282   // all inputs are extensions.
11283   if (N->getOperand(0).getOpcode() != ISD::AND &&
11284       N->getOperand(0).getOpcode() != ISD::OR  &&
11285       N->getOperand(0).getOpcode() != ISD::XOR &&
11286       N->getOperand(0).getOpcode() != ISD::SELECT &&
11287       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11288       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11289       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11290       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11291       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11292     return SDValue();
11293 
11294   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11295       N->getOperand(1).getOpcode() != ISD::AND &&
11296       N->getOperand(1).getOpcode() != ISD::OR  &&
11297       N->getOperand(1).getOpcode() != ISD::XOR &&
11298       N->getOperand(1).getOpcode() != ISD::SELECT &&
11299       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11300       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11301       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11302       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11303       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11304     return SDValue();
11305 
11306   SmallVector<SDValue, 4> Inputs;
11307   SmallVector<SDValue, 8> BinOps, PromOps;
11308   SmallPtrSet<SDNode *, 16> Visited;
11309 
11310   for (unsigned i = 0; i < 2; ++i) {
11311     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11312           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11313           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11314           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11315         isa<ConstantSDNode>(N->getOperand(i)))
11316       Inputs.push_back(N->getOperand(i));
11317     else
11318       BinOps.push_back(N->getOperand(i));
11319 
11320     if (N->getOpcode() == ISD::TRUNCATE)
11321       break;
11322   }
11323 
11324   // Visit all inputs, collect all binary operations (and, or, xor and
11325   // select) that are all fed by extensions.
11326   while (!BinOps.empty()) {
11327     SDValue BinOp = BinOps.back();
11328     BinOps.pop_back();
11329 
11330     if (!Visited.insert(BinOp.getNode()).second)
11331       continue;
11332 
11333     PromOps.push_back(BinOp);
11334 
11335     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11336       // The condition of the select is not promoted.
11337       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11338         continue;
11339       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11340         continue;
11341 
11342       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11343             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11344             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11345            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11346           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11347         Inputs.push_back(BinOp.getOperand(i));
11348       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11349                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11350                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11351                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11352                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11353                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11354                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11355                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11356                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11357         BinOps.push_back(BinOp.getOperand(i));
11358       } else {
11359         // We have an input that is not an extension or another binary
11360         // operation; we'll abort this transformation.
11361         return SDValue();
11362       }
11363     }
11364   }
11365 
11366   // Make sure that this is a self-contained cluster of operations (which
11367   // is not quite the same thing as saying that everything has only one
11368   // use).
11369   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11370     if (isa<ConstantSDNode>(Inputs[i]))
11371       continue;
11372 
11373     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11374                               UE = Inputs[i].getNode()->use_end();
11375          UI != UE; ++UI) {
11376       SDNode *User = *UI;
11377       if (User != N && !Visited.count(User))
11378         return SDValue();
11379 
11380       // Make sure that we're not going to promote the non-output-value
11381       // operand(s) or SELECT or SELECT_CC.
11382       // FIXME: Although we could sometimes handle this, and it does occur in
11383       // practice that one of the condition inputs to the select is also one of
11384       // the outputs, we currently can't deal with this.
11385       if (User->getOpcode() == ISD::SELECT) {
11386         if (User->getOperand(0) == Inputs[i])
11387           return SDValue();
11388       } else if (User->getOpcode() == ISD::SELECT_CC) {
11389         if (User->getOperand(0) == Inputs[i] ||
11390             User->getOperand(1) == Inputs[i])
11391           return SDValue();
11392       }
11393     }
11394   }
11395 
11396   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11397     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11398                               UE = PromOps[i].getNode()->use_end();
11399          UI != UE; ++UI) {
11400       SDNode *User = *UI;
11401       if (User != N && !Visited.count(User))
11402         return SDValue();
11403 
11404       // Make sure that we're not going to promote the non-output-value
11405       // operand(s) or SELECT or SELECT_CC.
11406       // FIXME: Although we could sometimes handle this, and it does occur in
11407       // practice that one of the condition inputs to the select is also one of
11408       // the outputs, we currently can't deal with this.
11409       if (User->getOpcode() == ISD::SELECT) {
11410         if (User->getOperand(0) == PromOps[i])
11411           return SDValue();
11412       } else if (User->getOpcode() == ISD::SELECT_CC) {
11413         if (User->getOperand(0) == PromOps[i] ||
11414             User->getOperand(1) == PromOps[i])
11415           return SDValue();
11416       }
11417     }
11418   }
11419 
11420   // Replace all inputs with the extension operand.
11421   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11422     // Constants may have users outside the cluster of to-be-promoted nodes,
11423     // and so we need to replace those as we do the promotions.
11424     if (isa<ConstantSDNode>(Inputs[i]))
11425       continue;
11426     else
11427       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11428   }
11429 
11430   std::list<HandleSDNode> PromOpHandles;
11431   for (auto &PromOp : PromOps)
11432     PromOpHandles.emplace_back(PromOp);
11433 
11434   // Replace all operations (these are all the same, but have a different
11435   // (i1) return type). DAG.getNode will validate that the types of
11436   // a binary operator match, so go through the list in reverse so that
11437   // we've likely promoted both operands first. Any intermediate truncations or
11438   // extensions disappear.
11439   while (!PromOpHandles.empty()) {
11440     SDValue PromOp = PromOpHandles.back().getValue();
11441     PromOpHandles.pop_back();
11442 
11443     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11444         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11445         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11446         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11447       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11448           PromOp.getOperand(0).getValueType() != MVT::i1) {
11449         // The operand is not yet ready (see comment below).
11450         PromOpHandles.emplace_front(PromOp);
11451         continue;
11452       }
11453 
11454       SDValue RepValue = PromOp.getOperand(0);
11455       if (isa<ConstantSDNode>(RepValue))
11456         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11457 
11458       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11459       continue;
11460     }
11461 
11462     unsigned C;
11463     switch (PromOp.getOpcode()) {
11464     default:             C = 0; break;
11465     case ISD::SELECT:    C = 1; break;
11466     case ISD::SELECT_CC: C = 2; break;
11467     }
11468 
11469     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11470          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11471         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11472          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11473       // The to-be-promoted operands of this node have not yet been
11474       // promoted (this should be rare because we're going through the
11475       // list backward, but if one of the operands has several users in
11476       // this cluster of to-be-promoted nodes, it is possible).
11477       PromOpHandles.emplace_front(PromOp);
11478       continue;
11479     }
11480 
11481     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11482                                 PromOp.getNode()->op_end());
11483 
11484     // If there are any constant inputs, make sure they're replaced now.
11485     for (unsigned i = 0; i < 2; ++i)
11486       if (isa<ConstantSDNode>(Ops[C+i]))
11487         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11488 
11489     DAG.ReplaceAllUsesOfValueWith(PromOp,
11490       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11491   }
11492 
11493   // Now we're left with the initial truncation itself.
11494   if (N->getOpcode() == ISD::TRUNCATE)
11495     return N->getOperand(0);
11496 
11497   // Otherwise, this is a comparison. The operands to be compared have just
11498   // changed type (to i1), but everything else is the same.
11499   return SDValue(N, 0);
11500 }
11501 
11502 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11503                                                   DAGCombinerInfo &DCI) const {
11504   SelectionDAG &DAG = DCI.DAG;
11505   SDLoc dl(N);
11506 
11507   // If we're tracking CR bits, we need to be careful that we don't have:
11508   //   zext(binary-ops(trunc(x), trunc(y)))
11509   // or
11510   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11511   // such that we're unnecessarily moving things into CR bits that can more
11512   // efficiently stay in GPRs. Note that if we're not certain that the high
11513   // bits are set as required by the final extension, we still may need to do
11514   // some masking to get the proper behavior.
11515 
11516   // This same functionality is important on PPC64 when dealing with
11517   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11518   // the return values of functions. Because it is so similar, it is handled
11519   // here as well.
11520 
11521   if (N->getValueType(0) != MVT::i32 &&
11522       N->getValueType(0) != MVT::i64)
11523     return SDValue();
11524 
11525   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11526         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11527     return SDValue();
11528 
11529   if (N->getOperand(0).getOpcode() != ISD::AND &&
11530       N->getOperand(0).getOpcode() != ISD::OR  &&
11531       N->getOperand(0).getOpcode() != ISD::XOR &&
11532       N->getOperand(0).getOpcode() != ISD::SELECT &&
11533       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11534     return SDValue();
11535 
11536   SmallVector<SDValue, 4> Inputs;
11537   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11538   SmallPtrSet<SDNode *, 16> Visited;
11539 
11540   // Visit all inputs, collect all binary operations (and, or, xor and
11541   // select) that are all fed by truncations.
11542   while (!BinOps.empty()) {
11543     SDValue BinOp = BinOps.back();
11544     BinOps.pop_back();
11545 
11546     if (!Visited.insert(BinOp.getNode()).second)
11547       continue;
11548 
11549     PromOps.push_back(BinOp);
11550 
11551     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11552       // The condition of the select is not promoted.
11553       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11554         continue;
11555       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11556         continue;
11557 
11558       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11559           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11560         Inputs.push_back(BinOp.getOperand(i));
11561       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11562                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11563                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11564                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11565                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11566         BinOps.push_back(BinOp.getOperand(i));
11567       } else {
11568         // We have an input that is not a truncation or another binary
11569         // operation; we'll abort this transformation.
11570         return SDValue();
11571       }
11572     }
11573   }
11574 
11575   // The operands of a select that must be truncated when the select is
11576   // promoted because the operand is actually part of the to-be-promoted set.
11577   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11578 
11579   // Make sure that this is a self-contained cluster of operations (which
11580   // is not quite the same thing as saying that everything has only one
11581   // use).
11582   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11583     if (isa<ConstantSDNode>(Inputs[i]))
11584       continue;
11585 
11586     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11587                               UE = Inputs[i].getNode()->use_end();
11588          UI != UE; ++UI) {
11589       SDNode *User = *UI;
11590       if (User != N && !Visited.count(User))
11591         return SDValue();
11592 
11593       // If we're going to promote the non-output-value operand(s) or SELECT or
11594       // SELECT_CC, record them for truncation.
11595       if (User->getOpcode() == ISD::SELECT) {
11596         if (User->getOperand(0) == Inputs[i])
11597           SelectTruncOp[0].insert(std::make_pair(User,
11598                                     User->getOperand(0).getValueType()));
11599       } else if (User->getOpcode() == ISD::SELECT_CC) {
11600         if (User->getOperand(0) == Inputs[i])
11601           SelectTruncOp[0].insert(std::make_pair(User,
11602                                     User->getOperand(0).getValueType()));
11603         if (User->getOperand(1) == Inputs[i])
11604           SelectTruncOp[1].insert(std::make_pair(User,
11605                                     User->getOperand(1).getValueType()));
11606       }
11607     }
11608   }
11609 
11610   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11611     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11612                               UE = PromOps[i].getNode()->use_end();
11613          UI != UE; ++UI) {
11614       SDNode *User = *UI;
11615       if (User != N && !Visited.count(User))
11616         return SDValue();
11617 
11618       // If we're going to promote the non-output-value operand(s) or SELECT or
11619       // SELECT_CC, record them for truncation.
11620       if (User->getOpcode() == ISD::SELECT) {
11621         if (User->getOperand(0) == PromOps[i])
11622           SelectTruncOp[0].insert(std::make_pair(User,
11623                                     User->getOperand(0).getValueType()));
11624       } else if (User->getOpcode() == ISD::SELECT_CC) {
11625         if (User->getOperand(0) == PromOps[i])
11626           SelectTruncOp[0].insert(std::make_pair(User,
11627                                     User->getOperand(0).getValueType()));
11628         if (User->getOperand(1) == PromOps[i])
11629           SelectTruncOp[1].insert(std::make_pair(User,
11630                                     User->getOperand(1).getValueType()));
11631       }
11632     }
11633   }
11634 
11635   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11636   bool ReallyNeedsExt = false;
11637   if (N->getOpcode() != ISD::ANY_EXTEND) {
11638     // If all of the inputs are not already sign/zero extended, then
11639     // we'll still need to do that at the end.
11640     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11641       if (isa<ConstantSDNode>(Inputs[i]))
11642         continue;
11643 
11644       unsigned OpBits =
11645         Inputs[i].getOperand(0).getValueSizeInBits();
11646       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11647 
11648       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11649            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11650                                   APInt::getHighBitsSet(OpBits,
11651                                                         OpBits-PromBits))) ||
11652           (N->getOpcode() == ISD::SIGN_EXTEND &&
11653            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11654              (OpBits-(PromBits-1)))) {
11655         ReallyNeedsExt = true;
11656         break;
11657       }
11658     }
11659   }
11660 
11661   // Replace all inputs, either with the truncation operand, or a
11662   // truncation or extension to the final output type.
11663   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11664     // Constant inputs need to be replaced with the to-be-promoted nodes that
11665     // use them because they might have users outside of the cluster of
11666     // promoted nodes.
11667     if (isa<ConstantSDNode>(Inputs[i]))
11668       continue;
11669 
11670     SDValue InSrc = Inputs[i].getOperand(0);
11671     if (Inputs[i].getValueType() == N->getValueType(0))
11672       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
11673     else if (N->getOpcode() == ISD::SIGN_EXTEND)
11674       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11675         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
11676     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11677       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11678         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
11679     else
11680       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11681         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
11682   }
11683 
11684   std::list<HandleSDNode> PromOpHandles;
11685   for (auto &PromOp : PromOps)
11686     PromOpHandles.emplace_back(PromOp);
11687 
11688   // Replace all operations (these are all the same, but have a different
11689   // (promoted) return type). DAG.getNode will validate that the types of
11690   // a binary operator match, so go through the list in reverse so that
11691   // we've likely promoted both operands first.
11692   while (!PromOpHandles.empty()) {
11693     SDValue PromOp = PromOpHandles.back().getValue();
11694     PromOpHandles.pop_back();
11695 
11696     unsigned C;
11697     switch (PromOp.getOpcode()) {
11698     default:             C = 0; break;
11699     case ISD::SELECT:    C = 1; break;
11700     case ISD::SELECT_CC: C = 2; break;
11701     }
11702 
11703     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11704          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
11705         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11706          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
11707       // The to-be-promoted operands of this node have not yet been
11708       // promoted (this should be rare because we're going through the
11709       // list backward, but if one of the operands has several users in
11710       // this cluster of to-be-promoted nodes, it is possible).
11711       PromOpHandles.emplace_front(PromOp);
11712       continue;
11713     }
11714 
11715     // For SELECT and SELECT_CC nodes, we do a similar check for any
11716     // to-be-promoted comparison inputs.
11717     if (PromOp.getOpcode() == ISD::SELECT ||
11718         PromOp.getOpcode() == ISD::SELECT_CC) {
11719       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
11720            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
11721           (SelectTruncOp[1].count(PromOp.getNode()) &&
11722            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
11723         PromOpHandles.emplace_front(PromOp);
11724         continue;
11725       }
11726     }
11727 
11728     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11729                                 PromOp.getNode()->op_end());
11730 
11731     // If this node has constant inputs, then they'll need to be promoted here.
11732     for (unsigned i = 0; i < 2; ++i) {
11733       if (!isa<ConstantSDNode>(Ops[C+i]))
11734         continue;
11735       if (Ops[C+i].getValueType() == N->getValueType(0))
11736         continue;
11737 
11738       if (N->getOpcode() == ISD::SIGN_EXTEND)
11739         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11740       else if (N->getOpcode() == ISD::ZERO_EXTEND)
11741         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11742       else
11743         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11744     }
11745 
11746     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
11747     // truncate them again to the original value type.
11748     if (PromOp.getOpcode() == ISD::SELECT ||
11749         PromOp.getOpcode() == ISD::SELECT_CC) {
11750       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
11751       if (SI0 != SelectTruncOp[0].end())
11752         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
11753       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
11754       if (SI1 != SelectTruncOp[1].end())
11755         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
11756     }
11757 
11758     DAG.ReplaceAllUsesOfValueWith(PromOp,
11759       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
11760   }
11761 
11762   // Now we're left with the initial extension itself.
11763   if (!ReallyNeedsExt)
11764     return N->getOperand(0);
11765 
11766   // To zero extend, just mask off everything except for the first bit (in the
11767   // i1 case).
11768   if (N->getOpcode() == ISD::ZERO_EXTEND)
11769     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
11770                        DAG.getConstant(APInt::getLowBitsSet(
11771                                          N->getValueSizeInBits(0), PromBits),
11772                                        dl, N->getValueType(0)));
11773 
11774   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
11775          "Invalid extension type");
11776   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
11777   SDValue ShiftCst =
11778       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
11779   return DAG.getNode(
11780       ISD::SRA, dl, N->getValueType(0),
11781       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
11782       ShiftCst);
11783 }
11784 
11785 // Is this an extending load from an f32 to an f64?
11786 static bool isFPExtLoad(SDValue Op) {
11787   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
11788     return LD->getExtensionType() == ISD::EXTLOAD &&
11789       Op.getValueType() == MVT::f64;
11790   return false;
11791 }
11792 
11793 /// Reduces the number of fp-to-int conversion when building a vector.
11794 ///
11795 /// If this vector is built out of floating to integer conversions,
11796 /// transform it to a vector built out of floating point values followed by a
11797 /// single floating to integer conversion of the vector.
11798 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
11799 /// becomes (fptosi (build_vector ($A, $B, ...)))
11800 SDValue PPCTargetLowering::
11801 combineElementTruncationToVectorTruncation(SDNode *N,
11802                                            DAGCombinerInfo &DCI) const {
11803   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11804          "Should be called with a BUILD_VECTOR node");
11805 
11806   SelectionDAG &DAG = DCI.DAG;
11807   SDLoc dl(N);
11808 
11809   SDValue FirstInput = N->getOperand(0);
11810   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
11811          "The input operand must be an fp-to-int conversion.");
11812 
11813   // This combine happens after legalization so the fp_to_[su]i nodes are
11814   // already converted to PPCSISD nodes.
11815   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
11816   if (FirstConversion == PPCISD::FCTIDZ ||
11817       FirstConversion == PPCISD::FCTIDUZ ||
11818       FirstConversion == PPCISD::FCTIWZ ||
11819       FirstConversion == PPCISD::FCTIWUZ) {
11820     bool IsSplat = true;
11821     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
11822       FirstConversion == PPCISD::FCTIWUZ;
11823     EVT SrcVT = FirstInput.getOperand(0).getValueType();
11824     SmallVector<SDValue, 4> Ops;
11825     EVT TargetVT = N->getValueType(0);
11826     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11827       SDValue NextOp = N->getOperand(i);
11828       if (NextOp.getOpcode() != PPCISD::MFVSR)
11829         return SDValue();
11830       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
11831       if (NextConversion != FirstConversion)
11832         return SDValue();
11833       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
11834       // This is not valid if the input was originally double precision. It is
11835       // also not profitable to do unless this is an extending load in which
11836       // case doing this combine will allow us to combine consecutive loads.
11837       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
11838         return SDValue();
11839       if (N->getOperand(i) != FirstInput)
11840         IsSplat = false;
11841     }
11842 
11843     // If this is a splat, we leave it as-is since there will be only a single
11844     // fp-to-int conversion followed by a splat of the integer. This is better
11845     // for 32-bit and smaller ints and neutral for 64-bit ints.
11846     if (IsSplat)
11847       return SDValue();
11848 
11849     // Now that we know we have the right type of node, get its operands
11850     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11851       SDValue In = N->getOperand(i).getOperand(0);
11852       if (Is32Bit) {
11853         // For 32-bit values, we need to add an FP_ROUND node (if we made it
11854         // here, we know that all inputs are extending loads so this is safe).
11855         if (In.isUndef())
11856           Ops.push_back(DAG.getUNDEF(SrcVT));
11857         else {
11858           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11859                                       MVT::f32, In.getOperand(0),
11860                                       DAG.getIntPtrConstant(1, dl));
11861           Ops.push_back(Trunc);
11862         }
11863       } else
11864         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11865     }
11866 
11867     unsigned Opcode;
11868     if (FirstConversion == PPCISD::FCTIDZ ||
11869         FirstConversion == PPCISD::FCTIWZ)
11870       Opcode = ISD::FP_TO_SINT;
11871     else
11872       Opcode = ISD::FP_TO_UINT;
11873 
11874     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11875     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11876     return DAG.getNode(Opcode, dl, TargetVT, BV);
11877   }
11878   return SDValue();
11879 }
11880 
11881 /// Reduce the number of loads when building a vector.
11882 ///
11883 /// Building a vector out of multiple loads can be converted to a load
11884 /// of the vector type if the loads are consecutive. If the loads are
11885 /// consecutive but in descending order, a shuffle is added at the end
11886 /// to reorder the vector.
11887 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11888   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11889          "Should be called with a BUILD_VECTOR node");
11890 
11891   SDLoc dl(N);
11892   bool InputsAreConsecutiveLoads = true;
11893   bool InputsAreReverseConsecutive = true;
11894   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11895   SDValue FirstInput = N->getOperand(0);
11896   bool IsRoundOfExtLoad = false;
11897 
11898   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11899       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11900     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11901     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11902   }
11903   // Not a build vector of (possibly fp_rounded) loads.
11904   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
11905       N->getNumOperands() == 1)
11906     return SDValue();
11907 
11908   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11909     // If any inputs are fp_round(extload), they all must be.
11910     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11911       return SDValue();
11912 
11913     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11914       N->getOperand(i);
11915     if (NextInput.getOpcode() != ISD::LOAD)
11916       return SDValue();
11917 
11918     SDValue PreviousInput =
11919       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11920     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11921     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11922 
11923     // If any inputs are fp_round(extload), they all must be.
11924     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11925       return SDValue();
11926 
11927     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11928       InputsAreConsecutiveLoads = false;
11929     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11930       InputsAreReverseConsecutive = false;
11931 
11932     // Exit early if the loads are neither consecutive nor reverse consecutive.
11933     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11934       return SDValue();
11935   }
11936 
11937   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11938          "The loads cannot be both consecutive and reverse consecutive.");
11939 
11940   SDValue FirstLoadOp =
11941     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11942   SDValue LastLoadOp =
11943     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11944                        N->getOperand(N->getNumOperands()-1);
11945 
11946   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11947   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11948   if (InputsAreConsecutiveLoads) {
11949     assert(LD1 && "Input needs to be a LoadSDNode.");
11950     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11951                        LD1->getBasePtr(), LD1->getPointerInfo(),
11952                        LD1->getAlignment());
11953   }
11954   if (InputsAreReverseConsecutive) {
11955     assert(LDL && "Input needs to be a LoadSDNode.");
11956     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11957                                LDL->getBasePtr(), LDL->getPointerInfo(),
11958                                LDL->getAlignment());
11959     SmallVector<int, 16> Ops;
11960     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11961       Ops.push_back(i);
11962 
11963     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11964                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11965   }
11966   return SDValue();
11967 }
11968 
11969 // This function adds the required vector_shuffle needed to get
11970 // the elements of the vector extract in the correct position
11971 // as specified by the CorrectElems encoding.
11972 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
11973                                       SDValue Input, uint64_t Elems,
11974                                       uint64_t CorrectElems) {
11975   SDLoc dl(N);
11976 
11977   unsigned NumElems = Input.getValueType().getVectorNumElements();
11978   SmallVector<int, 16> ShuffleMask(NumElems, -1);
11979 
11980   // Knowing the element indices being extracted from the original
11981   // vector and the order in which they're being inserted, just put
11982   // them at element indices required for the instruction.
11983   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11984     if (DAG.getDataLayout().isLittleEndian())
11985       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
11986     else
11987       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
11988     CorrectElems = CorrectElems >> 8;
11989     Elems = Elems >> 8;
11990   }
11991 
11992   SDValue Shuffle =
11993       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
11994                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
11995 
11996   EVT Ty = N->getValueType(0);
11997   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
11998   return BV;
11999 }
12000 
12001 // Look for build vector patterns where input operands come from sign
12002 // extended vector_extract elements of specific indices. If the correct indices
12003 // aren't used, add a vector shuffle to fix up the indices and create a new
12004 // PPCISD:SExtVElems node which selects the vector sign extend instructions
12005 // during instruction selection.
12006 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
12007   // This array encodes the indices that the vector sign extend instructions
12008   // extract from when extending from one type to another for both BE and LE.
12009   // The right nibble of each byte corresponds to the LE incides.
12010   // and the left nibble of each byte corresponds to the BE incides.
12011   // For example: 0x3074B8FC  byte->word
12012   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
12013   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
12014   // For example: 0x000070F8  byte->double word
12015   // For LE: the allowed indices are: 0x0,0x8
12016   // For BE: the allowed indices are: 0x7,0xF
12017   uint64_t TargetElems[] = {
12018       0x3074B8FC, // b->w
12019       0x000070F8, // b->d
12020       0x10325476, // h->w
12021       0x00003074, // h->d
12022       0x00001032, // w->d
12023   };
12024 
12025   uint64_t Elems = 0;
12026   int Index;
12027   SDValue Input;
12028 
12029   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
12030     if (!Op)
12031       return false;
12032     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
12033         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
12034       return false;
12035 
12036     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
12037     // of the right width.
12038     SDValue Extract = Op.getOperand(0);
12039     if (Extract.getOpcode() == ISD::ANY_EXTEND)
12040       Extract = Extract.getOperand(0);
12041     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12042       return false;
12043 
12044     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12045     if (!ExtOp)
12046       return false;
12047 
12048     Index = ExtOp->getZExtValue();
12049     if (Input && Input != Extract.getOperand(0))
12050       return false;
12051 
12052     if (!Input)
12053       Input = Extract.getOperand(0);
12054 
12055     Elems = Elems << 8;
12056     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12057     Elems |= Index;
12058 
12059     return true;
12060   };
12061 
12062   // If the build vector operands aren't sign extended vector extracts,
12063   // of the same input vector, then return.
12064   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12065     if (!isSExtOfVecExtract(N->getOperand(i))) {
12066       return SDValue();
12067     }
12068   }
12069 
12070   // If the vector extract indicies are not correct, add the appropriate
12071   // vector_shuffle.
12072   int TgtElemArrayIdx;
12073   int InputSize = Input.getValueType().getScalarSizeInBits();
12074   int OutputSize = N->getValueType(0).getScalarSizeInBits();
12075   if (InputSize + OutputSize == 40)
12076     TgtElemArrayIdx = 0;
12077   else if (InputSize + OutputSize == 72)
12078     TgtElemArrayIdx = 1;
12079   else if (InputSize + OutputSize == 48)
12080     TgtElemArrayIdx = 2;
12081   else if (InputSize + OutputSize == 80)
12082     TgtElemArrayIdx = 3;
12083   else if (InputSize + OutputSize == 96)
12084     TgtElemArrayIdx = 4;
12085   else
12086     return SDValue();
12087 
12088   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12089   CorrectElems = DAG.getDataLayout().isLittleEndian()
12090                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12091                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12092   if (Elems != CorrectElems) {
12093     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12094   }
12095 
12096   // Regular lowering will catch cases where a shuffle is not needed.
12097   return SDValue();
12098 }
12099 
12100 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12101                                                  DAGCombinerInfo &DCI) const {
12102   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12103          "Should be called with a BUILD_VECTOR node");
12104 
12105   SelectionDAG &DAG = DCI.DAG;
12106   SDLoc dl(N);
12107 
12108   if (!Subtarget.hasVSX())
12109     return SDValue();
12110 
12111   // The target independent DAG combiner will leave a build_vector of
12112   // float-to-int conversions intact. We can generate MUCH better code for
12113   // a float-to-int conversion of a vector of floats.
12114   SDValue FirstInput = N->getOperand(0);
12115   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12116     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12117     if (Reduced)
12118       return Reduced;
12119   }
12120 
12121   // If we're building a vector out of consecutive loads, just load that
12122   // vector type.
12123   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12124   if (Reduced)
12125     return Reduced;
12126 
12127   // If we're building a vector out of extended elements from another vector
12128   // we have P9 vector integer extend instructions. The code assumes legal
12129   // input types (i.e. it can't handle things like v4i16) so do not run before
12130   // legalization.
12131   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
12132     Reduced = combineBVOfVecSExt(N, DAG);
12133     if (Reduced)
12134       return Reduced;
12135   }
12136 
12137 
12138   if (N->getValueType(0) != MVT::v2f64)
12139     return SDValue();
12140 
12141   // Looking for:
12142   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12143   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12144       FirstInput.getOpcode() != ISD::UINT_TO_FP)
12145     return SDValue();
12146   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12147       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12148     return SDValue();
12149   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12150     return SDValue();
12151 
12152   SDValue Ext1 = FirstInput.getOperand(0);
12153   SDValue Ext2 = N->getOperand(1).getOperand(0);
12154   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12155      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12156     return SDValue();
12157 
12158   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12159   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12160   if (!Ext1Op || !Ext2Op)
12161     return SDValue();
12162   if (Ext1.getValueType() != MVT::i32 ||
12163       Ext2.getValueType() != MVT::i32)
12164   if (Ext1.getOperand(0) != Ext2.getOperand(0))
12165     return SDValue();
12166 
12167   int FirstElem = Ext1Op->getZExtValue();
12168   int SecondElem = Ext2Op->getZExtValue();
12169   int SubvecIdx;
12170   if (FirstElem == 0 && SecondElem == 1)
12171     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12172   else if (FirstElem == 2 && SecondElem == 3)
12173     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12174   else
12175     return SDValue();
12176 
12177   SDValue SrcVec = Ext1.getOperand(0);
12178   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12179     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12180   return DAG.getNode(NodeType, dl, MVT::v2f64,
12181                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12182 }
12183 
12184 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12185                                               DAGCombinerInfo &DCI) const {
12186   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12187           N->getOpcode() == ISD::UINT_TO_FP) &&
12188          "Need an int -> FP conversion node here");
12189 
12190   if (useSoftFloat() || !Subtarget.has64BitSupport())
12191     return SDValue();
12192 
12193   SelectionDAG &DAG = DCI.DAG;
12194   SDLoc dl(N);
12195   SDValue Op(N, 0);
12196 
12197   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12198   // from the hardware.
12199   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12200     return SDValue();
12201   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12202       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12203     return SDValue();
12204 
12205   SDValue FirstOperand(Op.getOperand(0));
12206   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12207     (FirstOperand.getValueType() == MVT::i8 ||
12208      FirstOperand.getValueType() == MVT::i16);
12209   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12210     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12211     bool DstDouble = Op.getValueType() == MVT::f64;
12212     unsigned ConvOp = Signed ?
12213       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12214       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12215     SDValue WidthConst =
12216       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12217                             dl, false);
12218     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12219     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12220     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12221                                          DAG.getVTList(MVT::f64, MVT::Other),
12222                                          Ops, MVT::i8, LDN->getMemOperand());
12223 
12224     // For signed conversion, we need to sign-extend the value in the VSR
12225     if (Signed) {
12226       SDValue ExtOps[] = { Ld, WidthConst };
12227       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12228       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12229     } else
12230       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12231   }
12232 
12233 
12234   // For i32 intermediate values, unfortunately, the conversion functions
12235   // leave the upper 32 bits of the value are undefined. Within the set of
12236   // scalar instructions, we have no method for zero- or sign-extending the
12237   // value. Thus, we cannot handle i32 intermediate values here.
12238   if (Op.getOperand(0).getValueType() == MVT::i32)
12239     return SDValue();
12240 
12241   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12242          "UINT_TO_FP is supported only with FPCVT");
12243 
12244   // If we have FCFIDS, then use it when converting to single-precision.
12245   // Otherwise, convert to double-precision and then round.
12246   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12247                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12248                                                             : PPCISD::FCFIDS)
12249                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12250                                                             : PPCISD::FCFID);
12251   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12252                   ? MVT::f32
12253                   : MVT::f64;
12254 
12255   // If we're converting from a float, to an int, and back to a float again,
12256   // then we don't need the store/load pair at all.
12257   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12258        Subtarget.hasFPCVT()) ||
12259       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12260     SDValue Src = Op.getOperand(0).getOperand(0);
12261     if (Src.getValueType() == MVT::f32) {
12262       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12263       DCI.AddToWorklist(Src.getNode());
12264     } else if (Src.getValueType() != MVT::f64) {
12265       // Make sure that we don't pick up a ppc_fp128 source value.
12266       return SDValue();
12267     }
12268 
12269     unsigned FCTOp =
12270       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12271                                                         PPCISD::FCTIDUZ;
12272 
12273     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12274     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12275 
12276     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12277       FP = DAG.getNode(ISD::FP_ROUND, dl,
12278                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12279       DCI.AddToWorklist(FP.getNode());
12280     }
12281 
12282     return FP;
12283   }
12284 
12285   return SDValue();
12286 }
12287 
12288 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12289 // builtins) into loads with swaps.
12290 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12291                                               DAGCombinerInfo &DCI) const {
12292   SelectionDAG &DAG = DCI.DAG;
12293   SDLoc dl(N);
12294   SDValue Chain;
12295   SDValue Base;
12296   MachineMemOperand *MMO;
12297 
12298   switch (N->getOpcode()) {
12299   default:
12300     llvm_unreachable("Unexpected opcode for little endian VSX load");
12301   case ISD::LOAD: {
12302     LoadSDNode *LD = cast<LoadSDNode>(N);
12303     Chain = LD->getChain();
12304     Base = LD->getBasePtr();
12305     MMO = LD->getMemOperand();
12306     // If the MMO suggests this isn't a load of a full vector, leave
12307     // things alone.  For a built-in, we have to make the change for
12308     // correctness, so if there is a size problem that will be a bug.
12309     if (MMO->getSize() < 16)
12310       return SDValue();
12311     break;
12312   }
12313   case ISD::INTRINSIC_W_CHAIN: {
12314     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12315     Chain = Intrin->getChain();
12316     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12317     // us what we want. Get operand 2 instead.
12318     Base = Intrin->getOperand(2);
12319     MMO = Intrin->getMemOperand();
12320     break;
12321   }
12322   }
12323 
12324   MVT VecTy = N->getValueType(0).getSimpleVT();
12325 
12326   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12327   // aligned and the type is a vector with elements up to 4 bytes
12328   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12329       && VecTy.getScalarSizeInBits() <= 32 ) {
12330     return SDValue();
12331   }
12332 
12333   SDValue LoadOps[] = { Chain, Base };
12334   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12335                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12336                                          LoadOps, MVT::v2f64, MMO);
12337 
12338   DCI.AddToWorklist(Load.getNode());
12339   Chain = Load.getValue(1);
12340   SDValue Swap = DAG.getNode(
12341       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12342   DCI.AddToWorklist(Swap.getNode());
12343 
12344   // Add a bitcast if the resulting load type doesn't match v2f64.
12345   if (VecTy != MVT::v2f64) {
12346     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12347     DCI.AddToWorklist(N.getNode());
12348     // Package {bitcast value, swap's chain} to match Load's shape.
12349     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12350                        N, Swap.getValue(1));
12351   }
12352 
12353   return Swap;
12354 }
12355 
12356 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12357 // builtins) into stores with swaps.
12358 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12359                                                DAGCombinerInfo &DCI) const {
12360   SelectionDAG &DAG = DCI.DAG;
12361   SDLoc dl(N);
12362   SDValue Chain;
12363   SDValue Base;
12364   unsigned SrcOpnd;
12365   MachineMemOperand *MMO;
12366 
12367   switch (N->getOpcode()) {
12368   default:
12369     llvm_unreachable("Unexpected opcode for little endian VSX store");
12370   case ISD::STORE: {
12371     StoreSDNode *ST = cast<StoreSDNode>(N);
12372     Chain = ST->getChain();
12373     Base = ST->getBasePtr();
12374     MMO = ST->getMemOperand();
12375     SrcOpnd = 1;
12376     // If the MMO suggests this isn't a store of a full vector, leave
12377     // things alone.  For a built-in, we have to make the change for
12378     // correctness, so if there is a size problem that will be a bug.
12379     if (MMO->getSize() < 16)
12380       return SDValue();
12381     break;
12382   }
12383   case ISD::INTRINSIC_VOID: {
12384     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12385     Chain = Intrin->getChain();
12386     // Intrin->getBasePtr() oddly does not get what we want.
12387     Base = Intrin->getOperand(3);
12388     MMO = Intrin->getMemOperand();
12389     SrcOpnd = 2;
12390     break;
12391   }
12392   }
12393 
12394   SDValue Src = N->getOperand(SrcOpnd);
12395   MVT VecTy = Src.getValueType().getSimpleVT();
12396 
12397   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12398   // aligned and the type is a vector with elements up to 4 bytes
12399   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12400       && VecTy.getScalarSizeInBits() <= 32 ) {
12401     return SDValue();
12402   }
12403 
12404   // All stores are done as v2f64 and possible bit cast.
12405   if (VecTy != MVT::v2f64) {
12406     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12407     DCI.AddToWorklist(Src.getNode());
12408   }
12409 
12410   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12411                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12412   DCI.AddToWorklist(Swap.getNode());
12413   Chain = Swap.getValue(1);
12414   SDValue StoreOps[] = { Chain, Swap, Base };
12415   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12416                                           DAG.getVTList(MVT::Other),
12417                                           StoreOps, VecTy, MMO);
12418   DCI.AddToWorklist(Store.getNode());
12419   return Store;
12420 }
12421 
12422 // Handle DAG combine for STORE (FP_TO_INT F).
12423 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
12424                                                DAGCombinerInfo &DCI) const {
12425 
12426   SelectionDAG &DAG = DCI.DAG;
12427   SDLoc dl(N);
12428   unsigned Opcode = N->getOperand(1).getOpcode();
12429 
12430   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
12431          && "Not a FP_TO_INT Instruction!");
12432 
12433   SDValue Val = N->getOperand(1).getOperand(0);
12434   EVT Op1VT = N->getOperand(1).getValueType();
12435   EVT ResVT = Val.getValueType();
12436 
12437   // Floating point types smaller than 32 bits are not legal on Power.
12438   if (ResVT.getScalarSizeInBits() < 32)
12439     return SDValue();
12440 
12441   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
12442   bool ValidTypeForStoreFltAsInt =
12443         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
12444          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
12445 
12446   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
12447       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
12448     return SDValue();
12449 
12450   // Extend f32 values to f64
12451   if (ResVT.getScalarSizeInBits() == 32) {
12452     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12453     DCI.AddToWorklist(Val.getNode());
12454   }
12455 
12456   // Set signed or unsigned conversion opcode.
12457   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
12458                           PPCISD::FP_TO_SINT_IN_VSR :
12459                           PPCISD::FP_TO_UINT_IN_VSR;
12460 
12461   Val = DAG.getNode(ConvOpcode,
12462                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
12463   DCI.AddToWorklist(Val.getNode());
12464 
12465   // Set number of bytes being converted.
12466   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
12467   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
12468                     DAG.getIntPtrConstant(ByteSize, dl, false),
12469                     DAG.getValueType(Op1VT) };
12470 
12471   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
12472           DAG.getVTList(MVT::Other), Ops,
12473           cast<StoreSDNode>(N)->getMemoryVT(),
12474           cast<StoreSDNode>(N)->getMemOperand());
12475 
12476   DCI.AddToWorklist(Val.getNode());
12477   return Val;
12478 }
12479 
12480 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12481                                              DAGCombinerInfo &DCI) const {
12482   SelectionDAG &DAG = DCI.DAG;
12483   SDLoc dl(N);
12484   switch (N->getOpcode()) {
12485   default: break;
12486   case ISD::ADD:
12487     return combineADD(N, DCI);
12488   case ISD::SHL:
12489     return combineSHL(N, DCI);
12490   case ISD::SRA:
12491     return combineSRA(N, DCI);
12492   case ISD::SRL:
12493     return combineSRL(N, DCI);
12494   case PPCISD::SHL:
12495     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12496         return N->getOperand(0);
12497     break;
12498   case PPCISD::SRL:
12499     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12500         return N->getOperand(0);
12501     break;
12502   case PPCISD::SRA:
12503     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12504       if (C->isNullValue() ||   //  0 >>s V -> 0.
12505           C->isAllOnesValue())    // -1 >>s V -> -1.
12506         return N->getOperand(0);
12507     }
12508     break;
12509   case ISD::SIGN_EXTEND:
12510   case ISD::ZERO_EXTEND:
12511   case ISD::ANY_EXTEND:
12512     return DAGCombineExtBoolTrunc(N, DCI);
12513   case ISD::TRUNCATE:
12514   case ISD::SETCC:
12515   case ISD::SELECT_CC:
12516     return DAGCombineTruncBoolExt(N, DCI);
12517   case ISD::SINT_TO_FP:
12518   case ISD::UINT_TO_FP:
12519     return combineFPToIntToFP(N, DCI);
12520   case ISD::STORE: {
12521 
12522     EVT Op1VT = N->getOperand(1).getValueType();
12523     unsigned Opcode = N->getOperand(1).getOpcode();
12524 
12525     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
12526       SDValue Val= combineStoreFPToInt(N, DCI);
12527       if (Val)
12528         return Val;
12529     }
12530 
12531     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12532     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
12533         N->getOperand(1).getNode()->hasOneUse() &&
12534         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
12535          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
12536 
12537       // STBRX can only handle simple types.
12538       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12539       if (mVT.isExtended())
12540         break;
12541 
12542       SDValue BSwapOp = N->getOperand(1).getOperand(0);
12543       // Do an any-extend to 32-bits if this is a half-word input.
12544       if (BSwapOp.getValueType() == MVT::i16)
12545         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12546 
12547       // If the type of BSWAP operand is wider than stored memory width
12548       // it need to be shifted to the right side before STBRX.
12549       if (Op1VT.bitsGT(mVT)) {
12550         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12551         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12552                               DAG.getConstant(Shift, dl, MVT::i32));
12553         // Need to truncate if this is a bswap of i64 stored as i32/i16.
12554         if (Op1VT == MVT::i64)
12555           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12556       }
12557 
12558       SDValue Ops[] = {
12559         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12560       };
12561       return
12562         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12563                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12564                                 cast<StoreSDNode>(N)->getMemOperand());
12565     }
12566 
12567     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
12568     // So it can increase the chance of CSE constant construction.
12569     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
12570         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
12571       // Need to sign-extended to 64-bits to handle negative values.
12572       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
12573       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
12574                                     MemVT.getSizeInBits());
12575       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
12576 
12577       // DAG.getTruncStore() can't be used here because it doesn't accept
12578       // the general (base + offset) addressing mode.
12579       // So we use UpdateNodeOperands and setTruncatingStore instead.
12580       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
12581                              N->getOperand(3));
12582       cast<StoreSDNode>(N)->setTruncatingStore(true);
12583       return SDValue(N, 0);
12584     }
12585 
12586     // For little endian, VSX stores require generating xxswapd/lxvd2x.
12587     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12588     if (Op1VT.isSimple()) {
12589       MVT StoreVT = Op1VT.getSimpleVT();
12590       if (Subtarget.needsSwapsForVSXMemOps() &&
12591           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12592            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12593         return expandVSXStoreForLE(N, DCI);
12594     }
12595     break;
12596   }
12597   case ISD::LOAD: {
12598     LoadSDNode *LD = cast<LoadSDNode>(N);
12599     EVT VT = LD->getValueType(0);
12600 
12601     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12602     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12603     if (VT.isSimple()) {
12604       MVT LoadVT = VT.getSimpleVT();
12605       if (Subtarget.needsSwapsForVSXMemOps() &&
12606           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12607            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12608         return expandVSXLoadForLE(N, DCI);
12609     }
12610 
12611     // We sometimes end up with a 64-bit integer load, from which we extract
12612     // two single-precision floating-point numbers. This happens with
12613     // std::complex<float>, and other similar structures, because of the way we
12614     // canonicalize structure copies. However, if we lack direct moves,
12615     // then the final bitcasts from the extracted integer values to the
12616     // floating-point numbers turn into store/load pairs. Even with direct moves,
12617     // just loading the two floating-point numbers is likely better.
12618     auto ReplaceTwoFloatLoad = [&]() {
12619       if (VT != MVT::i64)
12620         return false;
12621 
12622       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
12623           LD->isVolatile())
12624         return false;
12625 
12626       //  We're looking for a sequence like this:
12627       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
12628       //      t16: i64 = srl t13, Constant:i32<32>
12629       //    t17: i32 = truncate t16
12630       //  t18: f32 = bitcast t17
12631       //    t19: i32 = truncate t13
12632       //  t20: f32 = bitcast t19
12633 
12634       if (!LD->hasNUsesOfValue(2, 0))
12635         return false;
12636 
12637       auto UI = LD->use_begin();
12638       while (UI.getUse().getResNo() != 0) ++UI;
12639       SDNode *Trunc = *UI++;
12640       while (UI.getUse().getResNo() != 0) ++UI;
12641       SDNode *RightShift = *UI;
12642       if (Trunc->getOpcode() != ISD::TRUNCATE)
12643         std::swap(Trunc, RightShift);
12644 
12645       if (Trunc->getOpcode() != ISD::TRUNCATE ||
12646           Trunc->getValueType(0) != MVT::i32 ||
12647           !Trunc->hasOneUse())
12648         return false;
12649       if (RightShift->getOpcode() != ISD::SRL ||
12650           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
12651           RightShift->getConstantOperandVal(1) != 32 ||
12652           !RightShift->hasOneUse())
12653         return false;
12654 
12655       SDNode *Trunc2 = *RightShift->use_begin();
12656       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
12657           Trunc2->getValueType(0) != MVT::i32 ||
12658           !Trunc2->hasOneUse())
12659         return false;
12660 
12661       SDNode *Bitcast = *Trunc->use_begin();
12662       SDNode *Bitcast2 = *Trunc2->use_begin();
12663 
12664       if (Bitcast->getOpcode() != ISD::BITCAST ||
12665           Bitcast->getValueType(0) != MVT::f32)
12666         return false;
12667       if (Bitcast2->getOpcode() != ISD::BITCAST ||
12668           Bitcast2->getValueType(0) != MVT::f32)
12669         return false;
12670 
12671       if (Subtarget.isLittleEndian())
12672         std::swap(Bitcast, Bitcast2);
12673 
12674       // Bitcast has the second float (in memory-layout order) and Bitcast2
12675       // has the first one.
12676 
12677       SDValue BasePtr = LD->getBasePtr();
12678       if (LD->isIndexed()) {
12679         assert(LD->getAddressingMode() == ISD::PRE_INC &&
12680                "Non-pre-inc AM on PPC?");
12681         BasePtr =
12682           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12683                       LD->getOffset());
12684       }
12685 
12686       auto MMOFlags =
12687           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
12688       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
12689                                       LD->getPointerInfo(), LD->getAlignment(),
12690                                       MMOFlags, LD->getAAInfo());
12691       SDValue AddPtr =
12692         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
12693                     BasePtr, DAG.getIntPtrConstant(4, dl));
12694       SDValue FloatLoad2 = DAG.getLoad(
12695           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
12696           LD->getPointerInfo().getWithOffset(4),
12697           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
12698 
12699       if (LD->isIndexed()) {
12700         // Note that DAGCombine should re-form any pre-increment load(s) from
12701         // what is produced here if that makes sense.
12702         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
12703       }
12704 
12705       DCI.CombineTo(Bitcast2, FloatLoad);
12706       DCI.CombineTo(Bitcast, FloatLoad2);
12707 
12708       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
12709                                     SDValue(FloatLoad2.getNode(), 1));
12710       return true;
12711     };
12712 
12713     if (ReplaceTwoFloatLoad())
12714       return SDValue(N, 0);
12715 
12716     EVT MemVT = LD->getMemoryVT();
12717     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
12718     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
12719     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
12720     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
12721     if (LD->isUnindexed() && VT.isVector() &&
12722         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
12723           // P8 and later hardware should just use LOAD.
12724           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
12725                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
12726          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
12727           LD->getAlignment() >= ScalarABIAlignment)) &&
12728         LD->getAlignment() < ABIAlignment) {
12729       // This is a type-legal unaligned Altivec or QPX load.
12730       SDValue Chain = LD->getChain();
12731       SDValue Ptr = LD->getBasePtr();
12732       bool isLittleEndian = Subtarget.isLittleEndian();
12733 
12734       // This implements the loading of unaligned vectors as described in
12735       // the venerable Apple Velocity Engine overview. Specifically:
12736       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
12737       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
12738       //
12739       // The general idea is to expand a sequence of one or more unaligned
12740       // loads into an alignment-based permutation-control instruction (lvsl
12741       // or lvsr), a series of regular vector loads (which always truncate
12742       // their input address to an aligned address), and a series of
12743       // permutations.  The results of these permutations are the requested
12744       // loaded values.  The trick is that the last "extra" load is not taken
12745       // from the address you might suspect (sizeof(vector) bytes after the
12746       // last requested load), but rather sizeof(vector) - 1 bytes after the
12747       // last requested vector. The point of this is to avoid a page fault if
12748       // the base address happened to be aligned. This works because if the
12749       // base address is aligned, then adding less than a full vector length
12750       // will cause the last vector in the sequence to be (re)loaded.
12751       // Otherwise, the next vector will be fetched as you might suspect was
12752       // necessary.
12753 
12754       // We might be able to reuse the permutation generation from
12755       // a different base address offset from this one by an aligned amount.
12756       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
12757       // optimization later.
12758       Intrinsic::ID Intr, IntrLD, IntrPerm;
12759       MVT PermCntlTy, PermTy, LDTy;
12760       if (Subtarget.hasAltivec()) {
12761         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
12762                                  Intrinsic::ppc_altivec_lvsl;
12763         IntrLD = Intrinsic::ppc_altivec_lvx;
12764         IntrPerm = Intrinsic::ppc_altivec_vperm;
12765         PermCntlTy = MVT::v16i8;
12766         PermTy = MVT::v4i32;
12767         LDTy = MVT::v4i32;
12768       } else {
12769         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
12770                                        Intrinsic::ppc_qpx_qvlpcls;
12771         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
12772                                        Intrinsic::ppc_qpx_qvlfs;
12773         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
12774         PermCntlTy = MVT::v4f64;
12775         PermTy = MVT::v4f64;
12776         LDTy = MemVT.getSimpleVT();
12777       }
12778 
12779       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
12780 
12781       // Create the new MMO for the new base load. It is like the original MMO,
12782       // but represents an area in memory almost twice the vector size centered
12783       // on the original address. If the address is unaligned, we might start
12784       // reading up to (sizeof(vector)-1) bytes below the address of the
12785       // original unaligned load.
12786       MachineFunction &MF = DAG.getMachineFunction();
12787       MachineMemOperand *BaseMMO =
12788         MF.getMachineMemOperand(LD->getMemOperand(),
12789                                 -(long)MemVT.getStoreSize()+1,
12790                                 2*MemVT.getStoreSize()-1);
12791 
12792       // Create the new base load.
12793       SDValue LDXIntID =
12794           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
12795       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
12796       SDValue BaseLoad =
12797         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12798                                 DAG.getVTList(PermTy, MVT::Other),
12799                                 BaseLoadOps, LDTy, BaseMMO);
12800 
12801       // Note that the value of IncOffset (which is provided to the next
12802       // load's pointer info offset value, and thus used to calculate the
12803       // alignment), and the value of IncValue (which is actually used to
12804       // increment the pointer value) are different! This is because we
12805       // require the next load to appear to be aligned, even though it
12806       // is actually offset from the base pointer by a lesser amount.
12807       int IncOffset = VT.getSizeInBits() / 8;
12808       int IncValue = IncOffset;
12809 
12810       // Walk (both up and down) the chain looking for another load at the real
12811       // (aligned) offset (the alignment of the other load does not matter in
12812       // this case). If found, then do not use the offset reduction trick, as
12813       // that will prevent the loads from being later combined (as they would
12814       // otherwise be duplicates).
12815       if (!findConsecutiveLoad(LD, DAG))
12816         --IncValue;
12817 
12818       SDValue Increment =
12819           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
12820       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12821 
12822       MachineMemOperand *ExtraMMO =
12823         MF.getMachineMemOperand(LD->getMemOperand(),
12824                                 1, 2*MemVT.getStoreSize()-1);
12825       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
12826       SDValue ExtraLoad =
12827         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12828                                 DAG.getVTList(PermTy, MVT::Other),
12829                                 ExtraLoadOps, LDTy, ExtraMMO);
12830 
12831       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
12832         BaseLoad.getValue(1), ExtraLoad.getValue(1));
12833 
12834       // Because vperm has a big-endian bias, we must reverse the order
12835       // of the input vectors and complement the permute control vector
12836       // when generating little endian code.  We have already handled the
12837       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
12838       // and ExtraLoad here.
12839       SDValue Perm;
12840       if (isLittleEndian)
12841         Perm = BuildIntrinsicOp(IntrPerm,
12842                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
12843       else
12844         Perm = BuildIntrinsicOp(IntrPerm,
12845                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
12846 
12847       if (VT != PermTy)
12848         Perm = Subtarget.hasAltivec() ?
12849                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
12850                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
12851                                DAG.getTargetConstant(1, dl, MVT::i64));
12852                                // second argument is 1 because this rounding
12853                                // is always exact.
12854 
12855       // The output of the permutation is our loaded result, the TokenFactor is
12856       // our new chain.
12857       DCI.CombineTo(N, Perm, TF);
12858       return SDValue(N, 0);
12859     }
12860     }
12861     break;
12862     case ISD::INTRINSIC_WO_CHAIN: {
12863       bool isLittleEndian = Subtarget.isLittleEndian();
12864       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12865       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
12866                                            : Intrinsic::ppc_altivec_lvsl);
12867       if ((IID == Intr ||
12868            IID == Intrinsic::ppc_qpx_qvlpcld  ||
12869            IID == Intrinsic::ppc_qpx_qvlpcls) &&
12870         N->getOperand(1)->getOpcode() == ISD::ADD) {
12871         SDValue Add = N->getOperand(1);
12872 
12873         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
12874                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
12875 
12876         if (DAG.MaskedValueIsZero(Add->getOperand(1),
12877                                   APInt::getAllOnesValue(Bits /* alignment */)
12878                                       .zext(Add.getScalarValueSizeInBits()))) {
12879           SDNode *BasePtr = Add->getOperand(0).getNode();
12880           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12881                                     UE = BasePtr->use_end();
12882                UI != UE; ++UI) {
12883             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12884                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
12885               // We've found another LVSL/LVSR, and this address is an aligned
12886               // multiple of that one. The results will be the same, so use the
12887               // one we've just found instead.
12888 
12889               return SDValue(*UI, 0);
12890             }
12891           }
12892         }
12893 
12894         if (isa<ConstantSDNode>(Add->getOperand(1))) {
12895           SDNode *BasePtr = Add->getOperand(0).getNode();
12896           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12897                UE = BasePtr->use_end(); UI != UE; ++UI) {
12898             if (UI->getOpcode() == ISD::ADD &&
12899                 isa<ConstantSDNode>(UI->getOperand(1)) &&
12900                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
12901                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
12902                 (1ULL << Bits) == 0) {
12903               SDNode *OtherAdd = *UI;
12904               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
12905                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
12906                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12907                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
12908                   return SDValue(*VI, 0);
12909                 }
12910               }
12911             }
12912           }
12913         }
12914       }
12915     }
12916 
12917     break;
12918   case ISD::INTRINSIC_W_CHAIN:
12919     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12920     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12921     if (Subtarget.needsSwapsForVSXMemOps()) {
12922       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12923       default:
12924         break;
12925       case Intrinsic::ppc_vsx_lxvw4x:
12926       case Intrinsic::ppc_vsx_lxvd2x:
12927         return expandVSXLoadForLE(N, DCI);
12928       }
12929     }
12930     break;
12931   case ISD::INTRINSIC_VOID:
12932     // For little endian, VSX stores require generating xxswapd/stxvd2x.
12933     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12934     if (Subtarget.needsSwapsForVSXMemOps()) {
12935       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12936       default:
12937         break;
12938       case Intrinsic::ppc_vsx_stxvw4x:
12939       case Intrinsic::ppc_vsx_stxvd2x:
12940         return expandVSXStoreForLE(N, DCI);
12941       }
12942     }
12943     break;
12944   case ISD::BSWAP:
12945     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
12946     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
12947         N->getOperand(0).hasOneUse() &&
12948         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
12949          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12950           N->getValueType(0) == MVT::i64))) {
12951       SDValue Load = N->getOperand(0);
12952       LoadSDNode *LD = cast<LoadSDNode>(Load);
12953       // Create the byte-swapping load.
12954       SDValue Ops[] = {
12955         LD->getChain(),    // Chain
12956         LD->getBasePtr(),  // Ptr
12957         DAG.getValueType(N->getValueType(0)) // VT
12958       };
12959       SDValue BSLoad =
12960         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
12961                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
12962                                               MVT::i64 : MVT::i32, MVT::Other),
12963                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
12964 
12965       // If this is an i16 load, insert the truncate.
12966       SDValue ResVal = BSLoad;
12967       if (N->getValueType(0) == MVT::i16)
12968         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
12969 
12970       // First, combine the bswap away.  This makes the value produced by the
12971       // load dead.
12972       DCI.CombineTo(N, ResVal);
12973 
12974       // Next, combine the load away, we give it a bogus result value but a real
12975       // chain result.  The result value is dead because the bswap is dead.
12976       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
12977 
12978       // Return N so it doesn't get rechecked!
12979       return SDValue(N, 0);
12980     }
12981     break;
12982   case PPCISD::VCMP:
12983     // If a VCMPo node already exists with exactly the same operands as this
12984     // node, use its result instead of this node (VCMPo computes both a CR6 and
12985     // a normal output).
12986     //
12987     if (!N->getOperand(0).hasOneUse() &&
12988         !N->getOperand(1).hasOneUse() &&
12989         !N->getOperand(2).hasOneUse()) {
12990 
12991       // Scan all of the users of the LHS, looking for VCMPo's that match.
12992       SDNode *VCMPoNode = nullptr;
12993 
12994       SDNode *LHSN = N->getOperand(0).getNode();
12995       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
12996            UI != E; ++UI)
12997         if (UI->getOpcode() == PPCISD::VCMPo &&
12998             UI->getOperand(1) == N->getOperand(1) &&
12999             UI->getOperand(2) == N->getOperand(2) &&
13000             UI->getOperand(0) == N->getOperand(0)) {
13001           VCMPoNode = *UI;
13002           break;
13003         }
13004 
13005       // If there is no VCMPo node, or if the flag value has a single use, don't
13006       // transform this.
13007       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
13008         break;
13009 
13010       // Look at the (necessarily single) use of the flag value.  If it has a
13011       // chain, this transformation is more complex.  Note that multiple things
13012       // could use the value result, which we should ignore.
13013       SDNode *FlagUser = nullptr;
13014       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
13015            FlagUser == nullptr; ++UI) {
13016         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
13017         SDNode *User = *UI;
13018         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
13019           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
13020             FlagUser = User;
13021             break;
13022           }
13023         }
13024       }
13025 
13026       // If the user is a MFOCRF instruction, we know this is safe.
13027       // Otherwise we give up for right now.
13028       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
13029         return SDValue(VCMPoNode, 0);
13030     }
13031     break;
13032   case ISD::BRCOND: {
13033     SDValue Cond = N->getOperand(1);
13034     SDValue Target = N->getOperand(2);
13035 
13036     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13037         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
13038           Intrinsic::ppc_is_decremented_ctr_nonzero) {
13039 
13040       // We now need to make the intrinsic dead (it cannot be instruction
13041       // selected).
13042       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
13043       assert(Cond.getNode()->hasOneUse() &&
13044              "Counter decrement has more than one use");
13045 
13046       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
13047                          N->getOperand(0), Target);
13048     }
13049   }
13050   break;
13051   case ISD::BR_CC: {
13052     // If this is a branch on an altivec predicate comparison, lower this so
13053     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
13054     // lowering is done pre-legalize, because the legalizer lowers the predicate
13055     // compare down to code that is difficult to reassemble.
13056     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13057     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13058 
13059     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13060     // value. If so, pass-through the AND to get to the intrinsic.
13061     if (LHS.getOpcode() == ISD::AND &&
13062         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13063         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13064           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13065         isa<ConstantSDNode>(LHS.getOperand(1)) &&
13066         !isNullConstant(LHS.getOperand(1)))
13067       LHS = LHS.getOperand(0);
13068 
13069     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13070         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13071           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13072         isa<ConstantSDNode>(RHS)) {
13073       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13074              "Counter decrement comparison is not EQ or NE");
13075 
13076       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13077       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13078                     (CC == ISD::SETNE && !Val);
13079 
13080       // We now need to make the intrinsic dead (it cannot be instruction
13081       // selected).
13082       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13083       assert(LHS.getNode()->hasOneUse() &&
13084              "Counter decrement has more than one use");
13085 
13086       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13087                          N->getOperand(0), N->getOperand(4));
13088     }
13089 
13090     int CompareOpc;
13091     bool isDot;
13092 
13093     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13094         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13095         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13096       assert(isDot && "Can't compare against a vector result!");
13097 
13098       // If this is a comparison against something other than 0/1, then we know
13099       // that the condition is never/always true.
13100       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13101       if (Val != 0 && Val != 1) {
13102         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
13103           return N->getOperand(0);
13104         // Always !=, turn it into an unconditional branch.
13105         return DAG.getNode(ISD::BR, dl, MVT::Other,
13106                            N->getOperand(0), N->getOperand(4));
13107       }
13108 
13109       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13110 
13111       // Create the PPCISD altivec 'dot' comparison node.
13112       SDValue Ops[] = {
13113         LHS.getOperand(2),  // LHS of compare
13114         LHS.getOperand(3),  // RHS of compare
13115         DAG.getConstant(CompareOpc, dl, MVT::i32)
13116       };
13117       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
13118       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
13119 
13120       // Unpack the result based on how the target uses it.
13121       PPC::Predicate CompOpc;
13122       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
13123       default:  // Can't happen, don't crash on invalid number though.
13124       case 0:   // Branch on the value of the EQ bit of CR6.
13125         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
13126         break;
13127       case 1:   // Branch on the inverted value of the EQ bit of CR6.
13128         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
13129         break;
13130       case 2:   // Branch on the value of the LT bit of CR6.
13131         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
13132         break;
13133       case 3:   // Branch on the inverted value of the LT bit of CR6.
13134         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
13135         break;
13136       }
13137 
13138       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
13139                          DAG.getConstant(CompOpc, dl, MVT::i32),
13140                          DAG.getRegister(PPC::CR6, MVT::i32),
13141                          N->getOperand(4), CompNode.getValue(1));
13142     }
13143     break;
13144   }
13145   case ISD::BUILD_VECTOR:
13146     return DAGCombineBuildVector(N, DCI);
13147   }
13148 
13149   return SDValue();
13150 }
13151 
13152 SDValue
13153 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13154                                  SelectionDAG &DAG,
13155                                  SmallVectorImpl<SDNode *> &Created) const {
13156   // fold (sdiv X, pow2)
13157   EVT VT = N->getValueType(0);
13158   if (VT == MVT::i64 && !Subtarget.isPPC64())
13159     return SDValue();
13160   if ((VT != MVT::i32 && VT != MVT::i64) ||
13161       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
13162     return SDValue();
13163 
13164   SDLoc DL(N);
13165   SDValue N0 = N->getOperand(0);
13166 
13167   bool IsNegPow2 = (-Divisor).isPowerOf2();
13168   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
13169   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
13170 
13171   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
13172   Created.push_back(Op.getNode());
13173 
13174   if (IsNegPow2) {
13175     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13176     Created.push_back(Op.getNode());
13177   }
13178 
13179   return Op;
13180 }
13181 
13182 //===----------------------------------------------------------------------===//
13183 // Inline Assembly Support
13184 //===----------------------------------------------------------------------===//
13185 
13186 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13187                                                       KnownBits &Known,
13188                                                       const APInt &DemandedElts,
13189                                                       const SelectionDAG &DAG,
13190                                                       unsigned Depth) const {
13191   Known.resetAll();
13192   switch (Op.getOpcode()) {
13193   default: break;
13194   case PPCISD::LBRX: {
13195     // lhbrx is known to have the top bits cleared out.
13196     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13197       Known.Zero = 0xFFFF0000;
13198     break;
13199   }
13200   case ISD::INTRINSIC_WO_CHAIN: {
13201     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13202     default: break;
13203     case Intrinsic::ppc_altivec_vcmpbfp_p:
13204     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13205     case Intrinsic::ppc_altivec_vcmpequb_p:
13206     case Intrinsic::ppc_altivec_vcmpequh_p:
13207     case Intrinsic::ppc_altivec_vcmpequw_p:
13208     case Intrinsic::ppc_altivec_vcmpequd_p:
13209     case Intrinsic::ppc_altivec_vcmpgefp_p:
13210     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13211     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13212     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13213     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13214     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13215     case Intrinsic::ppc_altivec_vcmpgtub_p:
13216     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13217     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13218     case Intrinsic::ppc_altivec_vcmpgtud_p:
13219       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13220       break;
13221     }
13222   }
13223   }
13224 }
13225 
13226 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13227   switch (Subtarget.getDarwinDirective()) {
13228   default: break;
13229   case PPC::DIR_970:
13230   case PPC::DIR_PWR4:
13231   case PPC::DIR_PWR5:
13232   case PPC::DIR_PWR5X:
13233   case PPC::DIR_PWR6:
13234   case PPC::DIR_PWR6X:
13235   case PPC::DIR_PWR7:
13236   case PPC::DIR_PWR8:
13237   case PPC::DIR_PWR9: {
13238     if (!ML)
13239       break;
13240 
13241     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13242 
13243     // For small loops (between 5 and 8 instructions), align to a 32-byte
13244     // boundary so that the entire loop fits in one instruction-cache line.
13245     uint64_t LoopSize = 0;
13246     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13247       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13248         LoopSize += TII->getInstSizeInBytes(*J);
13249         if (LoopSize > 32)
13250           break;
13251       }
13252 
13253     if (LoopSize > 16 && LoopSize <= 32)
13254       return 5;
13255 
13256     break;
13257   }
13258   }
13259 
13260   return TargetLowering::getPrefLoopAlignment(ML);
13261 }
13262 
13263 /// getConstraintType - Given a constraint, return the type of
13264 /// constraint it is for this target.
13265 PPCTargetLowering::ConstraintType
13266 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13267   if (Constraint.size() == 1) {
13268     switch (Constraint[0]) {
13269     default: break;
13270     case 'b':
13271     case 'r':
13272     case 'f':
13273     case 'd':
13274     case 'v':
13275     case 'y':
13276       return C_RegisterClass;
13277     case 'Z':
13278       // FIXME: While Z does indicate a memory constraint, it specifically
13279       // indicates an r+r address (used in conjunction with the 'y' modifier
13280       // in the replacement string). Currently, we're forcing the base
13281       // register to be r0 in the asm printer (which is interpreted as zero)
13282       // and forming the complete address in the second register. This is
13283       // suboptimal.
13284       return C_Memory;
13285     }
13286   } else if (Constraint == "wc") { // individual CR bits.
13287     return C_RegisterClass;
13288   } else if (Constraint == "wa" || Constraint == "wd" ||
13289              Constraint == "wf" || Constraint == "ws") {
13290     return C_RegisterClass; // VSX registers.
13291   }
13292   return TargetLowering::getConstraintType(Constraint);
13293 }
13294 
13295 /// Examine constraint type and operand type and determine a weight value.
13296 /// This object must already have been set up with the operand type
13297 /// and the current alternative constraint selected.
13298 TargetLowering::ConstraintWeight
13299 PPCTargetLowering::getSingleConstraintMatchWeight(
13300     AsmOperandInfo &info, const char *constraint) const {
13301   ConstraintWeight weight = CW_Invalid;
13302   Value *CallOperandVal = info.CallOperandVal;
13303     // If we don't have a value, we can't do a match,
13304     // but allow it at the lowest weight.
13305   if (!CallOperandVal)
13306     return CW_Default;
13307   Type *type = CallOperandVal->getType();
13308 
13309   // Look at the constraint type.
13310   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13311     return CW_Register; // an individual CR bit.
13312   else if ((StringRef(constraint) == "wa" ||
13313             StringRef(constraint) == "wd" ||
13314             StringRef(constraint) == "wf") &&
13315            type->isVectorTy())
13316     return CW_Register;
13317   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13318     return CW_Register;
13319 
13320   switch (*constraint) {
13321   default:
13322     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13323     break;
13324   case 'b':
13325     if (type->isIntegerTy())
13326       weight = CW_Register;
13327     break;
13328   case 'f':
13329     if (type->isFloatTy())
13330       weight = CW_Register;
13331     break;
13332   case 'd':
13333     if (type->isDoubleTy())
13334       weight = CW_Register;
13335     break;
13336   case 'v':
13337     if (type->isVectorTy())
13338       weight = CW_Register;
13339     break;
13340   case 'y':
13341     weight = CW_Register;
13342     break;
13343   case 'Z':
13344     weight = CW_Memory;
13345     break;
13346   }
13347   return weight;
13348 }
13349 
13350 std::pair<unsigned, const TargetRegisterClass *>
13351 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13352                                                 StringRef Constraint,
13353                                                 MVT VT) const {
13354   if (Constraint.size() == 1) {
13355     // GCC RS6000 Constraint Letters
13356     switch (Constraint[0]) {
13357     case 'b':   // R1-R31
13358       if (VT == MVT::i64 && Subtarget.isPPC64())
13359         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13360       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13361     case 'r':   // R0-R31
13362       if (VT == MVT::i64 && Subtarget.isPPC64())
13363         return std::make_pair(0U, &PPC::G8RCRegClass);
13364       return std::make_pair(0U, &PPC::GPRCRegClass);
13365     // 'd' and 'f' constraints are both defined to be "the floating point
13366     // registers", where one is for 32-bit and the other for 64-bit. We don't
13367     // really care overly much here so just give them all the same reg classes.
13368     case 'd':
13369     case 'f':
13370       if (Subtarget.hasSPE()) {
13371         if (VT == MVT::f32 || VT == MVT::i32)
13372           return std::make_pair(0U, &PPC::SPE4RCRegClass);
13373         if (VT == MVT::f64 || VT == MVT::i64)
13374           return std::make_pair(0U, &PPC::SPERCRegClass);
13375       } else {
13376         if (VT == MVT::f32 || VT == MVT::i32)
13377           return std::make_pair(0U, &PPC::F4RCRegClass);
13378         if (VT == MVT::f64 || VT == MVT::i64)
13379           return std::make_pair(0U, &PPC::F8RCRegClass);
13380         if (VT == MVT::v4f64 && Subtarget.hasQPX())
13381           return std::make_pair(0U, &PPC::QFRCRegClass);
13382         if (VT == MVT::v4f32 && Subtarget.hasQPX())
13383           return std::make_pair(0U, &PPC::QSRCRegClass);
13384       }
13385       break;
13386     case 'v':
13387       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13388         return std::make_pair(0U, &PPC::QFRCRegClass);
13389       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13390         return std::make_pair(0U, &PPC::QSRCRegClass);
13391       if (Subtarget.hasAltivec())
13392         return std::make_pair(0U, &PPC::VRRCRegClass);
13393       break;
13394     case 'y':   // crrc
13395       return std::make_pair(0U, &PPC::CRRCRegClass);
13396     }
13397   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13398     // An individual CR bit.
13399     return std::make_pair(0U, &PPC::CRBITRCRegClass);
13400   } else if ((Constraint == "wa" || Constraint == "wd" ||
13401              Constraint == "wf") && Subtarget.hasVSX()) {
13402     return std::make_pair(0U, &PPC::VSRCRegClass);
13403   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13404     if (VT == MVT::f32 && Subtarget.hasP8Vector())
13405       return std::make_pair(0U, &PPC::VSSRCRegClass);
13406     else
13407       return std::make_pair(0U, &PPC::VSFRCRegClass);
13408   }
13409 
13410   std::pair<unsigned, const TargetRegisterClass *> R =
13411       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13412 
13413   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13414   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13415   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13416   // register.
13417   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13418   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13419   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13420       PPC::GPRCRegClass.contains(R.first))
13421     return std::make_pair(TRI->getMatchingSuperReg(R.first,
13422                             PPC::sub_32, &PPC::G8RCRegClass),
13423                           &PPC::G8RCRegClass);
13424 
13425   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13426   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13427     R.first = PPC::CR0;
13428     R.second = &PPC::CRRCRegClass;
13429   }
13430 
13431   return R;
13432 }
13433 
13434 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13435 /// vector.  If it is invalid, don't add anything to Ops.
13436 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13437                                                      std::string &Constraint,
13438                                                      std::vector<SDValue>&Ops,
13439                                                      SelectionDAG &DAG) const {
13440   SDValue Result;
13441 
13442   // Only support length 1 constraints.
13443   if (Constraint.length() > 1) return;
13444 
13445   char Letter = Constraint[0];
13446   switch (Letter) {
13447   default: break;
13448   case 'I':
13449   case 'J':
13450   case 'K':
13451   case 'L':
13452   case 'M':
13453   case 'N':
13454   case 'O':
13455   case 'P': {
13456     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13457     if (!CST) return; // Must be an immediate to match.
13458     SDLoc dl(Op);
13459     int64_t Value = CST->getSExtValue();
13460     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13461                          // numbers are printed as such.
13462     switch (Letter) {
13463     default: llvm_unreachable("Unknown constraint letter!");
13464     case 'I':  // "I" is a signed 16-bit constant.
13465       if (isInt<16>(Value))
13466         Result = DAG.getTargetConstant(Value, dl, TCVT);
13467       break;
13468     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
13469       if (isShiftedUInt<16, 16>(Value))
13470         Result = DAG.getTargetConstant(Value, dl, TCVT);
13471       break;
13472     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
13473       if (isShiftedInt<16, 16>(Value))
13474         Result = DAG.getTargetConstant(Value, dl, TCVT);
13475       break;
13476     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
13477       if (isUInt<16>(Value))
13478         Result = DAG.getTargetConstant(Value, dl, TCVT);
13479       break;
13480     case 'M':  // "M" is a constant that is greater than 31.
13481       if (Value > 31)
13482         Result = DAG.getTargetConstant(Value, dl, TCVT);
13483       break;
13484     case 'N':  // "N" is a positive constant that is an exact power of two.
13485       if (Value > 0 && isPowerOf2_64(Value))
13486         Result = DAG.getTargetConstant(Value, dl, TCVT);
13487       break;
13488     case 'O':  // "O" is the constant zero.
13489       if (Value == 0)
13490         Result = DAG.getTargetConstant(Value, dl, TCVT);
13491       break;
13492     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
13493       if (isInt<16>(-Value))
13494         Result = DAG.getTargetConstant(Value, dl, TCVT);
13495       break;
13496     }
13497     break;
13498   }
13499   }
13500 
13501   if (Result.getNode()) {
13502     Ops.push_back(Result);
13503     return;
13504   }
13505 
13506   // Handle standard constraint letters.
13507   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13508 }
13509 
13510 // isLegalAddressingMode - Return true if the addressing mode represented
13511 // by AM is legal for this target, for a load/store of the specified type.
13512 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13513                                               const AddrMode &AM, Type *Ty,
13514                                               unsigned AS, Instruction *I) const {
13515   // PPC does not allow r+i addressing modes for vectors!
13516   if (Ty->isVectorTy() && AM.BaseOffs != 0)
13517     return false;
13518 
13519   // PPC allows a sign-extended 16-bit immediate field.
13520   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13521     return false;
13522 
13523   // No global is ever allowed as a base.
13524   if (AM.BaseGV)
13525     return false;
13526 
13527   // PPC only support r+r,
13528   switch (AM.Scale) {
13529   case 0:  // "r+i" or just "i", depending on HasBaseReg.
13530     break;
13531   case 1:
13532     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
13533       return false;
13534     // Otherwise we have r+r or r+i.
13535     break;
13536   case 2:
13537     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
13538       return false;
13539     // Allow 2*r as r+r.
13540     break;
13541   default:
13542     // No other scales are supported.
13543     return false;
13544   }
13545 
13546   return true;
13547 }
13548 
13549 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13550                                            SelectionDAG &DAG) const {
13551   MachineFunction &MF = DAG.getMachineFunction();
13552   MachineFrameInfo &MFI = MF.getFrameInfo();
13553   MFI.setReturnAddressIsTaken(true);
13554 
13555   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13556     return SDValue();
13557 
13558   SDLoc dl(Op);
13559   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13560 
13561   // Make sure the function does not optimize away the store of the RA to
13562   // the stack.
13563   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13564   FuncInfo->setLRStoreRequired();
13565   bool isPPC64 = Subtarget.isPPC64();
13566   auto PtrVT = getPointerTy(MF.getDataLayout());
13567 
13568   if (Depth > 0) {
13569     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13570     SDValue Offset =
13571         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13572                         isPPC64 ? MVT::i64 : MVT::i32);
13573     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13574                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13575                        MachinePointerInfo());
13576   }
13577 
13578   // Just load the return address off the stack.
13579   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
13580   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
13581                      MachinePointerInfo());
13582 }
13583 
13584 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
13585                                           SelectionDAG &DAG) const {
13586   SDLoc dl(Op);
13587   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13588 
13589   MachineFunction &MF = DAG.getMachineFunction();
13590   MachineFrameInfo &MFI = MF.getFrameInfo();
13591   MFI.setFrameAddressIsTaken(true);
13592 
13593   EVT PtrVT = getPointerTy(MF.getDataLayout());
13594   bool isPPC64 = PtrVT == MVT::i64;
13595 
13596   // Naked functions never have a frame pointer, and so we use r1. For all
13597   // other functions, this decision must be delayed until during PEI.
13598   unsigned FrameReg;
13599   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
13600     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
13601   else
13602     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
13603 
13604   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
13605                                          PtrVT);
13606   while (Depth--)
13607     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
13608                             FrameAddr, MachinePointerInfo());
13609   return FrameAddr;
13610 }
13611 
13612 // FIXME? Maybe this could be a TableGen attribute on some registers and
13613 // this table could be generated automatically from RegInfo.
13614 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
13615                                               SelectionDAG &DAG) const {
13616   bool isPPC64 = Subtarget.isPPC64();
13617   bool isDarwinABI = Subtarget.isDarwinABI();
13618 
13619   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
13620       (!isPPC64 && VT != MVT::i32))
13621     report_fatal_error("Invalid register global variable type");
13622 
13623   bool is64Bit = isPPC64 && VT == MVT::i64;
13624   unsigned Reg = StringSwitch<unsigned>(RegName)
13625                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
13626                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
13627                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
13628                                   (is64Bit ? PPC::X13 : PPC::R13))
13629                    .Default(0);
13630 
13631   if (Reg)
13632     return Reg;
13633   report_fatal_error("Invalid register name global variable");
13634 }
13635 
13636 bool
13637 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13638   // The PowerPC target isn't yet aware of offsets.
13639   return false;
13640 }
13641 
13642 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13643                                            const CallInst &I,
13644                                            MachineFunction &MF,
13645                                            unsigned Intrinsic) const {
13646   switch (Intrinsic) {
13647   case Intrinsic::ppc_qpx_qvlfd:
13648   case Intrinsic::ppc_qpx_qvlfs:
13649   case Intrinsic::ppc_qpx_qvlfcd:
13650   case Intrinsic::ppc_qpx_qvlfcs:
13651   case Intrinsic::ppc_qpx_qvlfiwa:
13652   case Intrinsic::ppc_qpx_qvlfiwz:
13653   case Intrinsic::ppc_altivec_lvx:
13654   case Intrinsic::ppc_altivec_lvxl:
13655   case Intrinsic::ppc_altivec_lvebx:
13656   case Intrinsic::ppc_altivec_lvehx:
13657   case Intrinsic::ppc_altivec_lvewx:
13658   case Intrinsic::ppc_vsx_lxvd2x:
13659   case Intrinsic::ppc_vsx_lxvw4x: {
13660     EVT VT;
13661     switch (Intrinsic) {
13662     case Intrinsic::ppc_altivec_lvebx:
13663       VT = MVT::i8;
13664       break;
13665     case Intrinsic::ppc_altivec_lvehx:
13666       VT = MVT::i16;
13667       break;
13668     case Intrinsic::ppc_altivec_lvewx:
13669       VT = MVT::i32;
13670       break;
13671     case Intrinsic::ppc_vsx_lxvd2x:
13672       VT = MVT::v2f64;
13673       break;
13674     case Intrinsic::ppc_qpx_qvlfd:
13675       VT = MVT::v4f64;
13676       break;
13677     case Intrinsic::ppc_qpx_qvlfs:
13678       VT = MVT::v4f32;
13679       break;
13680     case Intrinsic::ppc_qpx_qvlfcd:
13681       VT = MVT::v2f64;
13682       break;
13683     case Intrinsic::ppc_qpx_qvlfcs:
13684       VT = MVT::v2f32;
13685       break;
13686     default:
13687       VT = MVT::v4i32;
13688       break;
13689     }
13690 
13691     Info.opc = ISD::INTRINSIC_W_CHAIN;
13692     Info.memVT = VT;
13693     Info.ptrVal = I.getArgOperand(0);
13694     Info.offset = -VT.getStoreSize()+1;
13695     Info.size = 2*VT.getStoreSize()-1;
13696     Info.align = 1;
13697     Info.flags = MachineMemOperand::MOLoad;
13698     return true;
13699   }
13700   case Intrinsic::ppc_qpx_qvlfda:
13701   case Intrinsic::ppc_qpx_qvlfsa:
13702   case Intrinsic::ppc_qpx_qvlfcda:
13703   case Intrinsic::ppc_qpx_qvlfcsa:
13704   case Intrinsic::ppc_qpx_qvlfiwaa:
13705   case Intrinsic::ppc_qpx_qvlfiwza: {
13706     EVT VT;
13707     switch (Intrinsic) {
13708     case Intrinsic::ppc_qpx_qvlfda:
13709       VT = MVT::v4f64;
13710       break;
13711     case Intrinsic::ppc_qpx_qvlfsa:
13712       VT = MVT::v4f32;
13713       break;
13714     case Intrinsic::ppc_qpx_qvlfcda:
13715       VT = MVT::v2f64;
13716       break;
13717     case Intrinsic::ppc_qpx_qvlfcsa:
13718       VT = MVT::v2f32;
13719       break;
13720     default:
13721       VT = MVT::v4i32;
13722       break;
13723     }
13724 
13725     Info.opc = ISD::INTRINSIC_W_CHAIN;
13726     Info.memVT = VT;
13727     Info.ptrVal = I.getArgOperand(0);
13728     Info.offset = 0;
13729     Info.size = VT.getStoreSize();
13730     Info.align = 1;
13731     Info.flags = MachineMemOperand::MOLoad;
13732     return true;
13733   }
13734   case Intrinsic::ppc_qpx_qvstfd:
13735   case Intrinsic::ppc_qpx_qvstfs:
13736   case Intrinsic::ppc_qpx_qvstfcd:
13737   case Intrinsic::ppc_qpx_qvstfcs:
13738   case Intrinsic::ppc_qpx_qvstfiw:
13739   case Intrinsic::ppc_altivec_stvx:
13740   case Intrinsic::ppc_altivec_stvxl:
13741   case Intrinsic::ppc_altivec_stvebx:
13742   case Intrinsic::ppc_altivec_stvehx:
13743   case Intrinsic::ppc_altivec_stvewx:
13744   case Intrinsic::ppc_vsx_stxvd2x:
13745   case Intrinsic::ppc_vsx_stxvw4x: {
13746     EVT VT;
13747     switch (Intrinsic) {
13748     case Intrinsic::ppc_altivec_stvebx:
13749       VT = MVT::i8;
13750       break;
13751     case Intrinsic::ppc_altivec_stvehx:
13752       VT = MVT::i16;
13753       break;
13754     case Intrinsic::ppc_altivec_stvewx:
13755       VT = MVT::i32;
13756       break;
13757     case Intrinsic::ppc_vsx_stxvd2x:
13758       VT = MVT::v2f64;
13759       break;
13760     case Intrinsic::ppc_qpx_qvstfd:
13761       VT = MVT::v4f64;
13762       break;
13763     case Intrinsic::ppc_qpx_qvstfs:
13764       VT = MVT::v4f32;
13765       break;
13766     case Intrinsic::ppc_qpx_qvstfcd:
13767       VT = MVT::v2f64;
13768       break;
13769     case Intrinsic::ppc_qpx_qvstfcs:
13770       VT = MVT::v2f32;
13771       break;
13772     default:
13773       VT = MVT::v4i32;
13774       break;
13775     }
13776 
13777     Info.opc = ISD::INTRINSIC_VOID;
13778     Info.memVT = VT;
13779     Info.ptrVal = I.getArgOperand(1);
13780     Info.offset = -VT.getStoreSize()+1;
13781     Info.size = 2*VT.getStoreSize()-1;
13782     Info.align = 1;
13783     Info.flags = MachineMemOperand::MOStore;
13784     return true;
13785   }
13786   case Intrinsic::ppc_qpx_qvstfda:
13787   case Intrinsic::ppc_qpx_qvstfsa:
13788   case Intrinsic::ppc_qpx_qvstfcda:
13789   case Intrinsic::ppc_qpx_qvstfcsa:
13790   case Intrinsic::ppc_qpx_qvstfiwa: {
13791     EVT VT;
13792     switch (Intrinsic) {
13793     case Intrinsic::ppc_qpx_qvstfda:
13794       VT = MVT::v4f64;
13795       break;
13796     case Intrinsic::ppc_qpx_qvstfsa:
13797       VT = MVT::v4f32;
13798       break;
13799     case Intrinsic::ppc_qpx_qvstfcda:
13800       VT = MVT::v2f64;
13801       break;
13802     case Intrinsic::ppc_qpx_qvstfcsa:
13803       VT = MVT::v2f32;
13804       break;
13805     default:
13806       VT = MVT::v4i32;
13807       break;
13808     }
13809 
13810     Info.opc = ISD::INTRINSIC_VOID;
13811     Info.memVT = VT;
13812     Info.ptrVal = I.getArgOperand(1);
13813     Info.offset = 0;
13814     Info.size = VT.getStoreSize();
13815     Info.align = 1;
13816     Info.flags = MachineMemOperand::MOStore;
13817     return true;
13818   }
13819   default:
13820     break;
13821   }
13822 
13823   return false;
13824 }
13825 
13826 /// getOptimalMemOpType - Returns the target specific optimal type for load
13827 /// and store operations as a result of memset, memcpy, and memmove
13828 /// lowering. If DstAlign is zero that means it's safe to destination
13829 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
13830 /// means there isn't a need to check it against alignment requirement,
13831 /// probably because the source does not need to be loaded. If 'IsMemset' is
13832 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
13833 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
13834 /// source is constant so it does not need to be loaded.
13835 /// It returns EVT::Other if the type should be determined using generic
13836 /// target-independent logic.
13837 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
13838                                            unsigned DstAlign, unsigned SrcAlign,
13839                                            bool IsMemset, bool ZeroMemset,
13840                                            bool MemcpyStrSrc,
13841                                            MachineFunction &MF) const {
13842   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
13843     const Function &F = MF.getFunction();
13844     // When expanding a memset, require at least two QPX instructions to cover
13845     // the cost of loading the value to be stored from the constant pool.
13846     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
13847        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
13848         !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
13849       return MVT::v4f64;
13850     }
13851 
13852     // We should use Altivec/VSX loads and stores when available. For unaligned
13853     // addresses, unaligned VSX loads are only fast starting with the P8.
13854     if (Subtarget.hasAltivec() && Size >= 16 &&
13855         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
13856          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
13857       return MVT::v4i32;
13858   }
13859 
13860   if (Subtarget.isPPC64()) {
13861     return MVT::i64;
13862   }
13863 
13864   return MVT::i32;
13865 }
13866 
13867 /// Returns true if it is beneficial to convert a load of a constant
13868 /// to just the constant itself.
13869 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13870                                                           Type *Ty) const {
13871   assert(Ty->isIntegerTy());
13872 
13873   unsigned BitSize = Ty->getPrimitiveSizeInBits();
13874   return !(BitSize == 0 || BitSize > 64);
13875 }
13876 
13877 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13878   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13879     return false;
13880   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13881   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13882   return NumBits1 == 64 && NumBits2 == 32;
13883 }
13884 
13885 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13886   if (!VT1.isInteger() || !VT2.isInteger())
13887     return false;
13888   unsigned NumBits1 = VT1.getSizeInBits();
13889   unsigned NumBits2 = VT2.getSizeInBits();
13890   return NumBits1 == 64 && NumBits2 == 32;
13891 }
13892 
13893 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13894   // Generally speaking, zexts are not free, but they are free when they can be
13895   // folded with other operations.
13896   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
13897     EVT MemVT = LD->getMemoryVT();
13898     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
13899          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
13900         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
13901          LD->getExtensionType() == ISD::ZEXTLOAD))
13902       return true;
13903   }
13904 
13905   // FIXME: Add other cases...
13906   //  - 32-bit shifts with a zext to i64
13907   //  - zext after ctlz, bswap, etc.
13908   //  - zext after and by a constant mask
13909 
13910   return TargetLowering::isZExtFree(Val, VT2);
13911 }
13912 
13913 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
13914   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
13915          "invalid fpext types");
13916   // Extending to float128 is not free.
13917   if (DestVT == MVT::f128)
13918     return false;
13919   return true;
13920 }
13921 
13922 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13923   return isInt<16>(Imm) || isUInt<16>(Imm);
13924 }
13925 
13926 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13927   return isInt<16>(Imm) || isUInt<16>(Imm);
13928 }
13929 
13930 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13931                                                        unsigned,
13932                                                        unsigned,
13933                                                        bool *Fast) const {
13934   if (DisablePPCUnaligned)
13935     return false;
13936 
13937   // PowerPC supports unaligned memory access for simple non-vector types.
13938   // Although accessing unaligned addresses is not as efficient as accessing
13939   // aligned addresses, it is generally more efficient than manual expansion,
13940   // and generally only traps for software emulation when crossing page
13941   // boundaries.
13942 
13943   if (!VT.isSimple())
13944     return false;
13945 
13946   if (VT.getSimpleVT().isVector()) {
13947     if (Subtarget.hasVSX()) {
13948       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
13949           VT != MVT::v4f32 && VT != MVT::v4i32)
13950         return false;
13951     } else {
13952       return false;
13953     }
13954   }
13955 
13956   if (VT == MVT::ppcf128)
13957     return false;
13958 
13959   if (Fast)
13960     *Fast = true;
13961 
13962   return true;
13963 }
13964 
13965 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13966   VT = VT.getScalarType();
13967 
13968   if (!VT.isSimple())
13969     return false;
13970 
13971   switch (VT.getSimpleVT().SimpleTy) {
13972   case MVT::f32:
13973   case MVT::f64:
13974     return true;
13975   case MVT::f128:
13976     return (EnableQuadPrecision && Subtarget.hasP9Vector());
13977   default:
13978     break;
13979   }
13980 
13981   return false;
13982 }
13983 
13984 const MCPhysReg *
13985 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
13986   // LR is a callee-save register, but we must treat it as clobbered by any call
13987   // site. Hence we include LR in the scratch registers, which are in turn added
13988   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
13989   // to CTR, which is used by any indirect call.
13990   static const MCPhysReg ScratchRegs[] = {
13991     PPC::X12, PPC::LR8, PPC::CTR8, 0
13992   };
13993 
13994   return ScratchRegs;
13995 }
13996 
13997 unsigned PPCTargetLowering::getExceptionPointerRegister(
13998     const Constant *PersonalityFn) const {
13999   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
14000 }
14001 
14002 unsigned PPCTargetLowering::getExceptionSelectorRegister(
14003     const Constant *PersonalityFn) const {
14004   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
14005 }
14006 
14007 bool
14008 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
14009                      EVT VT , unsigned DefinedValues) const {
14010   if (VT == MVT::v2i64)
14011     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
14012 
14013   if (Subtarget.hasVSX() || Subtarget.hasQPX())
14014     return true;
14015 
14016   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
14017 }
14018 
14019 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
14020   if (DisableILPPref || Subtarget.enableMachineScheduler())
14021     return TargetLowering::getSchedulingPreference(N);
14022 
14023   return Sched::ILP;
14024 }
14025 
14026 // Create a fast isel object.
14027 FastISel *
14028 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
14029                                   const TargetLibraryInfo *LibInfo) const {
14030   return PPC::createFastISel(FuncInfo, LibInfo);
14031 }
14032 
14033 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14034   if (Subtarget.isDarwinABI()) return;
14035   if (!Subtarget.isPPC64()) return;
14036 
14037   // Update IsSplitCSR in PPCFunctionInfo
14038   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
14039   PFI->setIsSplitCSR(true);
14040 }
14041 
14042 void PPCTargetLowering::insertCopiesSplitCSR(
14043   MachineBasicBlock *Entry,
14044   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14045   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
14046   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14047   if (!IStart)
14048     return;
14049 
14050   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14051   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14052   MachineBasicBlock::iterator MBBI = Entry->begin();
14053   for (const MCPhysReg *I = IStart; *I; ++I) {
14054     const TargetRegisterClass *RC = nullptr;
14055     if (PPC::G8RCRegClass.contains(*I))
14056       RC = &PPC::G8RCRegClass;
14057     else if (PPC::F8RCRegClass.contains(*I))
14058       RC = &PPC::F8RCRegClass;
14059     else if (PPC::CRRCRegClass.contains(*I))
14060       RC = &PPC::CRRCRegClass;
14061     else if (PPC::VRRCRegClass.contains(*I))
14062       RC = &PPC::VRRCRegClass;
14063     else
14064       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14065 
14066     unsigned NewVR = MRI->createVirtualRegister(RC);
14067     // Create copy from CSR to a virtual register.
14068     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14069     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14070     // nounwind. If we want to generalize this later, we may need to emit
14071     // CFI pseudo-instructions.
14072     assert(Entry->getParent()->getFunction().hasFnAttribute(
14073              Attribute::NoUnwind) &&
14074            "Function should be nounwind in insertCopiesSplitCSR!");
14075     Entry->addLiveIn(*I);
14076     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14077       .addReg(*I);
14078 
14079     // Insert the copy-back instructions right before the terminator
14080     for (auto *Exit : Exits)
14081       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14082               TII->get(TargetOpcode::COPY), *I)
14083         .addReg(NewVR);
14084   }
14085 }
14086 
14087 // Override to enable LOAD_STACK_GUARD lowering on Linux.
14088 bool PPCTargetLowering::useLoadStackGuardNode() const {
14089   if (!Subtarget.isTargetLinux())
14090     return TargetLowering::useLoadStackGuardNode();
14091   return true;
14092 }
14093 
14094 // Override to disable global variable loading on Linux.
14095 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
14096   if (!Subtarget.isTargetLinux())
14097     return TargetLowering::insertSSPDeclarations(M);
14098 }
14099 
14100 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
14101   if (!VT.isSimple() || !Subtarget.hasVSX())
14102     return false;
14103 
14104   switch(VT.getSimpleVT().SimpleTy) {
14105   default:
14106     // For FP types that are currently not supported by PPC backend, return
14107     // false. Examples: f16, f80.
14108     return false;
14109   case MVT::f32:
14110   case MVT::f64:
14111   case MVT::ppcf128:
14112     return Imm.isPosZero();
14113   }
14114 }
14115 
14116 // For vector shift operation op, fold
14117 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
14118 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
14119                                   SelectionDAG &DAG) {
14120   SDValue N0 = N->getOperand(0);
14121   SDValue N1 = N->getOperand(1);
14122   EVT VT = N0.getValueType();
14123   unsigned OpSizeInBits = VT.getScalarSizeInBits();
14124   unsigned Opcode = N->getOpcode();
14125   unsigned TargetOpcode;
14126 
14127   switch (Opcode) {
14128   default:
14129     llvm_unreachable("Unexpected shift operation");
14130   case ISD::SHL:
14131     TargetOpcode = PPCISD::SHL;
14132     break;
14133   case ISD::SRL:
14134     TargetOpcode = PPCISD::SRL;
14135     break;
14136   case ISD::SRA:
14137     TargetOpcode = PPCISD::SRA;
14138     break;
14139   }
14140 
14141   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
14142       N1->getOpcode() == ISD::AND)
14143     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
14144       if (Mask->getZExtValue() == OpSizeInBits - 1)
14145         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
14146 
14147   return SDValue();
14148 }
14149 
14150 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
14151   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14152     return Value;
14153 
14154   SDValue N0 = N->getOperand(0);
14155   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
14156   if (!Subtarget.isISA3_0() ||
14157       N0.getOpcode() != ISD::SIGN_EXTEND ||
14158       N0.getOperand(0).getValueType() != MVT::i32 ||
14159       CN1 == nullptr || N->getValueType(0) != MVT::i64)
14160     return SDValue();
14161 
14162   // We can't save an operation here if the value is already extended, and
14163   // the existing shift is easier to combine.
14164   SDValue ExtsSrc = N0.getOperand(0);
14165   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
14166       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
14167     return SDValue();
14168 
14169   SDLoc DL(N0);
14170   SDValue ShiftBy = SDValue(CN1, 0);
14171   // We want the shift amount to be i32 on the extswli, but the shift could
14172   // have an i64.
14173   if (ShiftBy.getValueType() == MVT::i64)
14174     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
14175 
14176   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
14177                          ShiftBy);
14178 }
14179 
14180 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
14181   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14182     return Value;
14183 
14184   return SDValue();
14185 }
14186 
14187 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
14188   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14189     return Value;
14190 
14191   return SDValue();
14192 }
14193 
14194 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
14195 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
14196 // When C is zero, the equation (addi Z, -C) can be simplified to Z
14197 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
14198 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
14199                                  const PPCSubtarget &Subtarget) {
14200   if (!Subtarget.isPPC64())
14201     return SDValue();
14202 
14203   SDValue LHS = N->getOperand(0);
14204   SDValue RHS = N->getOperand(1);
14205 
14206   auto isZextOfCompareWithConstant = [](SDValue Op) {
14207     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
14208         Op.getValueType() != MVT::i64)
14209       return false;
14210 
14211     SDValue Cmp = Op.getOperand(0);
14212     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
14213         Cmp.getOperand(0).getValueType() != MVT::i64)
14214       return false;
14215 
14216     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
14217       int64_t NegConstant = 0 - Constant->getSExtValue();
14218       // Due to the limitations of the addi instruction,
14219       // -C is required to be [-32768, 32767].
14220       return isInt<16>(NegConstant);
14221     }
14222 
14223     return false;
14224   };
14225 
14226   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
14227   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
14228 
14229   // If there is a pattern, canonicalize a zext operand to the RHS.
14230   if (LHSHasPattern && !RHSHasPattern)
14231     std::swap(LHS, RHS);
14232   else if (!LHSHasPattern && !RHSHasPattern)
14233     return SDValue();
14234 
14235   SDLoc DL(N);
14236   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i64);
14237   SDValue Cmp = RHS.getOperand(0);
14238   SDValue Z = Cmp.getOperand(0);
14239   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
14240 
14241   assert(Constant && "Constant Should not be a null pointer.");
14242   int64_t NegConstant = 0 - Constant->getSExtValue();
14243 
14244   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
14245   default: break;
14246   case ISD::SETNE: {
14247     //                                 when C == 0
14248     //                             --> addze X, (addic Z, -1).carry
14249     //                            /
14250     // add X, (zext(setne Z, C))--
14251     //                            \    when -32768 <= -C <= 32767 && C != 0
14252     //                             --> addze X, (addic (addi Z, -C), -1).carry
14253     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14254                               DAG.getConstant(NegConstant, DL, MVT::i64));
14255     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14256     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14257                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
14258     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14259                        SDValue(Addc.getNode(), 1));
14260     }
14261   case ISD::SETEQ: {
14262     //                                 when C == 0
14263     //                             --> addze X, (subfic Z, 0).carry
14264     //                            /
14265     // add X, (zext(sete  Z, C))--
14266     //                            \    when -32768 <= -C <= 32767 && C != 0
14267     //                             --> addze X, (subfic (addi Z, -C), 0).carry
14268     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14269                               DAG.getConstant(NegConstant, DL, MVT::i64));
14270     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14271     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14272                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
14273     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14274                        SDValue(Subc.getNode(), 1));
14275     }
14276   }
14277 
14278   return SDValue();
14279 }
14280 
14281 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
14282   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
14283     return Value;
14284 
14285   return SDValue();
14286 }
14287 
14288 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14289   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
14290   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
14291     return false;
14292 
14293   // If not a tail call then no need to proceed.
14294   if (!CI->isTailCall())
14295     return false;
14296 
14297   // If tail calls are disabled for the caller then we are done.
14298   const Function *Caller = CI->getParent()->getParent();
14299   auto Attr = Caller->getFnAttribute("disable-tail-calls");
14300   if (Attr.getValueAsString() == "true")
14301     return false;
14302 
14303   // If sibling calls have been disabled and tail-calls aren't guaranteed
14304   // there is no reason to duplicate.
14305   auto &TM = getTargetMachine();
14306   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
14307     return false;
14308 
14309   // Can't tail call a function called indirectly, or if it has variadic args.
14310   const Function *Callee = CI->getCalledFunction();
14311   if (!Callee || Callee->isVarArg())
14312     return false;
14313 
14314   // Make sure the callee and caller calling conventions are eligible for tco.
14315   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
14316                                            CI->getCallingConv()))
14317       return false;
14318 
14319   // If the function is local then we have a good chance at tail-calling it
14320   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
14321 }
14322 
14323 bool PPCTargetLowering::
14324 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
14325   const Value *Mask = AndI.getOperand(1);
14326   // If the mask is suitable for andi. or andis. we should sink the and.
14327   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
14328     // Can't handle constants wider than 64-bits.
14329     if (CI->getBitWidth() > 64)
14330       return false;
14331     int64_t ConstVal = CI->getZExtValue();
14332     return isUInt<16>(ConstVal) ||
14333       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
14334   }
14335 
14336   // For non-constant masks, we can always use the record-form and.
14337   return true;
14338 }
14339