1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineOperand.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/CodeGen/RuntimeLibcalls.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGNodes.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetLowering.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/IR/CallSite.h"
57 #include "llvm/IR/CallingConv.h"
58 #include "llvm/IR/Constant.h"
59 #include "llvm/IR/Constants.h"
60 #include "llvm/IR/DataLayout.h"
61 #include "llvm/IR/DebugLoc.h"
62 #include "llvm/IR/DerivedTypes.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/IRBuilder.h"
66 #include "llvm/IR/Instructions.h"
67 #include "llvm/IR/Intrinsics.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/MC/MCExpr.h"
73 #include "llvm/MC/MCRegisterInfo.h"
74 #include "llvm/Support/AtomicOrdering.h"
75 #include "llvm/Support/BranchProbability.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CodeGen.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/Format.h"
83 #include "llvm/Support/KnownBits.h"
84 #include "llvm/Support/MachineValueType.h"
85 #include "llvm/Support/MathExtras.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstdint>
92 #include <iterator>
93 #include <list>
94 #include <utility>
95 #include <vector>
96 
97 using namespace llvm;
98 
99 #define DEBUG_TYPE "ppc-lowering"
100 
101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
103 
104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
106 
107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
109 
110 static cl::opt<bool> DisableSCO("disable-ppc-sco",
111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
112 
113 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
114 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
115 
116 STATISTIC(NumTailCalls, "Number of tail calls");
117 STATISTIC(NumSiblingCalls, "Number of sibling calls");
118 
119 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
120 
121 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
122 
123 // FIXME: Remove this once the bug has been fixed!
124 extern cl::opt<bool> ANDIGlueBug;
125 
126 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
127                                      const PPCSubtarget &STI)
128     : TargetLowering(TM), Subtarget(STI) {
129   // Use _setjmp/_longjmp instead of setjmp/longjmp.
130   setUseUnderscoreSetJmp(true);
131   setUseUnderscoreLongJmp(true);
132 
133   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
134   // arguments are at least 4/8 bytes aligned.
135   bool isPPC64 = Subtarget.isPPC64();
136   setMinStackArgumentAlignment(isPPC64 ? 8:4);
137 
138   // Set up the register classes.
139   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
140   if (!useSoftFloat()) {
141     if (hasSPE()) {
142       addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
143       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
144     } else {
145       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
146       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
147     }
148   }
149 
150   // Match BITREVERSE to customized fast code sequence in the td file.
151   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
152   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
153 
154   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
155   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
156 
157   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
158   for (MVT VT : MVT::integer_valuetypes()) {
159     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
160     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
161   }
162 
163   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
164 
165   // PowerPC has pre-inc load and store's.
166   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
167   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
168   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
169   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
170   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
171   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
172   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
173   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
174   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
175   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
176   if (!Subtarget.hasSPE()) {
177     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
178     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
179     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
180     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
181   }
182 
183   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
184   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
185   for (MVT VT : ScalarIntVTs) {
186     setOperationAction(ISD::ADDC, VT, Legal);
187     setOperationAction(ISD::ADDE, VT, Legal);
188     setOperationAction(ISD::SUBC, VT, Legal);
189     setOperationAction(ISD::SUBE, VT, Legal);
190   }
191 
192   if (Subtarget.useCRBits()) {
193     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
194 
195     if (isPPC64 || Subtarget.hasFPCVT()) {
196       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
197       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
198                          isPPC64 ? MVT::i64 : MVT::i32);
199       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
200       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
201                         isPPC64 ? MVT::i64 : MVT::i32);
202     } else {
203       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
204       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
205     }
206 
207     // PowerPC does not support direct load/store of condition registers.
208     setOperationAction(ISD::LOAD, MVT::i1, Custom);
209     setOperationAction(ISD::STORE, MVT::i1, Custom);
210 
211     // FIXME: Remove this once the ANDI glue bug is fixed:
212     if (ANDIGlueBug)
213       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
214 
215     for (MVT VT : MVT::integer_valuetypes()) {
216       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
217       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
218       setTruncStoreAction(VT, MVT::i1, Expand);
219     }
220 
221     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
222   }
223 
224   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
225   // PPC (the libcall is not available).
226   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
227   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
228 
229   // We do not currently implement these libm ops for PowerPC.
230   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
231   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
232   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
233   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
234   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
235   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
236 
237   // PowerPC has no SREM/UREM instructions unless we are on P9
238   // On P9 we may use a hardware instruction to compute the remainder.
239   // The instructions are not legalized directly because in the cases where the
240   // result of both the remainder and the division is required it is more
241   // efficient to compute the remainder from the result of the division rather
242   // than use the remainder instruction.
243   if (Subtarget.isISA3_0()) {
244     setOperationAction(ISD::SREM, MVT::i32, Custom);
245     setOperationAction(ISD::UREM, MVT::i32, Custom);
246     setOperationAction(ISD::SREM, MVT::i64, Custom);
247     setOperationAction(ISD::UREM, MVT::i64, Custom);
248   } else {
249     setOperationAction(ISD::SREM, MVT::i32, Expand);
250     setOperationAction(ISD::UREM, MVT::i32, Expand);
251     setOperationAction(ISD::SREM, MVT::i64, Expand);
252     setOperationAction(ISD::UREM, MVT::i64, Expand);
253   }
254 
255   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
256   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
257   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
258   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
259   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
260   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
261   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
262   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
263   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
264 
265   // We don't support sin/cos/sqrt/fmod/pow
266   setOperationAction(ISD::FSIN , MVT::f64, Expand);
267   setOperationAction(ISD::FCOS , MVT::f64, Expand);
268   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
269   setOperationAction(ISD::FREM , MVT::f64, Expand);
270   setOperationAction(ISD::FPOW , MVT::f64, Expand);
271   setOperationAction(ISD::FSIN , MVT::f32, Expand);
272   setOperationAction(ISD::FCOS , MVT::f32, Expand);
273   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
274   setOperationAction(ISD::FREM , MVT::f32, Expand);
275   setOperationAction(ISD::FPOW , MVT::f32, Expand);
276   if (Subtarget.hasSPE()) {
277     setOperationAction(ISD::FMA  , MVT::f64, Expand);
278     setOperationAction(ISD::FMA  , MVT::f32, Expand);
279   } else {
280     setOperationAction(ISD::FMA  , MVT::f64, Legal);
281     setOperationAction(ISD::FMA  , MVT::f32, Legal);
282   }
283 
284   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
285 
286   // If we're enabling GP optimizations, use hardware square root
287   if (!Subtarget.hasFSQRT() &&
288       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
289         Subtarget.hasFRE()))
290     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
291 
292   if (!Subtarget.hasFSQRT() &&
293       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
294         Subtarget.hasFRES()))
295     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
296 
297   if (Subtarget.hasFCPSGN()) {
298     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
299     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
300   } else {
301     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
302     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
303   }
304 
305   if (Subtarget.hasFPRND()) {
306     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
307     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
308     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
309     setOperationAction(ISD::FROUND, MVT::f64, Legal);
310 
311     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
312     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
313     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
314     setOperationAction(ISD::FROUND, MVT::f32, Legal);
315   }
316 
317   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
318   // to speed up scalar BSWAP64.
319   // CTPOP or CTTZ were introduced in P8/P9 respectively
320   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
321   if (Subtarget.hasP9Vector())
322     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
323   else
324     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
325   if (Subtarget.isISA3_0()) {
326     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
327     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
328   } else {
329     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
330     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
331   }
332 
333   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
334     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
335     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
336   } else {
337     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
338     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
339   }
340 
341   // PowerPC does not have ROTR
342   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
343   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
344 
345   if (!Subtarget.useCRBits()) {
346     // PowerPC does not have Select
347     setOperationAction(ISD::SELECT, MVT::i32, Expand);
348     setOperationAction(ISD::SELECT, MVT::i64, Expand);
349     setOperationAction(ISD::SELECT, MVT::f32, Expand);
350     setOperationAction(ISD::SELECT, MVT::f64, Expand);
351   }
352 
353   // PowerPC wants to turn select_cc of FP into fsel when possible.
354   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
355   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
356 
357   // PowerPC wants to optimize integer setcc a bit
358   if (!Subtarget.useCRBits())
359     setOperationAction(ISD::SETCC, MVT::i32, Custom);
360 
361   // PowerPC does not have BRCOND which requires SetCC
362   if (!Subtarget.useCRBits())
363     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
364 
365   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
366 
367   if (Subtarget.hasSPE()) {
368     // SPE has built-in conversions
369     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
370     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
371     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
372   } else {
373     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
374     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
375 
376     // PowerPC does not have [U|S]INT_TO_FP
377     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
378     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
379   }
380 
381   if (Subtarget.hasDirectMove() && isPPC64) {
382     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
383     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
384     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
385     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
386   } else {
387     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
388     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
389     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
390     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
391   }
392 
393   // We cannot sextinreg(i1).  Expand to shifts.
394   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
395 
396   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
397   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
398   // support continuation, user-level threading, and etc.. As a result, no
399   // other SjLj exception interfaces are implemented and please don't build
400   // your own exception handling based on them.
401   // LLVM/Clang supports zero-cost DWARF exception handling.
402   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
403   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
404 
405   // We want to legalize GlobalAddress and ConstantPool nodes into the
406   // appropriate instructions to materialize the address.
407   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
408   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
409   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
410   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
411   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
412   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
413   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
414   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
415   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
416   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
417 
418   // TRAP is legal.
419   setOperationAction(ISD::TRAP, MVT::Other, Legal);
420 
421   // TRAMPOLINE is custom lowered.
422   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
423   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
424 
425   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
426   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
427 
428   if (Subtarget.isSVR4ABI()) {
429     if (isPPC64) {
430       // VAARG always uses double-word chunks, so promote anything smaller.
431       setOperationAction(ISD::VAARG, MVT::i1, Promote);
432       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
433       setOperationAction(ISD::VAARG, MVT::i8, Promote);
434       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
435       setOperationAction(ISD::VAARG, MVT::i16, Promote);
436       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
437       setOperationAction(ISD::VAARG, MVT::i32, Promote);
438       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
439       setOperationAction(ISD::VAARG, MVT::Other, Expand);
440     } else {
441       // VAARG is custom lowered with the 32-bit SVR4 ABI.
442       setOperationAction(ISD::VAARG, MVT::Other, Custom);
443       setOperationAction(ISD::VAARG, MVT::i64, Custom);
444     }
445   } else
446     setOperationAction(ISD::VAARG, MVT::Other, Expand);
447 
448   if (Subtarget.isSVR4ABI() && !isPPC64)
449     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
450     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
451   else
452     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
453 
454   // Use the default implementation.
455   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
456   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
457   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
458   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
459   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
460   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
461   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
462   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
463   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
464 
465   // We want to custom lower some of our intrinsics.
466   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
467 
468   // To handle counter-based loop conditions.
469   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
470 
471   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
472   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
473   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
474   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
475 
476   // Comparisons that require checking two conditions.
477   if (Subtarget.hasSPE()) {
478     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
479     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
480     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
481     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
482   }
483   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
484   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
485   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
486   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
487   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
488   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
489   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
490   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
491   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
492   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
493   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
494   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
495 
496   if (Subtarget.has64BitSupport()) {
497     // They also have instructions for converting between i64 and fp.
498     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
499     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
500     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
501     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
502     // This is just the low 32 bits of a (signed) fp->i64 conversion.
503     // We cannot do this with Promote because i64 is not a legal type.
504     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
505 
506     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
507       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
508   } else {
509     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
510     if (Subtarget.hasSPE())
511       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
512     else
513       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
514   }
515 
516   // With the instructions enabled under FPCVT, we can do everything.
517   if (Subtarget.hasFPCVT()) {
518     if (Subtarget.has64BitSupport()) {
519       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
520       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
521       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
522       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
523     }
524 
525     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
526     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
527     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
529   }
530 
531   if (Subtarget.use64BitRegs()) {
532     // 64-bit PowerPC implementations can support i64 types directly
533     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
534     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
535     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
536     // 64-bit PowerPC wants to expand i128 shifts itself.
537     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
538     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
539     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
540   } else {
541     // 32-bit PowerPC wants to expand i64 shifts itself.
542     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
543     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
544     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
545   }
546 
547   if (Subtarget.hasAltivec()) {
548     // First set operation action for all vector types to expand. Then we
549     // will selectively turn on ones that can be effectively codegen'd.
550     for (MVT VT : MVT::vector_valuetypes()) {
551       // add/sub are legal for all supported vector VT's.
552       setOperationAction(ISD::ADD, VT, Legal);
553       setOperationAction(ISD::SUB, VT, Legal);
554 
555       // Vector instructions introduced in P8
556       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
557         setOperationAction(ISD::CTPOP, VT, Legal);
558         setOperationAction(ISD::CTLZ, VT, Legal);
559       }
560       else {
561         setOperationAction(ISD::CTPOP, VT, Expand);
562         setOperationAction(ISD::CTLZ, VT, Expand);
563       }
564 
565       // Vector instructions introduced in P9
566       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
567         setOperationAction(ISD::CTTZ, VT, Legal);
568       else
569         setOperationAction(ISD::CTTZ, VT, Expand);
570 
571       // We promote all shuffles to v16i8.
572       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
573       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
574 
575       // We promote all non-typed operations to v4i32.
576       setOperationAction(ISD::AND   , VT, Promote);
577       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
578       setOperationAction(ISD::OR    , VT, Promote);
579       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
580       setOperationAction(ISD::XOR   , VT, Promote);
581       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
582       setOperationAction(ISD::LOAD  , VT, Promote);
583       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
584       setOperationAction(ISD::SELECT, VT, Promote);
585       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
586       setOperationAction(ISD::VSELECT, VT, Legal);
587       setOperationAction(ISD::SELECT_CC, VT, Promote);
588       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
589       setOperationAction(ISD::STORE, VT, Promote);
590       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
591 
592       // No other operations are legal.
593       setOperationAction(ISD::MUL , VT, Expand);
594       setOperationAction(ISD::SDIV, VT, Expand);
595       setOperationAction(ISD::SREM, VT, Expand);
596       setOperationAction(ISD::UDIV, VT, Expand);
597       setOperationAction(ISD::UREM, VT, Expand);
598       setOperationAction(ISD::FDIV, VT, Expand);
599       setOperationAction(ISD::FREM, VT, Expand);
600       setOperationAction(ISD::FNEG, VT, Expand);
601       setOperationAction(ISD::FSQRT, VT, Expand);
602       setOperationAction(ISD::FLOG, VT, Expand);
603       setOperationAction(ISD::FLOG10, VT, Expand);
604       setOperationAction(ISD::FLOG2, VT, Expand);
605       setOperationAction(ISD::FEXP, VT, Expand);
606       setOperationAction(ISD::FEXP2, VT, Expand);
607       setOperationAction(ISD::FSIN, VT, Expand);
608       setOperationAction(ISD::FCOS, VT, Expand);
609       setOperationAction(ISD::FABS, VT, Expand);
610       setOperationAction(ISD::FFLOOR, VT, Expand);
611       setOperationAction(ISD::FCEIL,  VT, Expand);
612       setOperationAction(ISD::FTRUNC, VT, Expand);
613       setOperationAction(ISD::FRINT,  VT, Expand);
614       setOperationAction(ISD::FNEARBYINT, VT, Expand);
615       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
616       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
617       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
618       setOperationAction(ISD::MULHU, VT, Expand);
619       setOperationAction(ISD::MULHS, VT, Expand);
620       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
621       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
622       setOperationAction(ISD::UDIVREM, VT, Expand);
623       setOperationAction(ISD::SDIVREM, VT, Expand);
624       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
625       setOperationAction(ISD::FPOW, VT, Expand);
626       setOperationAction(ISD::BSWAP, VT, Expand);
627       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
628       setOperationAction(ISD::ROTL, VT, Expand);
629       setOperationAction(ISD::ROTR, VT, Expand);
630 
631       for (MVT InnerVT : MVT::vector_valuetypes()) {
632         setTruncStoreAction(VT, InnerVT, Expand);
633         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
634         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
635         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
636       }
637     }
638 
639     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
640       setOperationAction(ISD::ABS, VT, Custom);
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     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
647     // are cheap, so handle them before they get expanded to scalar.
648     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
649     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
650     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
651     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
652     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
653 
654     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
655     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
656     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
657     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
658     setOperationAction(ISD::SELECT, MVT::v4i32,
659                        Subtarget.useCRBits() ? Legal : Expand);
660     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
661     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
662     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
663     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
664     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
665     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
666     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
667     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
668     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
669 
670     // Without hasP8Altivec set, v2i64 SMAX isn't available.
671     // But ABS custom lowering requires SMAX support.
672     if (!Subtarget.hasP8Altivec())
673       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
674 
675     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
676     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
677     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
678     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
679 
680     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
681     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
682 
683     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
684       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
685       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
686     }
687 
688     if (Subtarget.hasP8Altivec())
689       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
690     else
691       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
692 
693     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
694     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
695 
696     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
697     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
698 
699     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
700     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
701     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
702     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
703 
704     // Altivec does not contain unordered floating-point compare instructions
705     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
706     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
707     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
708     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
709 
710     if (Subtarget.hasVSX()) {
711       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
712       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
713       if (Subtarget.hasP8Vector()) {
714         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
715         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
716       }
717       if (Subtarget.hasDirectMove() && isPPC64) {
718         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
719         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
720         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
721         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
722         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
723         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
724         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
725         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
726       }
727       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
728 
729       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
730       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
731       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
732       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
733       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
734 
735       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
736 
737       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
738       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
739 
740       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
741       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
742 
743       // Share the Altivec comparison restrictions.
744       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
745       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
746       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
747       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
748 
749       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
750       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
751 
752       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
753 
754       if (Subtarget.hasP8Vector())
755         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
756 
757       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
758 
759       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
760       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
761       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
762 
763       if (Subtarget.hasP8Altivec()) {
764         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
765         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
766         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
767 
768         // 128 bit shifts can be accomplished via 3 instructions for SHL and
769         // SRL, but not for SRA because of the instructions available:
770         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
771         // doing
772         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
773         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
774         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
775 
776         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
777       }
778       else {
779         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
780         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
781         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
782 
783         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
784 
785         // VSX v2i64 only supports non-arithmetic operations.
786         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
787         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
788       }
789 
790       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
791       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
792       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
793       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
794 
795       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
796 
797       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
798       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
799       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
800       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
801 
802       // Custom handling for partial vectors of integers converted to
803       // floating point. We already have optimal handling for v2i32 through
804       // the DAG combine, so those aren't necessary.
805       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
806       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
807       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
808       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
809       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
810       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
811       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
812       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
813 
814       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
815       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
816       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
817       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
818 
819       if (Subtarget.hasDirectMove())
820         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
821       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
822 
823       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
824     }
825 
826     if (Subtarget.hasP8Altivec()) {
827       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
828       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
829     }
830 
831     if (Subtarget.hasP9Vector()) {
832       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
833       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
834 
835       // 128 bit shifts can be accomplished via 3 instructions for SHL and
836       // SRL, but not for SRA because of the instructions available:
837       // VS{RL} and VS{RL}O.
838       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
839       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
840       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
841 
842       if (EnableQuadPrecision) {
843         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
844         setOperationAction(ISD::FADD, MVT::f128, Legal);
845         setOperationAction(ISD::FSUB, MVT::f128, Legal);
846         setOperationAction(ISD::FDIV, MVT::f128, Legal);
847         setOperationAction(ISD::FMUL, MVT::f128, Legal);
848         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
849         // No extending loads to f128 on PPC.
850         for (MVT FPT : MVT::fp_valuetypes())
851           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
852         setOperationAction(ISD::FMA, MVT::f128, Legal);
853         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
854         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
855         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
856         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
857         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
858         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
859 
860         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
861         setOperationAction(ISD::FRINT, MVT::f128, Legal);
862         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
863         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
864         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
865         setOperationAction(ISD::FROUND, MVT::f128, Legal);
866 
867         setOperationAction(ISD::SELECT, MVT::f128, Expand);
868         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
869         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
870         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
871         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
872         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
873         // No implementation for these ops for PowerPC.
874         setOperationAction(ISD::FSIN , MVT::f128, Expand);
875         setOperationAction(ISD::FCOS , MVT::f128, Expand);
876         setOperationAction(ISD::FPOW, MVT::f128, Expand);
877         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
878         setOperationAction(ISD::FREM, MVT::f128, Expand);
879       }
880       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
881 
882     }
883 
884     if (Subtarget.hasP9Altivec()) {
885       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
886       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
887     }
888   }
889 
890   if (Subtarget.hasQPX()) {
891     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
892     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
893     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
894     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
895 
896     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
897     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
898 
899     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
900     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
901 
902     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
903     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
904 
905     if (!Subtarget.useCRBits())
906       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
907     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
908 
909     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
910     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
911     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
912     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
913     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
914     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
915     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
916 
917     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
918     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
919 
920     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
921     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
922     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
923 
924     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
925     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
926     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
927     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
928     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
929     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
930     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
931     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
932     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
933     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
934 
935     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
936     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
937 
938     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
939     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
940 
941     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
942 
943     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
944     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
945     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
946     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
947 
948     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
949     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
950 
951     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
952     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
953 
954     if (!Subtarget.useCRBits())
955       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
956     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
957 
958     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
959     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
960     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
961     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
962     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
963     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
964     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
965 
966     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
967     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
968 
969     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
970     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
971     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
972     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
973     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
974     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
975     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
976     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
977     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
978     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
979 
980     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
981     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
982 
983     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
984     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
985 
986     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
987 
988     setOperationAction(ISD::AND , MVT::v4i1, Legal);
989     setOperationAction(ISD::OR , MVT::v4i1, Legal);
990     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
991 
992     if (!Subtarget.useCRBits())
993       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
994     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
995 
996     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
997     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
998 
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1001     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1002     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1003     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1004     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1005     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1006 
1007     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1008     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1009 
1010     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1011 
1012     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1013     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1014     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1015     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1016 
1017     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1018     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1019     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1020     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1021 
1022     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1023     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1024 
1025     // These need to set FE_INEXACT, and so cannot be vectorized here.
1026     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1027     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1028 
1029     if (TM.Options.UnsafeFPMath) {
1030       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1031       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1032 
1033       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1034       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1035     } else {
1036       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1037       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1038 
1039       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1040       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1041     }
1042   }
1043 
1044   if (Subtarget.has64BitSupport())
1045     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1046 
1047   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1048 
1049   if (!isPPC64) {
1050     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1051     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1052   }
1053 
1054   setBooleanContents(ZeroOrOneBooleanContent);
1055 
1056   if (Subtarget.hasAltivec()) {
1057     // Altivec instructions set fields to all zeros or all ones.
1058     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1059   }
1060 
1061   if (!isPPC64) {
1062     // These libcalls are not available in 32-bit.
1063     setLibcallName(RTLIB::SHL_I128, nullptr);
1064     setLibcallName(RTLIB::SRL_I128, nullptr);
1065     setLibcallName(RTLIB::SRA_I128, nullptr);
1066   }
1067 
1068   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1069 
1070   // We have target-specific dag combine patterns for the following nodes:
1071   setTargetDAGCombine(ISD::ADD);
1072   setTargetDAGCombine(ISD::SHL);
1073   setTargetDAGCombine(ISD::SRA);
1074   setTargetDAGCombine(ISD::SRL);
1075   setTargetDAGCombine(ISD::MUL);
1076   setTargetDAGCombine(ISD::SINT_TO_FP);
1077   setTargetDAGCombine(ISD::BUILD_VECTOR);
1078   if (Subtarget.hasFPCVT())
1079     setTargetDAGCombine(ISD::UINT_TO_FP);
1080   setTargetDAGCombine(ISD::LOAD);
1081   setTargetDAGCombine(ISD::STORE);
1082   setTargetDAGCombine(ISD::BR_CC);
1083   if (Subtarget.useCRBits())
1084     setTargetDAGCombine(ISD::BRCOND);
1085   setTargetDAGCombine(ISD::BSWAP);
1086   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1087   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1088   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1089 
1090   setTargetDAGCombine(ISD::SIGN_EXTEND);
1091   setTargetDAGCombine(ISD::ZERO_EXTEND);
1092   setTargetDAGCombine(ISD::ANY_EXTEND);
1093 
1094   setTargetDAGCombine(ISD::TRUNCATE);
1095 
1096   if (Subtarget.useCRBits()) {
1097     setTargetDAGCombine(ISD::TRUNCATE);
1098     setTargetDAGCombine(ISD::SETCC);
1099     setTargetDAGCombine(ISD::SELECT_CC);
1100   }
1101 
1102   // Use reciprocal estimates.
1103   if (TM.Options.UnsafeFPMath) {
1104     setTargetDAGCombine(ISD::FDIV);
1105     setTargetDAGCombine(ISD::FSQRT);
1106   }
1107 
1108   if (Subtarget.hasP9Altivec()) {
1109     setTargetDAGCombine(ISD::ABS);
1110     setTargetDAGCombine(ISD::VSELECT);
1111   }
1112 
1113   // Darwin long double math library functions have $LDBL128 appended.
1114   if (Subtarget.isDarwin()) {
1115     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1116     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1117     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1118     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1119     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1120     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1121     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1122     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1123     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1124     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1125   }
1126 
1127   if (EnableQuadPrecision) {
1128     setLibcallName(RTLIB::LOG_F128, "logf128");
1129     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1130     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1131     setLibcallName(RTLIB::EXP_F128, "expf128");
1132     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1133     setLibcallName(RTLIB::SIN_F128, "sinf128");
1134     setLibcallName(RTLIB::COS_F128, "cosf128");
1135     setLibcallName(RTLIB::POW_F128, "powf128");
1136     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1137     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1138     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1139     setLibcallName(RTLIB::REM_F128, "fmodf128");
1140   }
1141 
1142   // With 32 condition bits, we don't need to sink (and duplicate) compares
1143   // aggressively in CodeGenPrep.
1144   if (Subtarget.useCRBits()) {
1145     setHasMultipleConditionRegisters();
1146     setJumpIsExpensive();
1147   }
1148 
1149   setMinFunctionAlignment(2);
1150   if (Subtarget.isDarwin())
1151     setPrefFunctionAlignment(4);
1152 
1153   switch (Subtarget.getDarwinDirective()) {
1154   default: break;
1155   case PPC::DIR_970:
1156   case PPC::DIR_A2:
1157   case PPC::DIR_E500:
1158   case PPC::DIR_E500mc:
1159   case PPC::DIR_E5500:
1160   case PPC::DIR_PWR4:
1161   case PPC::DIR_PWR5:
1162   case PPC::DIR_PWR5X:
1163   case PPC::DIR_PWR6:
1164   case PPC::DIR_PWR6X:
1165   case PPC::DIR_PWR7:
1166   case PPC::DIR_PWR8:
1167   case PPC::DIR_PWR9:
1168     setPrefFunctionAlignment(4);
1169     setPrefLoopAlignment(4);
1170     break;
1171   }
1172 
1173   if (Subtarget.enableMachineScheduler())
1174     setSchedulingPreference(Sched::Source);
1175   else
1176     setSchedulingPreference(Sched::Hybrid);
1177 
1178   computeRegisterProperties(STI.getRegisterInfo());
1179 
1180   // The Freescale cores do better with aggressive inlining of memcpy and
1181   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1182   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1183       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1184     MaxStoresPerMemset = 32;
1185     MaxStoresPerMemsetOptSize = 16;
1186     MaxStoresPerMemcpy = 32;
1187     MaxStoresPerMemcpyOptSize = 8;
1188     MaxStoresPerMemmove = 32;
1189     MaxStoresPerMemmoveOptSize = 8;
1190   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1191     // The A2 also benefits from (very) aggressive inlining of memcpy and
1192     // friends. The overhead of a the function call, even when warm, can be
1193     // over one hundred cycles.
1194     MaxStoresPerMemset = 128;
1195     MaxStoresPerMemcpy = 128;
1196     MaxStoresPerMemmove = 128;
1197     MaxLoadsPerMemcmp = 128;
1198   } else {
1199     MaxLoadsPerMemcmp = 8;
1200     MaxLoadsPerMemcmpOptSize = 4;
1201   }
1202 }
1203 
1204 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1205 /// the desired ByVal argument alignment.
1206 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1207                              unsigned MaxMaxAlign) {
1208   if (MaxAlign == MaxMaxAlign)
1209     return;
1210   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1211     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1212       MaxAlign = 32;
1213     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1214       MaxAlign = 16;
1215   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1216     unsigned EltAlign = 0;
1217     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1218     if (EltAlign > MaxAlign)
1219       MaxAlign = EltAlign;
1220   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1221     for (auto *EltTy : STy->elements()) {
1222       unsigned EltAlign = 0;
1223       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1224       if (EltAlign > MaxAlign)
1225         MaxAlign = EltAlign;
1226       if (MaxAlign == MaxMaxAlign)
1227         break;
1228     }
1229   }
1230 }
1231 
1232 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1233 /// function arguments in the caller parameter area.
1234 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1235                                                   const DataLayout &DL) const {
1236   // Darwin passes everything on 4 byte boundary.
1237   if (Subtarget.isDarwin())
1238     return 4;
1239 
1240   // 16byte and wider vectors are passed on 16byte boundary.
1241   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1242   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1243   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1244     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1245   return Align;
1246 }
1247 
1248 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1249                                                           CallingConv:: ID CC,
1250                                                           EVT VT) const {
1251   if (Subtarget.hasSPE() && VT == MVT::f64)
1252     return 2;
1253   return PPCTargetLowering::getNumRegisters(Context, VT);
1254 }
1255 
1256 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1257                                                      CallingConv:: ID CC,
1258                                                      EVT VT) const {
1259   if (Subtarget.hasSPE() && VT == MVT::f64)
1260     return MVT::i32;
1261   return PPCTargetLowering::getRegisterType(Context, VT);
1262 }
1263 
1264 bool PPCTargetLowering::useSoftFloat() const {
1265   return Subtarget.useSoftFloat();
1266 }
1267 
1268 bool PPCTargetLowering::hasSPE() const {
1269   return Subtarget.hasSPE();
1270 }
1271 
1272 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1273   switch ((PPCISD::NodeType)Opcode) {
1274   case PPCISD::FIRST_NUMBER:    break;
1275   case PPCISD::FSEL:            return "PPCISD::FSEL";
1276   case PPCISD::FCFID:           return "PPCISD::FCFID";
1277   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1278   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1279   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1280   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1281   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1282   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1283   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1284   case PPCISD::FP_TO_UINT_IN_VSR:
1285                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1286   case PPCISD::FP_TO_SINT_IN_VSR:
1287                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1288   case PPCISD::FRE:             return "PPCISD::FRE";
1289   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1290   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1291   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1292   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1293   case PPCISD::VPERM:           return "PPCISD::VPERM";
1294   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1295   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1296   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1297   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1298   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1299   case PPCISD::CMPB:            return "PPCISD::CMPB";
1300   case PPCISD::Hi:              return "PPCISD::Hi";
1301   case PPCISD::Lo:              return "PPCISD::Lo";
1302   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1303   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1304   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1305   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1306   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1307   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1308   case PPCISD::SRL:             return "PPCISD::SRL";
1309   case PPCISD::SRA:             return "PPCISD::SRA";
1310   case PPCISD::SHL:             return "PPCISD::SHL";
1311   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1312   case PPCISD::CALL:            return "PPCISD::CALL";
1313   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1314   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1315   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1316   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1317   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1318   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1319   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1320   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1321   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1322   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1323   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1324   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1325   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1326   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1327   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1328   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1329   case PPCISD::VCMP:            return "PPCISD::VCMP";
1330   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1331   case PPCISD::LBRX:            return "PPCISD::LBRX";
1332   case PPCISD::STBRX:           return "PPCISD::STBRX";
1333   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1334   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1335   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1336   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1337   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1338   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1339   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1340   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1341   case PPCISD::ST_VSR_SCAL_INT:
1342                                 return "PPCISD::ST_VSR_SCAL_INT";
1343   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1344   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1345   case PPCISD::BDZ:             return "PPCISD::BDZ";
1346   case PPCISD::MFFS:            return "PPCISD::MFFS";
1347   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1348   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1349   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1350   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1351   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1352   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1353   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1354   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1355   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1356   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1357   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1358   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1359   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1360   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1361   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1362   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1363   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1364   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1365   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1366   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1367   case PPCISD::SC:              return "PPCISD::SC";
1368   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1369   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1370   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1371   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1372   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1373   case PPCISD::VABSD:           return "PPCISD::VABSD";
1374   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1375   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1376   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1377   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1378   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1379   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1380   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1381   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1382   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1383   case PPCISD::FP_EXTEND_LH:    return "PPCISD::FP_EXTEND_LH";
1384   }
1385   return nullptr;
1386 }
1387 
1388 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1389                                           EVT VT) const {
1390   if (!VT.isVector())
1391     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1392 
1393   if (Subtarget.hasQPX())
1394     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1395 
1396   return VT.changeVectorElementTypeToInteger();
1397 }
1398 
1399 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1400   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1401   return true;
1402 }
1403 
1404 //===----------------------------------------------------------------------===//
1405 // Node matching predicates, for use by the tblgen matching code.
1406 //===----------------------------------------------------------------------===//
1407 
1408 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1409 static bool isFloatingPointZero(SDValue Op) {
1410   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1411     return CFP->getValueAPF().isZero();
1412   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1413     // Maybe this has already been legalized into the constant pool?
1414     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1415       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1416         return CFP->getValueAPF().isZero();
1417   }
1418   return false;
1419 }
1420 
1421 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1422 /// true if Op is undef or if it matches the specified value.
1423 static bool isConstantOrUndef(int Op, int Val) {
1424   return Op < 0 || Op == Val;
1425 }
1426 
1427 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1428 /// VPKUHUM instruction.
1429 /// The ShuffleKind distinguishes between big-endian operations with
1430 /// two different inputs (0), either-endian operations with two identical
1431 /// inputs (1), and little-endian operations with two different inputs (2).
1432 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1433 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1434                                SelectionDAG &DAG) {
1435   bool IsLE = DAG.getDataLayout().isLittleEndian();
1436   if (ShuffleKind == 0) {
1437     if (IsLE)
1438       return false;
1439     for (unsigned i = 0; i != 16; ++i)
1440       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1441         return false;
1442   } else if (ShuffleKind == 2) {
1443     if (!IsLE)
1444       return false;
1445     for (unsigned i = 0; i != 16; ++i)
1446       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1447         return false;
1448   } else if (ShuffleKind == 1) {
1449     unsigned j = IsLE ? 0 : 1;
1450     for (unsigned i = 0; i != 8; ++i)
1451       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1452           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1453         return false;
1454   }
1455   return true;
1456 }
1457 
1458 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1459 /// VPKUWUM instruction.
1460 /// The ShuffleKind distinguishes between big-endian operations with
1461 /// two different inputs (0), either-endian operations with two identical
1462 /// inputs (1), and little-endian operations with two different inputs (2).
1463 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1464 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1465                                SelectionDAG &DAG) {
1466   bool IsLE = DAG.getDataLayout().isLittleEndian();
1467   if (ShuffleKind == 0) {
1468     if (IsLE)
1469       return false;
1470     for (unsigned i = 0; i != 16; i += 2)
1471       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1472           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1473         return false;
1474   } else if (ShuffleKind == 2) {
1475     if (!IsLE)
1476       return false;
1477     for (unsigned i = 0; i != 16; i += 2)
1478       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1479           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1480         return false;
1481   } else if (ShuffleKind == 1) {
1482     unsigned j = IsLE ? 0 : 2;
1483     for (unsigned i = 0; i != 8; i += 2)
1484       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1485           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1486           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1487           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1488         return false;
1489   }
1490   return true;
1491 }
1492 
1493 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1494 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1495 /// current subtarget.
1496 ///
1497 /// The ShuffleKind distinguishes between big-endian operations with
1498 /// two different inputs (0), either-endian operations with two identical
1499 /// inputs (1), and little-endian operations with two different inputs (2).
1500 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1501 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1502                                SelectionDAG &DAG) {
1503   const PPCSubtarget& Subtarget =
1504     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1505   if (!Subtarget.hasP8Vector())
1506     return false;
1507 
1508   bool IsLE = DAG.getDataLayout().isLittleEndian();
1509   if (ShuffleKind == 0) {
1510     if (IsLE)
1511       return false;
1512     for (unsigned i = 0; i != 16; i += 4)
1513       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1514           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1515           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1516           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1517         return false;
1518   } else if (ShuffleKind == 2) {
1519     if (!IsLE)
1520       return false;
1521     for (unsigned i = 0; i != 16; i += 4)
1522       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1523           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1524           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1525           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1526         return false;
1527   } else if (ShuffleKind == 1) {
1528     unsigned j = IsLE ? 0 : 4;
1529     for (unsigned i = 0; i != 8; i += 4)
1530       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1531           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1532           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1533           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1534           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1535           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1536           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1537           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1538         return false;
1539   }
1540   return true;
1541 }
1542 
1543 /// isVMerge - Common function, used to match vmrg* shuffles.
1544 ///
1545 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1546                      unsigned LHSStart, unsigned RHSStart) {
1547   if (N->getValueType(0) != MVT::v16i8)
1548     return false;
1549   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1550          "Unsupported merge size!");
1551 
1552   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1553     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1554       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1555                              LHSStart+j+i*UnitSize) ||
1556           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1557                              RHSStart+j+i*UnitSize))
1558         return false;
1559     }
1560   return true;
1561 }
1562 
1563 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1564 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1565 /// The ShuffleKind distinguishes between big-endian merges with two
1566 /// different inputs (0), either-endian merges with two identical inputs (1),
1567 /// and little-endian merges with two different inputs (2).  For the latter,
1568 /// the input operands are swapped (see PPCInstrAltivec.td).
1569 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1570                              unsigned ShuffleKind, SelectionDAG &DAG) {
1571   if (DAG.getDataLayout().isLittleEndian()) {
1572     if (ShuffleKind == 1) // unary
1573       return isVMerge(N, UnitSize, 0, 0);
1574     else if (ShuffleKind == 2) // swapped
1575       return isVMerge(N, UnitSize, 0, 16);
1576     else
1577       return false;
1578   } else {
1579     if (ShuffleKind == 1) // unary
1580       return isVMerge(N, UnitSize, 8, 8);
1581     else if (ShuffleKind == 0) // normal
1582       return isVMerge(N, UnitSize, 8, 24);
1583     else
1584       return false;
1585   }
1586 }
1587 
1588 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1589 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1590 /// The ShuffleKind distinguishes between big-endian merges with two
1591 /// different inputs (0), either-endian merges with two identical inputs (1),
1592 /// and little-endian merges with two different inputs (2).  For the latter,
1593 /// the input operands are swapped (see PPCInstrAltivec.td).
1594 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1595                              unsigned ShuffleKind, SelectionDAG &DAG) {
1596   if (DAG.getDataLayout().isLittleEndian()) {
1597     if (ShuffleKind == 1) // unary
1598       return isVMerge(N, UnitSize, 8, 8);
1599     else if (ShuffleKind == 2) // swapped
1600       return isVMerge(N, UnitSize, 8, 24);
1601     else
1602       return false;
1603   } else {
1604     if (ShuffleKind == 1) // unary
1605       return isVMerge(N, UnitSize, 0, 0);
1606     else if (ShuffleKind == 0) // normal
1607       return isVMerge(N, UnitSize, 0, 16);
1608     else
1609       return false;
1610   }
1611 }
1612 
1613 /**
1614  * Common function used to match vmrgew and vmrgow shuffles
1615  *
1616  * The indexOffset determines whether to look for even or odd words in
1617  * the shuffle mask. This is based on the of the endianness of the target
1618  * machine.
1619  *   - Little Endian:
1620  *     - Use offset of 0 to check for odd elements
1621  *     - Use offset of 4 to check for even elements
1622  *   - Big Endian:
1623  *     - Use offset of 0 to check for even elements
1624  *     - Use offset of 4 to check for odd elements
1625  * A detailed description of the vector element ordering for little endian and
1626  * big endian can be found at
1627  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1628  * Targeting your applications - what little endian and big endian IBM XL C/C++
1629  * compiler differences mean to you
1630  *
1631  * The mask to the shuffle vector instruction specifies the indices of the
1632  * elements from the two input vectors to place in the result. The elements are
1633  * numbered in array-access order, starting with the first vector. These vectors
1634  * are always of type v16i8, thus each vector will contain 16 elements of size
1635  * 8. More info on the shuffle vector can be found in the
1636  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1637  * Language Reference.
1638  *
1639  * The RHSStartValue indicates whether the same input vectors are used (unary)
1640  * or two different input vectors are used, based on the following:
1641  *   - If the instruction uses the same vector for both inputs, the range of the
1642  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1643  *     be 0.
1644  *   - If the instruction has two different vectors then the range of the
1645  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1646  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1647  *     to 31 specify elements in the second vector).
1648  *
1649  * \param[in] N The shuffle vector SD Node to analyze
1650  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1651  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1652  * vector to the shuffle_vector instruction
1653  * \return true iff this shuffle vector represents an even or odd word merge
1654  */
1655 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1656                      unsigned RHSStartValue) {
1657   if (N->getValueType(0) != MVT::v16i8)
1658     return false;
1659 
1660   for (unsigned i = 0; i < 2; ++i)
1661     for (unsigned j = 0; j < 4; ++j)
1662       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1663                              i*RHSStartValue+j+IndexOffset) ||
1664           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1665                              i*RHSStartValue+j+IndexOffset+8))
1666         return false;
1667   return true;
1668 }
1669 
1670 /**
1671  * Determine if the specified shuffle mask is suitable for the vmrgew or
1672  * vmrgow instructions.
1673  *
1674  * \param[in] N The shuffle vector SD Node to analyze
1675  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1676  * \param[in] ShuffleKind Identify the type of merge:
1677  *   - 0 = big-endian merge with two different inputs;
1678  *   - 1 = either-endian merge with two identical inputs;
1679  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1680  *     little-endian merges).
1681  * \param[in] DAG The current SelectionDAG
1682  * \return true iff this shuffle mask
1683  */
1684 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1685                               unsigned ShuffleKind, SelectionDAG &DAG) {
1686   if (DAG.getDataLayout().isLittleEndian()) {
1687     unsigned indexOffset = CheckEven ? 4 : 0;
1688     if (ShuffleKind == 1) // Unary
1689       return isVMerge(N, indexOffset, 0);
1690     else if (ShuffleKind == 2) // swapped
1691       return isVMerge(N, indexOffset, 16);
1692     else
1693       return false;
1694   }
1695   else {
1696     unsigned indexOffset = CheckEven ? 0 : 4;
1697     if (ShuffleKind == 1) // Unary
1698       return isVMerge(N, indexOffset, 0);
1699     else if (ShuffleKind == 0) // Normal
1700       return isVMerge(N, indexOffset, 16);
1701     else
1702       return false;
1703   }
1704   return false;
1705 }
1706 
1707 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1708 /// amount, otherwise return -1.
1709 /// The ShuffleKind distinguishes between big-endian operations with two
1710 /// different inputs (0), either-endian operations with two identical inputs
1711 /// (1), and little-endian operations with two different inputs (2).  For the
1712 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1713 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1714                              SelectionDAG &DAG) {
1715   if (N->getValueType(0) != MVT::v16i8)
1716     return -1;
1717 
1718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1719 
1720   // Find the first non-undef value in the shuffle mask.
1721   unsigned i;
1722   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1723     /*search*/;
1724 
1725   if (i == 16) return -1;  // all undef.
1726 
1727   // Otherwise, check to see if the rest of the elements are consecutively
1728   // numbered from this value.
1729   unsigned ShiftAmt = SVOp->getMaskElt(i);
1730   if (ShiftAmt < i) return -1;
1731 
1732   ShiftAmt -= i;
1733   bool isLE = DAG.getDataLayout().isLittleEndian();
1734 
1735   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1736     // Check the rest of the elements to see if they are consecutive.
1737     for (++i; i != 16; ++i)
1738       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1739         return -1;
1740   } else if (ShuffleKind == 1) {
1741     // Check the rest of the elements to see if they are consecutive.
1742     for (++i; i != 16; ++i)
1743       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1744         return -1;
1745   } else
1746     return -1;
1747 
1748   if (isLE)
1749     ShiftAmt = 16 - ShiftAmt;
1750 
1751   return ShiftAmt;
1752 }
1753 
1754 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1755 /// specifies a splat of a single element that is suitable for input to
1756 /// VSPLTB/VSPLTH/VSPLTW.
1757 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1758   assert(N->getValueType(0) == MVT::v16i8 &&
1759          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1760 
1761   // The consecutive indices need to specify an element, not part of two
1762   // different elements.  So abandon ship early if this isn't the case.
1763   if (N->getMaskElt(0) % EltSize != 0)
1764     return false;
1765 
1766   // This is a splat operation if each element of the permute is the same, and
1767   // if the value doesn't reference the second vector.
1768   unsigned ElementBase = N->getMaskElt(0);
1769 
1770   // FIXME: Handle UNDEF elements too!
1771   if (ElementBase >= 16)
1772     return false;
1773 
1774   // Check that the indices are consecutive, in the case of a multi-byte element
1775   // splatted with a v16i8 mask.
1776   for (unsigned i = 1; i != EltSize; ++i)
1777     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1778       return false;
1779 
1780   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1781     if (N->getMaskElt(i) < 0) continue;
1782     for (unsigned j = 0; j != EltSize; ++j)
1783       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1784         return false;
1785   }
1786   return true;
1787 }
1788 
1789 /// Check that the mask is shuffling N byte elements. Within each N byte
1790 /// element of the mask, the indices could be either in increasing or
1791 /// decreasing order as long as they are consecutive.
1792 /// \param[in] N the shuffle vector SD Node to analyze
1793 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1794 /// Word/DoubleWord/QuadWord).
1795 /// \param[in] StepLen the delta indices number among the N byte element, if
1796 /// the mask is in increasing/decreasing order then it is 1/-1.
1797 /// \return true iff the mask is shuffling N byte elements.
1798 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1799                                    int StepLen) {
1800   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1801          "Unexpected element width.");
1802   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1803 
1804   unsigned NumOfElem = 16 / Width;
1805   unsigned MaskVal[16]; //  Width is never greater than 16
1806   for (unsigned i = 0; i < NumOfElem; ++i) {
1807     MaskVal[0] = N->getMaskElt(i * Width);
1808     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1809       return false;
1810     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1811       return false;
1812     }
1813 
1814     for (unsigned int j = 1; j < Width; ++j) {
1815       MaskVal[j] = N->getMaskElt(i * Width + j);
1816       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1817         return false;
1818       }
1819     }
1820   }
1821 
1822   return true;
1823 }
1824 
1825 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1826                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1827   if (!isNByteElemShuffleMask(N, 4, 1))
1828     return false;
1829 
1830   // Now we look at mask elements 0,4,8,12
1831   unsigned M0 = N->getMaskElt(0) / 4;
1832   unsigned M1 = N->getMaskElt(4) / 4;
1833   unsigned M2 = N->getMaskElt(8) / 4;
1834   unsigned M3 = N->getMaskElt(12) / 4;
1835   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1836   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1837 
1838   // Below, let H and L be arbitrary elements of the shuffle mask
1839   // where H is in the range [4,7] and L is in the range [0,3].
1840   // H, 1, 2, 3 or L, 5, 6, 7
1841   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1842       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1843     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1844     InsertAtByte = IsLE ? 12 : 0;
1845     Swap = M0 < 4;
1846     return true;
1847   }
1848   // 0, H, 2, 3 or 4, L, 6, 7
1849   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1850       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1851     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1852     InsertAtByte = IsLE ? 8 : 4;
1853     Swap = M1 < 4;
1854     return true;
1855   }
1856   // 0, 1, H, 3 or 4, 5, L, 7
1857   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1858       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1859     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1860     InsertAtByte = IsLE ? 4 : 8;
1861     Swap = M2 < 4;
1862     return true;
1863   }
1864   // 0, 1, 2, H or 4, 5, 6, L
1865   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1866       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1867     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1868     InsertAtByte = IsLE ? 0 : 12;
1869     Swap = M3 < 4;
1870     return true;
1871   }
1872 
1873   // If both vector operands for the shuffle are the same vector, the mask will
1874   // contain only elements from the first one and the second one will be undef.
1875   if (N->getOperand(1).isUndef()) {
1876     ShiftElts = 0;
1877     Swap = true;
1878     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1879     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1880       InsertAtByte = IsLE ? 12 : 0;
1881       return true;
1882     }
1883     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1884       InsertAtByte = IsLE ? 8 : 4;
1885       return true;
1886     }
1887     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1888       InsertAtByte = IsLE ? 4 : 8;
1889       return true;
1890     }
1891     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1892       InsertAtByte = IsLE ? 0 : 12;
1893       return true;
1894     }
1895   }
1896 
1897   return false;
1898 }
1899 
1900 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1901                                bool &Swap, bool IsLE) {
1902   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1903   // Ensure each byte index of the word is consecutive.
1904   if (!isNByteElemShuffleMask(N, 4, 1))
1905     return false;
1906 
1907   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1908   unsigned M0 = N->getMaskElt(0) / 4;
1909   unsigned M1 = N->getMaskElt(4) / 4;
1910   unsigned M2 = N->getMaskElt(8) / 4;
1911   unsigned M3 = N->getMaskElt(12) / 4;
1912 
1913   // If both vector operands for the shuffle are the same vector, the mask will
1914   // contain only elements from the first one and the second one will be undef.
1915   if (N->getOperand(1).isUndef()) {
1916     assert(M0 < 4 && "Indexing into an undef vector?");
1917     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1918       return false;
1919 
1920     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1921     Swap = false;
1922     return true;
1923   }
1924 
1925   // Ensure each word index of the ShuffleVector Mask is consecutive.
1926   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1927     return false;
1928 
1929   if (IsLE) {
1930     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1931       // Input vectors don't need to be swapped if the leading element
1932       // of the result is one of the 3 left elements of the second vector
1933       // (or if there is no shift to be done at all).
1934       Swap = false;
1935       ShiftElts = (8 - M0) % 8;
1936     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1937       // Input vectors need to be swapped if the leading element
1938       // of the result is one of the 3 left elements of the first vector
1939       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1940       Swap = true;
1941       ShiftElts = (4 - M0) % 4;
1942     }
1943 
1944     return true;
1945   } else {                                          // BE
1946     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1947       // Input vectors don't need to be swapped if the leading element
1948       // of the result is one of the 4 elements of the first vector.
1949       Swap = false;
1950       ShiftElts = M0;
1951     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1952       // Input vectors need to be swapped if the leading element
1953       // of the result is one of the 4 elements of the right vector.
1954       Swap = true;
1955       ShiftElts = M0 - 4;
1956     }
1957 
1958     return true;
1959   }
1960 }
1961 
1962 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1963   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1964 
1965   if (!isNByteElemShuffleMask(N, Width, -1))
1966     return false;
1967 
1968   for (int i = 0; i < 16; i += Width)
1969     if (N->getMaskElt(i) != i + Width - 1)
1970       return false;
1971 
1972   return true;
1973 }
1974 
1975 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1976   return isXXBRShuffleMaskHelper(N, 2);
1977 }
1978 
1979 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1980   return isXXBRShuffleMaskHelper(N, 4);
1981 }
1982 
1983 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1984   return isXXBRShuffleMaskHelper(N, 8);
1985 }
1986 
1987 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1988   return isXXBRShuffleMaskHelper(N, 16);
1989 }
1990 
1991 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1992 /// if the inputs to the instruction should be swapped and set \p DM to the
1993 /// value for the immediate.
1994 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1995 /// AND element 0 of the result comes from the first input (LE) or second input
1996 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1997 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1998 /// mask.
1999 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2000                                bool &Swap, bool IsLE) {
2001   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2002 
2003   // Ensure each byte index of the double word is consecutive.
2004   if (!isNByteElemShuffleMask(N, 8, 1))
2005     return false;
2006 
2007   unsigned M0 = N->getMaskElt(0) / 8;
2008   unsigned M1 = N->getMaskElt(8) / 8;
2009   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2010 
2011   // If both vector operands for the shuffle are the same vector, the mask will
2012   // contain only elements from the first one and the second one will be undef.
2013   if (N->getOperand(1).isUndef()) {
2014     if ((M0 | M1) < 2) {
2015       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2016       Swap = false;
2017       return true;
2018     } else
2019       return false;
2020   }
2021 
2022   if (IsLE) {
2023     if (M0 > 1 && M1 < 2) {
2024       Swap = false;
2025     } else if (M0 < 2 && M1 > 1) {
2026       M0 = (M0 + 2) % 4;
2027       M1 = (M1 + 2) % 4;
2028       Swap = true;
2029     } else
2030       return false;
2031 
2032     // Note: if control flow comes here that means Swap is already set above
2033     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2034     return true;
2035   } else { // BE
2036     if (M0 < 2 && M1 > 1) {
2037       Swap = false;
2038     } else if (M0 > 1 && M1 < 2) {
2039       M0 = (M0 + 2) % 4;
2040       M1 = (M1 + 2) % 4;
2041       Swap = true;
2042     } else
2043       return false;
2044 
2045     // Note: if control flow comes here that means Swap is already set above
2046     DM = (M0 << 1) + (M1 & 1);
2047     return true;
2048   }
2049 }
2050 
2051 
2052 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2053 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2054 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2055                                 SelectionDAG &DAG) {
2056   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2057   assert(isSplatShuffleMask(SVOp, EltSize));
2058   if (DAG.getDataLayout().isLittleEndian())
2059     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2060   else
2061     return SVOp->getMaskElt(0) / EltSize;
2062 }
2063 
2064 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2065 /// by using a vspltis[bhw] instruction of the specified element size, return
2066 /// the constant being splatted.  The ByteSize field indicates the number of
2067 /// bytes of each element [124] -> [bhw].
2068 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2069   SDValue OpVal(nullptr, 0);
2070 
2071   // If ByteSize of the splat is bigger than the element size of the
2072   // build_vector, then we have a case where we are checking for a splat where
2073   // multiple elements of the buildvector are folded together into a single
2074   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2075   unsigned EltSize = 16/N->getNumOperands();
2076   if (EltSize < ByteSize) {
2077     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2078     SDValue UniquedVals[4];
2079     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2080 
2081     // See if all of the elements in the buildvector agree across.
2082     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2083       if (N->getOperand(i).isUndef()) continue;
2084       // If the element isn't a constant, bail fully out.
2085       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2086 
2087       if (!UniquedVals[i&(Multiple-1)].getNode())
2088         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2089       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2090         return SDValue();  // no match.
2091     }
2092 
2093     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2094     // either constant or undef values that are identical for each chunk.  See
2095     // if these chunks can form into a larger vspltis*.
2096 
2097     // Check to see if all of the leading entries are either 0 or -1.  If
2098     // neither, then this won't fit into the immediate field.
2099     bool LeadingZero = true;
2100     bool LeadingOnes = true;
2101     for (unsigned i = 0; i != Multiple-1; ++i) {
2102       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2103 
2104       LeadingZero &= isNullConstant(UniquedVals[i]);
2105       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2106     }
2107     // Finally, check the least significant entry.
2108     if (LeadingZero) {
2109       if (!UniquedVals[Multiple-1].getNode())
2110         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2111       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2112       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2113         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2114     }
2115     if (LeadingOnes) {
2116       if (!UniquedVals[Multiple-1].getNode())
2117         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2118       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2119       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2120         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2121     }
2122 
2123     return SDValue();
2124   }
2125 
2126   // Check to see if this buildvec has a single non-undef value in its elements.
2127   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2128     if (N->getOperand(i).isUndef()) continue;
2129     if (!OpVal.getNode())
2130       OpVal = N->getOperand(i);
2131     else if (OpVal != N->getOperand(i))
2132       return SDValue();
2133   }
2134 
2135   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2136 
2137   unsigned ValSizeInBytes = EltSize;
2138   uint64_t Value = 0;
2139   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2140     Value = CN->getZExtValue();
2141   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2142     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2143     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2144   }
2145 
2146   // If the splat value is larger than the element value, then we can never do
2147   // this splat.  The only case that we could fit the replicated bits into our
2148   // immediate field for would be zero, and we prefer to use vxor for it.
2149   if (ValSizeInBytes < ByteSize) return SDValue();
2150 
2151   // If the element value is larger than the splat value, check if it consists
2152   // of a repeated bit pattern of size ByteSize.
2153   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2154     return SDValue();
2155 
2156   // Properly sign extend the value.
2157   int MaskVal = SignExtend32(Value, ByteSize * 8);
2158 
2159   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2160   if (MaskVal == 0) return SDValue();
2161 
2162   // Finally, if this value fits in a 5 bit sext field, return it
2163   if (SignExtend32<5>(MaskVal) == MaskVal)
2164     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2165   return SDValue();
2166 }
2167 
2168 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2169 /// amount, otherwise return -1.
2170 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2171   EVT VT = N->getValueType(0);
2172   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2173     return -1;
2174 
2175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2176 
2177   // Find the first non-undef value in the shuffle mask.
2178   unsigned i;
2179   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2180     /*search*/;
2181 
2182   if (i == 4) return -1;  // all undef.
2183 
2184   // Otherwise, check to see if the rest of the elements are consecutively
2185   // numbered from this value.
2186   unsigned ShiftAmt = SVOp->getMaskElt(i);
2187   if (ShiftAmt < i) return -1;
2188   ShiftAmt -= i;
2189 
2190   // Check the rest of the elements to see if they are consecutive.
2191   for (++i; i != 4; ++i)
2192     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2193       return -1;
2194 
2195   return ShiftAmt;
2196 }
2197 
2198 //===----------------------------------------------------------------------===//
2199 //  Addressing Mode Selection
2200 //===----------------------------------------------------------------------===//
2201 
2202 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2203 /// or 64-bit immediate, and if the value can be accurately represented as a
2204 /// sign extension from a 16-bit value.  If so, this returns true and the
2205 /// immediate.
2206 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2207   if (!isa<ConstantSDNode>(N))
2208     return false;
2209 
2210   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2211   if (N->getValueType(0) == MVT::i32)
2212     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2213   else
2214     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2215 }
2216 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2217   return isIntS16Immediate(Op.getNode(), Imm);
2218 }
2219 
2220 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2221 /// can be represented as an indexed [r+r] operation.  Returns false if it
2222 /// can be more efficiently represented with [r+imm].
2223 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2224                                             SDValue &Index,
2225                                             SelectionDAG &DAG) const {
2226   int16_t imm = 0;
2227   if (N.getOpcode() == ISD::ADD) {
2228     if (isIntS16Immediate(N.getOperand(1), imm))
2229       return false;    // r+i
2230     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2231       return false;    // r+i
2232 
2233     Base = N.getOperand(0);
2234     Index = N.getOperand(1);
2235     return true;
2236   } else if (N.getOpcode() == ISD::OR) {
2237     if (isIntS16Immediate(N.getOperand(1), imm))
2238       return false;    // r+i can fold it if we can.
2239 
2240     // If this is an or of disjoint bitfields, we can codegen this as an add
2241     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2242     // disjoint.
2243     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2244 
2245     if (LHSKnown.Zero.getBoolValue()) {
2246       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2247       // If all of the bits are known zero on the LHS or RHS, the add won't
2248       // carry.
2249       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2250         Base = N.getOperand(0);
2251         Index = N.getOperand(1);
2252         return true;
2253       }
2254     }
2255   }
2256 
2257   return false;
2258 }
2259 
2260 // If we happen to be doing an i64 load or store into a stack slot that has
2261 // less than a 4-byte alignment, then the frame-index elimination may need to
2262 // use an indexed load or store instruction (because the offset may not be a
2263 // multiple of 4). The extra register needed to hold the offset comes from the
2264 // register scavenger, and it is possible that the scavenger will need to use
2265 // an emergency spill slot. As a result, we need to make sure that a spill slot
2266 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2267 // stack slot.
2268 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2269   // FIXME: This does not handle the LWA case.
2270   if (VT != MVT::i64)
2271     return;
2272 
2273   // NOTE: We'll exclude negative FIs here, which come from argument
2274   // lowering, because there are no known test cases triggering this problem
2275   // using packed structures (or similar). We can remove this exclusion if
2276   // we find such a test case. The reason why this is so test-case driven is
2277   // because this entire 'fixup' is only to prevent crashes (from the
2278   // register scavenger) on not-really-valid inputs. For example, if we have:
2279   //   %a = alloca i1
2280   //   %b = bitcast i1* %a to i64*
2281   //   store i64* a, i64 b
2282   // then the store should really be marked as 'align 1', but is not. If it
2283   // were marked as 'align 1' then the indexed form would have been
2284   // instruction-selected initially, and the problem this 'fixup' is preventing
2285   // won't happen regardless.
2286   if (FrameIdx < 0)
2287     return;
2288 
2289   MachineFunction &MF = DAG.getMachineFunction();
2290   MachineFrameInfo &MFI = MF.getFrameInfo();
2291 
2292   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2293   if (Align >= 4)
2294     return;
2295 
2296   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2297   FuncInfo->setHasNonRISpills();
2298 }
2299 
2300 /// Returns true if the address N can be represented by a base register plus
2301 /// a signed 16-bit displacement [r+imm], and if it is not better
2302 /// represented as reg+reg.  If \p Alignment is non-zero, only accept
2303 /// displacements that are multiples of that value.
2304 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2305                                             SDValue &Base,
2306                                             SelectionDAG &DAG,
2307                                             unsigned Alignment) const {
2308   // FIXME dl should come from parent load or store, not from address
2309   SDLoc dl(N);
2310   // If this can be more profitably realized as r+r, fail.
2311   if (SelectAddressRegReg(N, Disp, Base, DAG))
2312     return false;
2313 
2314   if (N.getOpcode() == ISD::ADD) {
2315     int16_t imm = 0;
2316     if (isIntS16Immediate(N.getOperand(1), imm) &&
2317         (!Alignment || (imm % Alignment) == 0)) {
2318       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2319       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2320         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2321         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2322       } else {
2323         Base = N.getOperand(0);
2324       }
2325       return true; // [r+i]
2326     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2327       // Match LOAD (ADD (X, Lo(G))).
2328       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2329              && "Cannot handle constant offsets yet!");
2330       Disp = N.getOperand(1).getOperand(0);  // The global address.
2331       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2332              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2333              Disp.getOpcode() == ISD::TargetConstantPool ||
2334              Disp.getOpcode() == ISD::TargetJumpTable);
2335       Base = N.getOperand(0);
2336       return true;  // [&g+r]
2337     }
2338   } else if (N.getOpcode() == ISD::OR) {
2339     int16_t imm = 0;
2340     if (isIntS16Immediate(N.getOperand(1), imm) &&
2341         (!Alignment || (imm % Alignment) == 0)) {
2342       // If this is an or of disjoint bitfields, we can codegen this as an add
2343       // (for better address arithmetic) if the LHS and RHS of the OR are
2344       // provably disjoint.
2345       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2346 
2347       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2348         // If all of the bits are known zero on the LHS or RHS, the add won't
2349         // carry.
2350         if (FrameIndexSDNode *FI =
2351               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2352           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2353           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2354         } else {
2355           Base = N.getOperand(0);
2356         }
2357         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2358         return true;
2359       }
2360     }
2361   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2362     // Loading from a constant address.
2363 
2364     // If this address fits entirely in a 16-bit sext immediate field, codegen
2365     // this as "d, 0"
2366     int16_t Imm;
2367     if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2368       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2369       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2370                              CN->getValueType(0));
2371       return true;
2372     }
2373 
2374     // Handle 32-bit sext immediates with LIS + addr mode.
2375     if ((CN->getValueType(0) == MVT::i32 ||
2376          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2377         (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2378       int Addr = (int)CN->getZExtValue();
2379 
2380       // Otherwise, break this down into an LIS + disp.
2381       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2382 
2383       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2384                                    MVT::i32);
2385       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2386       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2387       return true;
2388     }
2389   }
2390 
2391   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2392   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2393     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2394     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2395   } else
2396     Base = N;
2397   return true;      // [r+0]
2398 }
2399 
2400 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2401 /// represented as an indexed [r+r] operation.
2402 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2403                                                 SDValue &Index,
2404                                                 SelectionDAG &DAG) const {
2405   // Check to see if we can easily represent this as an [r+r] address.  This
2406   // will fail if it thinks that the address is more profitably represented as
2407   // reg+imm, e.g. where imm = 0.
2408   if (SelectAddressRegReg(N, Base, Index, DAG))
2409     return true;
2410 
2411   // If the address is the result of an add, we will utilize the fact that the
2412   // address calculation includes an implicit add.  However, we can reduce
2413   // register pressure if we do not materialize a constant just for use as the
2414   // index register.  We only get rid of the add if it is not an add of a
2415   // value and a 16-bit signed constant and both have a single use.
2416   int16_t imm = 0;
2417   if (N.getOpcode() == ISD::ADD &&
2418       (!isIntS16Immediate(N.getOperand(1), imm) ||
2419        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2420     Base = N.getOperand(0);
2421     Index = N.getOperand(1);
2422     return true;
2423   }
2424 
2425   // Otherwise, do it the hard way, using R0 as the base register.
2426   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2427                          N.getValueType());
2428   Index = N;
2429   return true;
2430 }
2431 
2432 /// Returns true if we should use a direct load into vector instruction
2433 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2434 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2435 
2436   // If there are any other uses other than scalar to vector, then we should
2437   // keep it as a scalar load -> direct move pattern to prevent multiple
2438   // loads.
2439   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2440   if (!LD)
2441     return false;
2442 
2443   EVT MemVT = LD->getMemoryVT();
2444   if (!MemVT.isSimple())
2445     return false;
2446   switch(MemVT.getSimpleVT().SimpleTy) {
2447   case MVT::i64:
2448     break;
2449   case MVT::i32:
2450     if (!ST.hasP8Vector())
2451       return false;
2452     break;
2453   case MVT::i16:
2454   case MVT::i8:
2455     if (!ST.hasP9Vector())
2456       return false;
2457     break;
2458   default:
2459     return false;
2460   }
2461 
2462   SDValue LoadedVal(N, 0);
2463   if (!LoadedVal.hasOneUse())
2464     return false;
2465 
2466   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2467        UI != UE; ++UI)
2468     if (UI.getUse().get().getResNo() == 0 &&
2469         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2470       return false;
2471 
2472   return true;
2473 }
2474 
2475 /// getPreIndexedAddressParts - returns true by value, base pointer and
2476 /// offset pointer and addressing mode by reference if the node's address
2477 /// can be legally represented as pre-indexed load / store address.
2478 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2479                                                   SDValue &Offset,
2480                                                   ISD::MemIndexedMode &AM,
2481                                                   SelectionDAG &DAG) const {
2482   if (DisablePPCPreinc) return false;
2483 
2484   bool isLoad = true;
2485   SDValue Ptr;
2486   EVT VT;
2487   unsigned Alignment;
2488   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2489     Ptr = LD->getBasePtr();
2490     VT = LD->getMemoryVT();
2491     Alignment = LD->getAlignment();
2492   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2493     Ptr = ST->getBasePtr();
2494     VT  = ST->getMemoryVT();
2495     Alignment = ST->getAlignment();
2496     isLoad = false;
2497   } else
2498     return false;
2499 
2500   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2501   // instructions because we can fold these into a more efficient instruction
2502   // instead, (such as LXSD).
2503   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2504     return false;
2505   }
2506 
2507   // PowerPC doesn't have preinc load/store instructions for vectors (except
2508   // for QPX, which does have preinc r+r forms).
2509   if (VT.isVector()) {
2510     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2511       return false;
2512     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2513       AM = ISD::PRE_INC;
2514       return true;
2515     }
2516   }
2517 
2518   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2519     // Common code will reject creating a pre-inc form if the base pointer
2520     // is a frame index, or if N is a store and the base pointer is either
2521     // the same as or a predecessor of the value being stored.  Check for
2522     // those situations here, and try with swapped Base/Offset instead.
2523     bool Swap = false;
2524 
2525     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2526       Swap = true;
2527     else if (!isLoad) {
2528       SDValue Val = cast<StoreSDNode>(N)->getValue();
2529       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2530         Swap = true;
2531     }
2532 
2533     if (Swap)
2534       std::swap(Base, Offset);
2535 
2536     AM = ISD::PRE_INC;
2537     return true;
2538   }
2539 
2540   // LDU/STU can only handle immediates that are a multiple of 4.
2541   if (VT != MVT::i64) {
2542     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2543       return false;
2544   } else {
2545     // LDU/STU need an address with at least 4-byte alignment.
2546     if (Alignment < 4)
2547       return false;
2548 
2549     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2550       return false;
2551   }
2552 
2553   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2554     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2555     // sext i32 to i64 when addr mode is r+i.
2556     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2557         LD->getExtensionType() == ISD::SEXTLOAD &&
2558         isa<ConstantSDNode>(Offset))
2559       return false;
2560   }
2561 
2562   AM = ISD::PRE_INC;
2563   return true;
2564 }
2565 
2566 //===----------------------------------------------------------------------===//
2567 //  LowerOperation implementation
2568 //===----------------------------------------------------------------------===//
2569 
2570 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2571 /// and LoOpFlags to the target MO flags.
2572 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2573                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2574                                const GlobalValue *GV = nullptr) {
2575   HiOpFlags = PPCII::MO_HA;
2576   LoOpFlags = PPCII::MO_LO;
2577 
2578   // Don't use the pic base if not in PIC relocation model.
2579   if (IsPIC) {
2580     HiOpFlags |= PPCII::MO_PIC_FLAG;
2581     LoOpFlags |= PPCII::MO_PIC_FLAG;
2582   }
2583 
2584   // If this is a reference to a global value that requires a non-lazy-ptr, make
2585   // sure that instruction lowering adds it.
2586   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2587     HiOpFlags |= PPCII::MO_NLP_FLAG;
2588     LoOpFlags |= PPCII::MO_NLP_FLAG;
2589 
2590     if (GV->hasHiddenVisibility()) {
2591       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2592       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2593     }
2594   }
2595 }
2596 
2597 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2598                              SelectionDAG &DAG) {
2599   SDLoc DL(HiPart);
2600   EVT PtrVT = HiPart.getValueType();
2601   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2602 
2603   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2604   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2605 
2606   // With PIC, the first instruction is actually "GR+hi(&G)".
2607   if (isPIC)
2608     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2609                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2610 
2611   // Generate non-pic code that has direct accesses to the constant pool.
2612   // The address of the global is just (hi(&g)+lo(&g)).
2613   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2614 }
2615 
2616 static void setUsesTOCBasePtr(MachineFunction &MF) {
2617   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2618   FuncInfo->setUsesTOCBasePtr();
2619 }
2620 
2621 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2622   setUsesTOCBasePtr(DAG.getMachineFunction());
2623 }
2624 
2625 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2626                            SDValue GA) {
2627   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2628   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2629                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2630 
2631   SDValue Ops[] = { GA, Reg };
2632   return DAG.getMemIntrinsicNode(
2633       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2634       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2635       MachineMemOperand::MOLoad);
2636 }
2637 
2638 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2639                                              SelectionDAG &DAG) const {
2640   EVT PtrVT = Op.getValueType();
2641   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2642   const Constant *C = CP->getConstVal();
2643 
2644   // 64-bit SVR4 ABI code is always position-independent.
2645   // The actual address of the GlobalValue is stored in the TOC.
2646   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2647     setUsesTOCBasePtr(DAG);
2648     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2649     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2650   }
2651 
2652   unsigned MOHiFlag, MOLoFlag;
2653   bool IsPIC = isPositionIndependent();
2654   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2655 
2656   if (IsPIC && Subtarget.isSVR4ABI()) {
2657     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2658                                            PPCII::MO_PIC_FLAG);
2659     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2660   }
2661 
2662   SDValue CPIHi =
2663     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2664   SDValue CPILo =
2665     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2666   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2667 }
2668 
2669 // For 64-bit PowerPC, prefer the more compact relative encodings.
2670 // This trades 32 bits per jump table entry for one or two instructions
2671 // on the jump site.
2672 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2673   if (isJumpTableRelative())
2674     return MachineJumpTableInfo::EK_LabelDifference32;
2675 
2676   return TargetLowering::getJumpTableEncoding();
2677 }
2678 
2679 bool PPCTargetLowering::isJumpTableRelative() const {
2680   if (Subtarget.isPPC64())
2681     return true;
2682   return TargetLowering::isJumpTableRelative();
2683 }
2684 
2685 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2686                                                     SelectionDAG &DAG) const {
2687   if (!Subtarget.isPPC64())
2688     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2689 
2690   switch (getTargetMachine().getCodeModel()) {
2691   case CodeModel::Small:
2692   case CodeModel::Medium:
2693     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2694   default:
2695     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2696                        getPointerTy(DAG.getDataLayout()));
2697   }
2698 }
2699 
2700 const MCExpr *
2701 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2702                                                 unsigned JTI,
2703                                                 MCContext &Ctx) const {
2704   if (!Subtarget.isPPC64())
2705     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2706 
2707   switch (getTargetMachine().getCodeModel()) {
2708   case CodeModel::Small:
2709   case CodeModel::Medium:
2710     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2711   default:
2712     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2713   }
2714 }
2715 
2716 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2717   EVT PtrVT = Op.getValueType();
2718   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2719 
2720   // 64-bit SVR4 ABI code is always position-independent.
2721   // The actual address of the GlobalValue is stored in the TOC.
2722   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2723     setUsesTOCBasePtr(DAG);
2724     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2725     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2726   }
2727 
2728   unsigned MOHiFlag, MOLoFlag;
2729   bool IsPIC = isPositionIndependent();
2730   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2731 
2732   if (IsPIC && Subtarget.isSVR4ABI()) {
2733     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2734                                         PPCII::MO_PIC_FLAG);
2735     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2736   }
2737 
2738   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2739   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2740   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2741 }
2742 
2743 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2744                                              SelectionDAG &DAG) const {
2745   EVT PtrVT = Op.getValueType();
2746   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2747   const BlockAddress *BA = BASDN->getBlockAddress();
2748 
2749   // 64-bit SVR4 ABI code is always position-independent.
2750   // The actual BlockAddress is stored in the TOC.
2751   if (Subtarget.isSVR4ABI() &&
2752       (Subtarget.isPPC64() || isPositionIndependent())) {
2753     if (Subtarget.isPPC64())
2754       setUsesTOCBasePtr(DAG);
2755     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2756     return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2757   }
2758 
2759   unsigned MOHiFlag, MOLoFlag;
2760   bool IsPIC = isPositionIndependent();
2761   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2762   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2763   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2764   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2765 }
2766 
2767 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2768                                               SelectionDAG &DAG) const {
2769   // FIXME: TLS addresses currently use medium model code sequences,
2770   // which is the most useful form.  Eventually support for small and
2771   // large models could be added if users need it, at the cost of
2772   // additional complexity.
2773   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2774   if (DAG.getTarget().useEmulatedTLS())
2775     return LowerToTLSEmulatedModel(GA, DAG);
2776 
2777   SDLoc dl(GA);
2778   const GlobalValue *GV = GA->getGlobal();
2779   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2780   bool is64bit = Subtarget.isPPC64();
2781   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2782   PICLevel::Level picLevel = M->getPICLevel();
2783 
2784   const TargetMachine &TM = getTargetMachine();
2785   TLSModel::Model Model = TM.getTLSModel(GV);
2786 
2787   if (Model == TLSModel::LocalExec) {
2788     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2789                                                PPCII::MO_TPREL_HA);
2790     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2791                                                PPCII::MO_TPREL_LO);
2792     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2793                              : DAG.getRegister(PPC::R2, MVT::i32);
2794 
2795     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2796     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2797   }
2798 
2799   if (Model == TLSModel::InitialExec) {
2800     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2801     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2802                                                 PPCII::MO_TLS);
2803     SDValue GOTPtr;
2804     if (is64bit) {
2805       setUsesTOCBasePtr(DAG);
2806       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2807       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2808                            PtrVT, GOTReg, TGA);
2809     } else {
2810       if (!TM.isPositionIndependent())
2811         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2812       else if (picLevel == PICLevel::SmallPIC)
2813         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2814       else
2815         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2816     }
2817     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2818                                    PtrVT, TGA, GOTPtr);
2819     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2820   }
2821 
2822   if (Model == TLSModel::GeneralDynamic) {
2823     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2824     SDValue GOTPtr;
2825     if (is64bit) {
2826       setUsesTOCBasePtr(DAG);
2827       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2828       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2829                                    GOTReg, TGA);
2830     } else {
2831       if (picLevel == PICLevel::SmallPIC)
2832         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2833       else
2834         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2835     }
2836     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2837                        GOTPtr, TGA, TGA);
2838   }
2839 
2840   if (Model == TLSModel::LocalDynamic) {
2841     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2842     SDValue GOTPtr;
2843     if (is64bit) {
2844       setUsesTOCBasePtr(DAG);
2845       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2846       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2847                            GOTReg, TGA);
2848     } else {
2849       if (picLevel == PICLevel::SmallPIC)
2850         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2851       else
2852         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2853     }
2854     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2855                                   PtrVT, GOTPtr, TGA, TGA);
2856     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2857                                       PtrVT, TLSAddr, TGA);
2858     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2859   }
2860 
2861   llvm_unreachable("Unknown TLS model!");
2862 }
2863 
2864 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2865                                               SelectionDAG &DAG) const {
2866   EVT PtrVT = Op.getValueType();
2867   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2868   SDLoc DL(GSDN);
2869   const GlobalValue *GV = GSDN->getGlobal();
2870 
2871   // 64-bit SVR4 ABI code is always position-independent.
2872   // The actual address of the GlobalValue is stored in the TOC.
2873   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2874     setUsesTOCBasePtr(DAG);
2875     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2876     return getTOCEntry(DAG, DL, true, GA);
2877   }
2878 
2879   unsigned MOHiFlag, MOLoFlag;
2880   bool IsPIC = isPositionIndependent();
2881   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2882 
2883   if (IsPIC && Subtarget.isSVR4ABI()) {
2884     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2885                                             GSDN->getOffset(),
2886                                             PPCII::MO_PIC_FLAG);
2887     return getTOCEntry(DAG, DL, false, GA);
2888   }
2889 
2890   SDValue GAHi =
2891     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2892   SDValue GALo =
2893     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2894 
2895   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2896 
2897   // If the global reference is actually to a non-lazy-pointer, we have to do an
2898   // extra load to get the address of the global.
2899   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2900     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2901   return Ptr;
2902 }
2903 
2904 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2905   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2906   SDLoc dl(Op);
2907 
2908   if (Op.getValueType() == MVT::v2i64) {
2909     // When the operands themselves are v2i64 values, we need to do something
2910     // special because VSX has no underlying comparison operations for these.
2911     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2912       // Equality can be handled by casting to the legal type for Altivec
2913       // comparisons, everything else needs to be expanded.
2914       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2915         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2916                  DAG.getSetCC(dl, MVT::v4i32,
2917                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2918                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2919                    CC));
2920       }
2921 
2922       return SDValue();
2923     }
2924 
2925     // We handle most of these in the usual way.
2926     return Op;
2927   }
2928 
2929   // If we're comparing for equality to zero, expose the fact that this is
2930   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2931   // fold the new nodes.
2932   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2933     return V;
2934 
2935   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2936     // Leave comparisons against 0 and -1 alone for now, since they're usually
2937     // optimized.  FIXME: revisit this when we can custom lower all setcc
2938     // optimizations.
2939     if (C->isAllOnesValue() || C->isNullValue())
2940       return SDValue();
2941   }
2942 
2943   // If we have an integer seteq/setne, turn it into a compare against zero
2944   // by xor'ing the rhs with the lhs, which is faster than setting a
2945   // condition register, reading it back out, and masking the correct bit.  The
2946   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2947   // the result to other bit-twiddling opportunities.
2948   EVT LHSVT = Op.getOperand(0).getValueType();
2949   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2950     EVT VT = Op.getValueType();
2951     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2952                                 Op.getOperand(1));
2953     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2954   }
2955   return SDValue();
2956 }
2957 
2958 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2959   SDNode *Node = Op.getNode();
2960   EVT VT = Node->getValueType(0);
2961   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2962   SDValue InChain = Node->getOperand(0);
2963   SDValue VAListPtr = Node->getOperand(1);
2964   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2965   SDLoc dl(Node);
2966 
2967   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2968 
2969   // gpr_index
2970   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2971                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2972   InChain = GprIndex.getValue(1);
2973 
2974   if (VT == MVT::i64) {
2975     // Check if GprIndex is even
2976     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2977                                  DAG.getConstant(1, dl, MVT::i32));
2978     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2979                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2980     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2981                                           DAG.getConstant(1, dl, MVT::i32));
2982     // Align GprIndex to be even if it isn't
2983     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2984                            GprIndex);
2985   }
2986 
2987   // fpr index is 1 byte after gpr
2988   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2989                                DAG.getConstant(1, dl, MVT::i32));
2990 
2991   // fpr
2992   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2993                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2994   InChain = FprIndex.getValue(1);
2995 
2996   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2997                                        DAG.getConstant(8, dl, MVT::i32));
2998 
2999   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3000                                         DAG.getConstant(4, dl, MVT::i32));
3001 
3002   // areas
3003   SDValue OverflowArea =
3004       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3005   InChain = OverflowArea.getValue(1);
3006 
3007   SDValue RegSaveArea =
3008       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3009   InChain = RegSaveArea.getValue(1);
3010 
3011   // select overflow_area if index > 8
3012   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3013                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3014 
3015   // adjustment constant gpr_index * 4/8
3016   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3017                                     VT.isInteger() ? GprIndex : FprIndex,
3018                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3019                                                     MVT::i32));
3020 
3021   // OurReg = RegSaveArea + RegConstant
3022   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3023                                RegConstant);
3024 
3025   // Floating types are 32 bytes into RegSaveArea
3026   if (VT.isFloatingPoint())
3027     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3028                          DAG.getConstant(32, dl, MVT::i32));
3029 
3030   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3031   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3032                                    VT.isInteger() ? GprIndex : FprIndex,
3033                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3034                                                    MVT::i32));
3035 
3036   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3037                               VT.isInteger() ? VAListPtr : FprPtr,
3038                               MachinePointerInfo(SV), MVT::i8);
3039 
3040   // determine if we should load from reg_save_area or overflow_area
3041   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3042 
3043   // increase overflow_area by 4/8 if gpr/fpr > 8
3044   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3045                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3046                                           dl, MVT::i32));
3047 
3048   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3049                              OverflowAreaPlusN);
3050 
3051   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3052                               MachinePointerInfo(), MVT::i32);
3053 
3054   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3055 }
3056 
3057 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3058   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3059 
3060   // We have to copy the entire va_list struct:
3061   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3062   return DAG.getMemcpy(Op.getOperand(0), Op,
3063                        Op.getOperand(1), Op.getOperand(2),
3064                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3065                        false, MachinePointerInfo(), MachinePointerInfo());
3066 }
3067 
3068 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3069                                                   SelectionDAG &DAG) const {
3070   return Op.getOperand(0);
3071 }
3072 
3073 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3074                                                 SelectionDAG &DAG) const {
3075   SDValue Chain = Op.getOperand(0);
3076   SDValue Trmp = Op.getOperand(1); // trampoline
3077   SDValue FPtr = Op.getOperand(2); // nested function
3078   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3079   SDLoc dl(Op);
3080 
3081   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3082   bool isPPC64 = (PtrVT == MVT::i64);
3083   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3084 
3085   TargetLowering::ArgListTy Args;
3086   TargetLowering::ArgListEntry Entry;
3087 
3088   Entry.Ty = IntPtrTy;
3089   Entry.Node = Trmp; Args.push_back(Entry);
3090 
3091   // TrampSize == (isPPC64 ? 48 : 40);
3092   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3093                                isPPC64 ? MVT::i64 : MVT::i32);
3094   Args.push_back(Entry);
3095 
3096   Entry.Node = FPtr; Args.push_back(Entry);
3097   Entry.Node = Nest; Args.push_back(Entry);
3098 
3099   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3100   TargetLowering::CallLoweringInfo CLI(DAG);
3101   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3102       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3103       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3104 
3105   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3106   return CallResult.second;
3107 }
3108 
3109 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3110   MachineFunction &MF = DAG.getMachineFunction();
3111   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3112   EVT PtrVT = getPointerTy(MF.getDataLayout());
3113 
3114   SDLoc dl(Op);
3115 
3116   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3117     // vastart just stores the address of the VarArgsFrameIndex slot into the
3118     // memory location argument.
3119     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3120     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3121     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3122                         MachinePointerInfo(SV));
3123   }
3124 
3125   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3126   // We suppose the given va_list is already allocated.
3127   //
3128   // typedef struct {
3129   //  char gpr;     /* index into the array of 8 GPRs
3130   //                 * stored in the register save area
3131   //                 * gpr=0 corresponds to r3,
3132   //                 * gpr=1 to r4, etc.
3133   //                 */
3134   //  char fpr;     /* index into the array of 8 FPRs
3135   //                 * stored in the register save area
3136   //                 * fpr=0 corresponds to f1,
3137   //                 * fpr=1 to f2, etc.
3138   //                 */
3139   //  char *overflow_arg_area;
3140   //                /* location on stack that holds
3141   //                 * the next overflow argument
3142   //                 */
3143   //  char *reg_save_area;
3144   //               /* where r3:r10 and f1:f8 (if saved)
3145   //                * are stored
3146   //                */
3147   // } va_list[1];
3148 
3149   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3150   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3151   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3152                                             PtrVT);
3153   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3154                                  PtrVT);
3155 
3156   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3157   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3158 
3159   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3160   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3161 
3162   uint64_t FPROffset = 1;
3163   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3164 
3165   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3166 
3167   // Store first byte : number of int regs
3168   SDValue firstStore =
3169       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3170                         MachinePointerInfo(SV), MVT::i8);
3171   uint64_t nextOffset = FPROffset;
3172   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3173                                   ConstFPROffset);
3174 
3175   // Store second byte : number of float regs
3176   SDValue secondStore =
3177       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3178                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3179   nextOffset += StackOffset;
3180   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3181 
3182   // Store second word : arguments given on stack
3183   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3184                                     MachinePointerInfo(SV, nextOffset));
3185   nextOffset += FrameOffset;
3186   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3187 
3188   // Store third word : arguments given in registers
3189   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3190                       MachinePointerInfo(SV, nextOffset));
3191 }
3192 
3193 /// FPR - The set of FP registers that should be allocated for arguments,
3194 /// on Darwin.
3195 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3196                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3197                                 PPC::F11, PPC::F12, PPC::F13};
3198 
3199 /// QFPR - The set of QPX registers that should be allocated for arguments.
3200 static const MCPhysReg QFPR[] = {
3201     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3202     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3203 
3204 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3205 /// the stack.
3206 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3207                                        unsigned PtrByteSize) {
3208   unsigned ArgSize = ArgVT.getStoreSize();
3209   if (Flags.isByVal())
3210     ArgSize = Flags.getByValSize();
3211 
3212   // Round up to multiples of the pointer size, except for array members,
3213   // which are always packed.
3214   if (!Flags.isInConsecutiveRegs())
3215     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3216 
3217   return ArgSize;
3218 }
3219 
3220 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3221 /// on the stack.
3222 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3223                                             ISD::ArgFlagsTy Flags,
3224                                             unsigned PtrByteSize) {
3225   unsigned Align = PtrByteSize;
3226 
3227   // Altivec parameters are padded to a 16 byte boundary.
3228   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3229       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3230       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3231       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3232     Align = 16;
3233   // QPX vector types stored in double-precision are padded to a 32 byte
3234   // boundary.
3235   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3236     Align = 32;
3237 
3238   // ByVal parameters are aligned as requested.
3239   if (Flags.isByVal()) {
3240     unsigned BVAlign = Flags.getByValAlign();
3241     if (BVAlign > PtrByteSize) {
3242       if (BVAlign % PtrByteSize != 0)
3243           llvm_unreachable(
3244             "ByVal alignment is not a multiple of the pointer size");
3245 
3246       Align = BVAlign;
3247     }
3248   }
3249 
3250   // Array members are always packed to their original alignment.
3251   if (Flags.isInConsecutiveRegs()) {
3252     // If the array member was split into multiple registers, the first
3253     // needs to be aligned to the size of the full type.  (Except for
3254     // ppcf128, which is only aligned as its f64 components.)
3255     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3256       Align = OrigVT.getStoreSize();
3257     else
3258       Align = ArgVT.getStoreSize();
3259   }
3260 
3261   return Align;
3262 }
3263 
3264 /// CalculateStackSlotUsed - Return whether this argument will use its
3265 /// stack slot (instead of being passed in registers).  ArgOffset,
3266 /// AvailableFPRs, and AvailableVRs must hold the current argument
3267 /// position, and will be updated to account for this argument.
3268 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3269                                    ISD::ArgFlagsTy Flags,
3270                                    unsigned PtrByteSize,
3271                                    unsigned LinkageSize,
3272                                    unsigned ParamAreaSize,
3273                                    unsigned &ArgOffset,
3274                                    unsigned &AvailableFPRs,
3275                                    unsigned &AvailableVRs, bool HasQPX) {
3276   bool UseMemory = false;
3277 
3278   // Respect alignment of argument on the stack.
3279   unsigned Align =
3280     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3281   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3282   // If there's no space left in the argument save area, we must
3283   // use memory (this check also catches zero-sized arguments).
3284   if (ArgOffset >= LinkageSize + ParamAreaSize)
3285     UseMemory = true;
3286 
3287   // Allocate argument on the stack.
3288   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3289   if (Flags.isInConsecutiveRegsLast())
3290     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3291   // If we overran the argument save area, we must use memory
3292   // (this check catches arguments passed partially in memory)
3293   if (ArgOffset > LinkageSize + ParamAreaSize)
3294     UseMemory = true;
3295 
3296   // However, if the argument is actually passed in an FPR or a VR,
3297   // we don't use memory after all.
3298   if (!Flags.isByVal()) {
3299     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3300         // QPX registers overlap with the scalar FP registers.
3301         (HasQPX && (ArgVT == MVT::v4f32 ||
3302                     ArgVT == MVT::v4f64 ||
3303                     ArgVT == MVT::v4i1)))
3304       if (AvailableFPRs > 0) {
3305         --AvailableFPRs;
3306         return false;
3307       }
3308     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3309         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3310         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3311         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3312       if (AvailableVRs > 0) {
3313         --AvailableVRs;
3314         return false;
3315       }
3316   }
3317 
3318   return UseMemory;
3319 }
3320 
3321 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3322 /// ensure minimum alignment required for target.
3323 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3324                                      unsigned NumBytes) {
3325   unsigned TargetAlign = Lowering->getStackAlignment();
3326   unsigned AlignMask = TargetAlign - 1;
3327   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3328   return NumBytes;
3329 }
3330 
3331 SDValue PPCTargetLowering::LowerFormalArguments(
3332     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3333     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3334     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3335   if (Subtarget.isSVR4ABI()) {
3336     if (Subtarget.isPPC64())
3337       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3338                                          dl, DAG, InVals);
3339     else
3340       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3341                                          dl, DAG, InVals);
3342   } else {
3343     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3344                                        dl, DAG, InVals);
3345   }
3346 }
3347 
3348 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3349     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3350     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3351     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3352 
3353   // 32-bit SVR4 ABI Stack Frame Layout:
3354   //              +-----------------------------------+
3355   //        +-->  |            Back chain             |
3356   //        |     +-----------------------------------+
3357   //        |     | Floating-point register save area |
3358   //        |     +-----------------------------------+
3359   //        |     |    General register save area     |
3360   //        |     +-----------------------------------+
3361   //        |     |          CR save word             |
3362   //        |     +-----------------------------------+
3363   //        |     |         VRSAVE save word          |
3364   //        |     +-----------------------------------+
3365   //        |     |         Alignment padding         |
3366   //        |     +-----------------------------------+
3367   //        |     |     Vector register save area     |
3368   //        |     +-----------------------------------+
3369   //        |     |       Local variable space        |
3370   //        |     +-----------------------------------+
3371   //        |     |        Parameter list area        |
3372   //        |     +-----------------------------------+
3373   //        |     |           LR save word            |
3374   //        |     +-----------------------------------+
3375   // SP-->  +---  |            Back chain             |
3376   //              +-----------------------------------+
3377   //
3378   // Specifications:
3379   //   System V Application Binary Interface PowerPC Processor Supplement
3380   //   AltiVec Technology Programming Interface Manual
3381 
3382   MachineFunction &MF = DAG.getMachineFunction();
3383   MachineFrameInfo &MFI = MF.getFrameInfo();
3384   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3385 
3386   EVT PtrVT = getPointerTy(MF.getDataLayout());
3387   // Potential tail calls could cause overwriting of argument stack slots.
3388   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3389                        (CallConv == CallingConv::Fast));
3390   unsigned PtrByteSize = 4;
3391 
3392   // Assign locations to all of the incoming arguments.
3393   SmallVector<CCValAssign, 16> ArgLocs;
3394   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3395                  *DAG.getContext());
3396 
3397   // Reserve space for the linkage area on the stack.
3398   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3399   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3400   if (useSoftFloat() || hasSPE())
3401     CCInfo.PreAnalyzeFormalArguments(Ins);
3402 
3403   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3404   CCInfo.clearWasPPCF128();
3405 
3406   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3407     CCValAssign &VA = ArgLocs[i];
3408 
3409     // Arguments stored in registers.
3410     if (VA.isRegLoc()) {
3411       const TargetRegisterClass *RC;
3412       EVT ValVT = VA.getValVT();
3413 
3414       switch (ValVT.getSimpleVT().SimpleTy) {
3415         default:
3416           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3417         case MVT::i1:
3418         case MVT::i32:
3419           RC = &PPC::GPRCRegClass;
3420           break;
3421         case MVT::f32:
3422           if (Subtarget.hasP8Vector())
3423             RC = &PPC::VSSRCRegClass;
3424           else if (Subtarget.hasSPE())
3425             RC = &PPC::SPE4RCRegClass;
3426           else
3427             RC = &PPC::F4RCRegClass;
3428           break;
3429         case MVT::f64:
3430           if (Subtarget.hasVSX())
3431             RC = &PPC::VSFRCRegClass;
3432           else if (Subtarget.hasSPE())
3433             RC = &PPC::SPERCRegClass;
3434           else
3435             RC = &PPC::F8RCRegClass;
3436           break;
3437         case MVT::v16i8:
3438         case MVT::v8i16:
3439         case MVT::v4i32:
3440           RC = &PPC::VRRCRegClass;
3441           break;
3442         case MVT::v4f32:
3443           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3444           break;
3445         case MVT::v2f64:
3446         case MVT::v2i64:
3447           RC = &PPC::VRRCRegClass;
3448           break;
3449         case MVT::v4f64:
3450           RC = &PPC::QFRCRegClass;
3451           break;
3452         case MVT::v4i1:
3453           RC = &PPC::QBRCRegClass;
3454           break;
3455       }
3456 
3457       // Transform the arguments stored in physical registers into virtual ones.
3458       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3459       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3460                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3461 
3462       if (ValVT == MVT::i1)
3463         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3464 
3465       InVals.push_back(ArgValue);
3466     } else {
3467       // Argument stored in memory.
3468       assert(VA.isMemLoc());
3469 
3470       // Get the extended size of the argument type in stack
3471       unsigned ArgSize = VA.getLocVT().getStoreSize();
3472       // Get the actual size of the argument type
3473       unsigned ObjSize = VA.getValVT().getStoreSize();
3474       unsigned ArgOffset = VA.getLocMemOffset();
3475       // Stack objects in PPC32 are right justified.
3476       ArgOffset += ArgSize - ObjSize;
3477       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3478 
3479       // Create load nodes to retrieve arguments from the stack.
3480       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3481       InVals.push_back(
3482           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3483     }
3484   }
3485 
3486   // Assign locations to all of the incoming aggregate by value arguments.
3487   // Aggregates passed by value are stored in the local variable space of the
3488   // caller's stack frame, right above the parameter list area.
3489   SmallVector<CCValAssign, 16> ByValArgLocs;
3490   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3491                       ByValArgLocs, *DAG.getContext());
3492 
3493   // Reserve stack space for the allocations in CCInfo.
3494   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3495 
3496   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3497 
3498   // Area that is at least reserved in the caller of this function.
3499   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3500   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3501 
3502   // Set the size that is at least reserved in caller of this function.  Tail
3503   // call optimized function's reserved stack space needs to be aligned so that
3504   // taking the difference between two stack areas will result in an aligned
3505   // stack.
3506   MinReservedArea =
3507       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3508   FuncInfo->setMinReservedArea(MinReservedArea);
3509 
3510   SmallVector<SDValue, 8> MemOps;
3511 
3512   // If the function takes variable number of arguments, make a frame index for
3513   // the start of the first vararg value... for expansion of llvm.va_start.
3514   if (isVarArg) {
3515     static const MCPhysReg GPArgRegs[] = {
3516       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3517       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3518     };
3519     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3520 
3521     static const MCPhysReg FPArgRegs[] = {
3522       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3523       PPC::F8
3524     };
3525     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3526 
3527     if (useSoftFloat() || hasSPE())
3528        NumFPArgRegs = 0;
3529 
3530     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3531     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3532 
3533     // Make room for NumGPArgRegs and NumFPArgRegs.
3534     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3535                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3536 
3537     FuncInfo->setVarArgsStackOffset(
3538       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3539                             CCInfo.getNextStackOffset(), true));
3540 
3541     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3542     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3543 
3544     // The fixed integer arguments of a variadic function are stored to the
3545     // VarArgsFrameIndex on the stack so that they may be loaded by
3546     // dereferencing the result of va_next.
3547     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3548       // Get an existing live-in vreg, or add a new one.
3549       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3550       if (!VReg)
3551         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3552 
3553       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3554       SDValue Store =
3555           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3556       MemOps.push_back(Store);
3557       // Increment the address by four for the next argument to store
3558       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3559       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3560     }
3561 
3562     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3563     // is set.
3564     // The double arguments are stored to the VarArgsFrameIndex
3565     // on the stack.
3566     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3567       // Get an existing live-in vreg, or add a new one.
3568       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3569       if (!VReg)
3570         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3571 
3572       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3573       SDValue Store =
3574           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3575       MemOps.push_back(Store);
3576       // Increment the address by eight for the next argument to store
3577       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3578                                          PtrVT);
3579       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3580     }
3581   }
3582 
3583   if (!MemOps.empty())
3584     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3585 
3586   return Chain;
3587 }
3588 
3589 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3590 // value to MVT::i64 and then truncate to the correct register size.
3591 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3592                                              EVT ObjectVT, SelectionDAG &DAG,
3593                                              SDValue ArgVal,
3594                                              const SDLoc &dl) const {
3595   if (Flags.isSExt())
3596     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3597                          DAG.getValueType(ObjectVT));
3598   else if (Flags.isZExt())
3599     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3600                          DAG.getValueType(ObjectVT));
3601 
3602   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3603 }
3604 
3605 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3606     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3607     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3608     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3609   // TODO: add description of PPC stack frame format, or at least some docs.
3610   //
3611   bool isELFv2ABI = Subtarget.isELFv2ABI();
3612   bool isLittleEndian = Subtarget.isLittleEndian();
3613   MachineFunction &MF = DAG.getMachineFunction();
3614   MachineFrameInfo &MFI = MF.getFrameInfo();
3615   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3616 
3617   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3618          "fastcc not supported on varargs functions");
3619 
3620   EVT PtrVT = getPointerTy(MF.getDataLayout());
3621   // Potential tail calls could cause overwriting of argument stack slots.
3622   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3623                        (CallConv == CallingConv::Fast));
3624   unsigned PtrByteSize = 8;
3625   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3626 
3627   static const MCPhysReg GPR[] = {
3628     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3629     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3630   };
3631   static const MCPhysReg VR[] = {
3632     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3633     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3634   };
3635 
3636   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3637   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3638   const unsigned Num_VR_Regs  = array_lengthof(VR);
3639   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3640 
3641   // Do a first pass over the arguments to determine whether the ABI
3642   // guarantees that our caller has allocated the parameter save area
3643   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3644   // in the ELFv2 ABI, it is true if this is a vararg function or if
3645   // any parameter is located in a stack slot.
3646 
3647   bool HasParameterArea = !isELFv2ABI || isVarArg;
3648   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3649   unsigned NumBytes = LinkageSize;
3650   unsigned AvailableFPRs = Num_FPR_Regs;
3651   unsigned AvailableVRs = Num_VR_Regs;
3652   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3653     if (Ins[i].Flags.isNest())
3654       continue;
3655 
3656     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3657                                PtrByteSize, LinkageSize, ParamAreaSize,
3658                                NumBytes, AvailableFPRs, AvailableVRs,
3659                                Subtarget.hasQPX()))
3660       HasParameterArea = true;
3661   }
3662 
3663   // Add DAG nodes to load the arguments or copy them out of registers.  On
3664   // entry to a function on PPC, the arguments start after the linkage area,
3665   // although the first ones are often in registers.
3666 
3667   unsigned ArgOffset = LinkageSize;
3668   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3669   unsigned &QFPR_idx = FPR_idx;
3670   SmallVector<SDValue, 8> MemOps;
3671   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3672   unsigned CurArgIdx = 0;
3673   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3674     SDValue ArgVal;
3675     bool needsLoad = false;
3676     EVT ObjectVT = Ins[ArgNo].VT;
3677     EVT OrigVT = Ins[ArgNo].ArgVT;
3678     unsigned ObjSize = ObjectVT.getStoreSize();
3679     unsigned ArgSize = ObjSize;
3680     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3681     if (Ins[ArgNo].isOrigArg()) {
3682       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3683       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3684     }
3685     // We re-align the argument offset for each argument, except when using the
3686     // fast calling convention, when we need to make sure we do that only when
3687     // we'll actually use a stack slot.
3688     unsigned CurArgOffset, Align;
3689     auto ComputeArgOffset = [&]() {
3690       /* Respect alignment of argument on the stack.  */
3691       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3692       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3693       CurArgOffset = ArgOffset;
3694     };
3695 
3696     if (CallConv != CallingConv::Fast) {
3697       ComputeArgOffset();
3698 
3699       /* Compute GPR index associated with argument offset.  */
3700       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3701       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3702     }
3703 
3704     // FIXME the codegen can be much improved in some cases.
3705     // We do not have to keep everything in memory.
3706     if (Flags.isByVal()) {
3707       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3708 
3709       if (CallConv == CallingConv::Fast)
3710         ComputeArgOffset();
3711 
3712       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3713       ObjSize = Flags.getByValSize();
3714       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3715       // Empty aggregate parameters do not take up registers.  Examples:
3716       //   struct { } a;
3717       //   union  { } b;
3718       //   int c[0];
3719       // etc.  However, we have to provide a place-holder in InVals, so
3720       // pretend we have an 8-byte item at the current address for that
3721       // purpose.
3722       if (!ObjSize) {
3723         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3724         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3725         InVals.push_back(FIN);
3726         continue;
3727       }
3728 
3729       // Create a stack object covering all stack doublewords occupied
3730       // by the argument.  If the argument is (fully or partially) on
3731       // the stack, or if the argument is fully in registers but the
3732       // caller has allocated the parameter save anyway, we can refer
3733       // directly to the caller's stack frame.  Otherwise, create a
3734       // local copy in our own frame.
3735       int FI;
3736       if (HasParameterArea ||
3737           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3738         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3739       else
3740         FI = MFI.CreateStackObject(ArgSize, Align, false);
3741       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3742 
3743       // Handle aggregates smaller than 8 bytes.
3744       if (ObjSize < PtrByteSize) {
3745         // The value of the object is its address, which differs from the
3746         // address of the enclosing doubleword on big-endian systems.
3747         SDValue Arg = FIN;
3748         if (!isLittleEndian) {
3749           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3750           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3751         }
3752         InVals.push_back(Arg);
3753 
3754         if (GPR_idx != Num_GPR_Regs) {
3755           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3756           FuncInfo->addLiveInAttr(VReg, Flags);
3757           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3758           SDValue Store;
3759 
3760           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3761             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3762                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3763             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3764                                       MachinePointerInfo(&*FuncArg), ObjType);
3765           } else {
3766             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3767             // store the whole register as-is to the parameter save area
3768             // slot.
3769             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3770                                  MachinePointerInfo(&*FuncArg));
3771           }
3772 
3773           MemOps.push_back(Store);
3774         }
3775         // Whether we copied from a register or not, advance the offset
3776         // into the parameter save area by a full doubleword.
3777         ArgOffset += PtrByteSize;
3778         continue;
3779       }
3780 
3781       // The value of the object is its address, which is the address of
3782       // its first stack doubleword.
3783       InVals.push_back(FIN);
3784 
3785       // Store whatever pieces of the object are in registers to memory.
3786       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3787         if (GPR_idx == Num_GPR_Regs)
3788           break;
3789 
3790         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3791         FuncInfo->addLiveInAttr(VReg, Flags);
3792         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3793         SDValue Addr = FIN;
3794         if (j) {
3795           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3796           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3797         }
3798         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3799                                      MachinePointerInfo(&*FuncArg, j));
3800         MemOps.push_back(Store);
3801         ++GPR_idx;
3802       }
3803       ArgOffset += ArgSize;
3804       continue;
3805     }
3806 
3807     switch (ObjectVT.getSimpleVT().SimpleTy) {
3808     default: llvm_unreachable("Unhandled argument type!");
3809     case MVT::i1:
3810     case MVT::i32:
3811     case MVT::i64:
3812       if (Flags.isNest()) {
3813         // The 'nest' parameter, if any, is passed in R11.
3814         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3815         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3816 
3817         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3818           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3819 
3820         break;
3821       }
3822 
3823       // These can be scalar arguments or elements of an integer array type
3824       // passed directly.  Clang may use those instead of "byval" aggregate
3825       // types to avoid forcing arguments to memory unnecessarily.
3826       if (GPR_idx != Num_GPR_Regs) {
3827         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3828         FuncInfo->addLiveInAttr(VReg, Flags);
3829         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3830 
3831         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3832           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3833           // value to MVT::i64 and then truncate to the correct register size.
3834           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3835       } else {
3836         if (CallConv == CallingConv::Fast)
3837           ComputeArgOffset();
3838 
3839         needsLoad = true;
3840         ArgSize = PtrByteSize;
3841       }
3842       if (CallConv != CallingConv::Fast || needsLoad)
3843         ArgOffset += 8;
3844       break;
3845 
3846     case MVT::f32:
3847     case MVT::f64:
3848       // These can be scalar arguments or elements of a float array type
3849       // passed directly.  The latter are used to implement ELFv2 homogenous
3850       // float aggregates.
3851       if (FPR_idx != Num_FPR_Regs) {
3852         unsigned VReg;
3853 
3854         if (ObjectVT == MVT::f32)
3855           VReg = MF.addLiveIn(FPR[FPR_idx],
3856                               Subtarget.hasP8Vector()
3857                                   ? &PPC::VSSRCRegClass
3858                                   : &PPC::F4RCRegClass);
3859         else
3860           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3861                                                 ? &PPC::VSFRCRegClass
3862                                                 : &PPC::F8RCRegClass);
3863 
3864         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3865         ++FPR_idx;
3866       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3867         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3868         // once we support fp <-> gpr moves.
3869 
3870         // This can only ever happen in the presence of f32 array types,
3871         // since otherwise we never run out of FPRs before running out
3872         // of GPRs.
3873         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3874         FuncInfo->addLiveInAttr(VReg, Flags);
3875         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3876 
3877         if (ObjectVT == MVT::f32) {
3878           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3879             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3880                                  DAG.getConstant(32, dl, MVT::i32));
3881           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3882         }
3883 
3884         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3885       } else {
3886         if (CallConv == CallingConv::Fast)
3887           ComputeArgOffset();
3888 
3889         needsLoad = true;
3890       }
3891 
3892       // When passing an array of floats, the array occupies consecutive
3893       // space in the argument area; only round up to the next doubleword
3894       // at the end of the array.  Otherwise, each float takes 8 bytes.
3895       if (CallConv != CallingConv::Fast || needsLoad) {
3896         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3897         ArgOffset += ArgSize;
3898         if (Flags.isInConsecutiveRegsLast())
3899           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3900       }
3901       break;
3902     case MVT::v4f32:
3903     case MVT::v4i32:
3904     case MVT::v8i16:
3905     case MVT::v16i8:
3906     case MVT::v2f64:
3907     case MVT::v2i64:
3908     case MVT::v1i128:
3909     case MVT::f128:
3910       if (!Subtarget.hasQPX()) {
3911         // These can be scalar arguments or elements of a vector array type
3912         // passed directly.  The latter are used to implement ELFv2 homogenous
3913         // vector aggregates.
3914         if (VR_idx != Num_VR_Regs) {
3915           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3916           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3917           ++VR_idx;
3918         } else {
3919           if (CallConv == CallingConv::Fast)
3920             ComputeArgOffset();
3921           needsLoad = true;
3922         }
3923         if (CallConv != CallingConv::Fast || needsLoad)
3924           ArgOffset += 16;
3925         break;
3926       } // not QPX
3927 
3928       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3929              "Invalid QPX parameter type");
3930       LLVM_FALLTHROUGH;
3931 
3932     case MVT::v4f64:
3933     case MVT::v4i1:
3934       // QPX vectors are treated like their scalar floating-point subregisters
3935       // (except that they're larger).
3936       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3937       if (QFPR_idx != Num_QFPR_Regs) {
3938         const TargetRegisterClass *RC;
3939         switch (ObjectVT.getSimpleVT().SimpleTy) {
3940         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3941         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3942         default:         RC = &PPC::QBRCRegClass; break;
3943         }
3944 
3945         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3946         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3947         ++QFPR_idx;
3948       } else {
3949         if (CallConv == CallingConv::Fast)
3950           ComputeArgOffset();
3951         needsLoad = true;
3952       }
3953       if (CallConv != CallingConv::Fast || needsLoad)
3954         ArgOffset += Sz;
3955       break;
3956     }
3957 
3958     // We need to load the argument to a virtual register if we determined
3959     // above that we ran out of physical registers of the appropriate type.
3960     if (needsLoad) {
3961       if (ObjSize < ArgSize && !isLittleEndian)
3962         CurArgOffset += ArgSize - ObjSize;
3963       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3964       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3965       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3966     }
3967 
3968     InVals.push_back(ArgVal);
3969   }
3970 
3971   // Area that is at least reserved in the caller of this function.
3972   unsigned MinReservedArea;
3973   if (HasParameterArea)
3974     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3975   else
3976     MinReservedArea = LinkageSize;
3977 
3978   // Set the size that is at least reserved in caller of this function.  Tail
3979   // call optimized functions' reserved stack space needs to be aligned so that
3980   // taking the difference between two stack areas will result in an aligned
3981   // stack.
3982   MinReservedArea =
3983       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3984   FuncInfo->setMinReservedArea(MinReservedArea);
3985 
3986   // If the function takes variable number of arguments, make a frame index for
3987   // the start of the first vararg value... for expansion of llvm.va_start.
3988   if (isVarArg) {
3989     int Depth = ArgOffset;
3990 
3991     FuncInfo->setVarArgsFrameIndex(
3992       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3993     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3994 
3995     // If this function is vararg, store any remaining integer argument regs
3996     // to their spots on the stack so that they may be loaded by dereferencing
3997     // the result of va_next.
3998     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3999          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4000       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4001       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4002       SDValue Store =
4003           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4004       MemOps.push_back(Store);
4005       // Increment the address by four for the next argument to store
4006       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4007       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4008     }
4009   }
4010 
4011   if (!MemOps.empty())
4012     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4013 
4014   return Chain;
4015 }
4016 
4017 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4018     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4019     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4020     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4021   // TODO: add description of PPC stack frame format, or at least some docs.
4022   //
4023   MachineFunction &MF = DAG.getMachineFunction();
4024   MachineFrameInfo &MFI = MF.getFrameInfo();
4025   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4026 
4027   EVT PtrVT = getPointerTy(MF.getDataLayout());
4028   bool isPPC64 = PtrVT == MVT::i64;
4029   // Potential tail calls could cause overwriting of argument stack slots.
4030   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4031                        (CallConv == CallingConv::Fast));
4032   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4033   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4034   unsigned ArgOffset = LinkageSize;
4035   // Area that is at least reserved in caller of this function.
4036   unsigned MinReservedArea = ArgOffset;
4037 
4038   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4039     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4040     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4041   };
4042   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4043     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4044     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4045   };
4046   static const MCPhysReg VR[] = {
4047     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4048     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4049   };
4050 
4051   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4052   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4053   const unsigned Num_VR_Regs  = array_lengthof( VR);
4054 
4055   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4056 
4057   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4058 
4059   // In 32-bit non-varargs functions, the stack space for vectors is after the
4060   // stack space for non-vectors.  We do not use this space unless we have
4061   // too many vectors to fit in registers, something that only occurs in
4062   // constructed examples:), but we have to walk the arglist to figure
4063   // that out...for the pathological case, compute VecArgOffset as the
4064   // start of the vector parameter area.  Computing VecArgOffset is the
4065   // entire point of the following loop.
4066   unsigned VecArgOffset = ArgOffset;
4067   if (!isVarArg && !isPPC64) {
4068     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4069          ++ArgNo) {
4070       EVT ObjectVT = Ins[ArgNo].VT;
4071       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4072 
4073       if (Flags.isByVal()) {
4074         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4075         unsigned ObjSize = Flags.getByValSize();
4076         unsigned ArgSize =
4077                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4078         VecArgOffset += ArgSize;
4079         continue;
4080       }
4081 
4082       switch(ObjectVT.getSimpleVT().SimpleTy) {
4083       default: llvm_unreachable("Unhandled argument type!");
4084       case MVT::i1:
4085       case MVT::i32:
4086       case MVT::f32:
4087         VecArgOffset += 4;
4088         break;
4089       case MVT::i64:  // PPC64
4090       case MVT::f64:
4091         // FIXME: We are guaranteed to be !isPPC64 at this point.
4092         // Does MVT::i64 apply?
4093         VecArgOffset += 8;
4094         break;
4095       case MVT::v4f32:
4096       case MVT::v4i32:
4097       case MVT::v8i16:
4098       case MVT::v16i8:
4099         // Nothing to do, we're only looking at Nonvector args here.
4100         break;
4101       }
4102     }
4103   }
4104   // We've found where the vector parameter area in memory is.  Skip the
4105   // first 12 parameters; these don't use that memory.
4106   VecArgOffset = ((VecArgOffset+15)/16)*16;
4107   VecArgOffset += 12*16;
4108 
4109   // Add DAG nodes to load the arguments or copy them out of registers.  On
4110   // entry to a function on PPC, the arguments start after the linkage area,
4111   // although the first ones are often in registers.
4112 
4113   SmallVector<SDValue, 8> MemOps;
4114   unsigned nAltivecParamsAtEnd = 0;
4115   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4116   unsigned CurArgIdx = 0;
4117   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4118     SDValue ArgVal;
4119     bool needsLoad = false;
4120     EVT ObjectVT = Ins[ArgNo].VT;
4121     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4122     unsigned ArgSize = ObjSize;
4123     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4124     if (Ins[ArgNo].isOrigArg()) {
4125       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4126       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4127     }
4128     unsigned CurArgOffset = ArgOffset;
4129 
4130     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4131     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4132         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4133       if (isVarArg || isPPC64) {
4134         MinReservedArea = ((MinReservedArea+15)/16)*16;
4135         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4136                                                   Flags,
4137                                                   PtrByteSize);
4138       } else  nAltivecParamsAtEnd++;
4139     } else
4140       // Calculate min reserved area.
4141       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4142                                                 Flags,
4143                                                 PtrByteSize);
4144 
4145     // FIXME the codegen can be much improved in some cases.
4146     // We do not have to keep everything in memory.
4147     if (Flags.isByVal()) {
4148       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4149 
4150       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4151       ObjSize = Flags.getByValSize();
4152       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4153       // Objects of size 1 and 2 are right justified, everything else is
4154       // left justified.  This means the memory address is adjusted forwards.
4155       if (ObjSize==1 || ObjSize==2) {
4156         CurArgOffset = CurArgOffset + (4 - ObjSize);
4157       }
4158       // The value of the object is its address.
4159       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4160       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4161       InVals.push_back(FIN);
4162       if (ObjSize==1 || ObjSize==2) {
4163         if (GPR_idx != Num_GPR_Regs) {
4164           unsigned VReg;
4165           if (isPPC64)
4166             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4167           else
4168             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4169           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4170           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4171           SDValue Store =
4172               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4173                                 MachinePointerInfo(&*FuncArg), ObjType);
4174           MemOps.push_back(Store);
4175           ++GPR_idx;
4176         }
4177 
4178         ArgOffset += PtrByteSize;
4179 
4180         continue;
4181       }
4182       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4183         // Store whatever pieces of the object are in registers
4184         // to memory.  ArgOffset will be the address of the beginning
4185         // of the object.
4186         if (GPR_idx != Num_GPR_Regs) {
4187           unsigned VReg;
4188           if (isPPC64)
4189             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4190           else
4191             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4192           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4193           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4194           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4195           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4196                                        MachinePointerInfo(&*FuncArg, j));
4197           MemOps.push_back(Store);
4198           ++GPR_idx;
4199           ArgOffset += PtrByteSize;
4200         } else {
4201           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4202           break;
4203         }
4204       }
4205       continue;
4206     }
4207 
4208     switch (ObjectVT.getSimpleVT().SimpleTy) {
4209     default: llvm_unreachable("Unhandled argument type!");
4210     case MVT::i1:
4211     case MVT::i32:
4212       if (!isPPC64) {
4213         if (GPR_idx != Num_GPR_Regs) {
4214           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4215           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4216 
4217           if (ObjectVT == MVT::i1)
4218             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4219 
4220           ++GPR_idx;
4221         } else {
4222           needsLoad = true;
4223           ArgSize = PtrByteSize;
4224         }
4225         // All int arguments reserve stack space in the Darwin ABI.
4226         ArgOffset += PtrByteSize;
4227         break;
4228       }
4229       LLVM_FALLTHROUGH;
4230     case MVT::i64:  // PPC64
4231       if (GPR_idx != Num_GPR_Regs) {
4232         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4233         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4234 
4235         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4236           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4237           // value to MVT::i64 and then truncate to the correct register size.
4238           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4239 
4240         ++GPR_idx;
4241       } else {
4242         needsLoad = true;
4243         ArgSize = PtrByteSize;
4244       }
4245       // All int arguments reserve stack space in the Darwin ABI.
4246       ArgOffset += 8;
4247       break;
4248 
4249     case MVT::f32:
4250     case MVT::f64:
4251       // Every 4 bytes of argument space consumes one of the GPRs available for
4252       // argument passing.
4253       if (GPR_idx != Num_GPR_Regs) {
4254         ++GPR_idx;
4255         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4256           ++GPR_idx;
4257       }
4258       if (FPR_idx != Num_FPR_Regs) {
4259         unsigned VReg;
4260 
4261         if (ObjectVT == MVT::f32)
4262           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4263         else
4264           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4265 
4266         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4267         ++FPR_idx;
4268       } else {
4269         needsLoad = true;
4270       }
4271 
4272       // All FP arguments reserve stack space in the Darwin ABI.
4273       ArgOffset += isPPC64 ? 8 : ObjSize;
4274       break;
4275     case MVT::v4f32:
4276     case MVT::v4i32:
4277     case MVT::v8i16:
4278     case MVT::v16i8:
4279       // Note that vector arguments in registers don't reserve stack space,
4280       // except in varargs functions.
4281       if (VR_idx != Num_VR_Regs) {
4282         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4283         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4284         if (isVarArg) {
4285           while ((ArgOffset % 16) != 0) {
4286             ArgOffset += PtrByteSize;
4287             if (GPR_idx != Num_GPR_Regs)
4288               GPR_idx++;
4289           }
4290           ArgOffset += 16;
4291           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4292         }
4293         ++VR_idx;
4294       } else {
4295         if (!isVarArg && !isPPC64) {
4296           // Vectors go after all the nonvectors.
4297           CurArgOffset = VecArgOffset;
4298           VecArgOffset += 16;
4299         } else {
4300           // Vectors are aligned.
4301           ArgOffset = ((ArgOffset+15)/16)*16;
4302           CurArgOffset = ArgOffset;
4303           ArgOffset += 16;
4304         }
4305         needsLoad = true;
4306       }
4307       break;
4308     }
4309 
4310     // We need to load the argument to a virtual register if we determined above
4311     // that we ran out of physical registers of the appropriate type.
4312     if (needsLoad) {
4313       int FI = MFI.CreateFixedObject(ObjSize,
4314                                      CurArgOffset + (ArgSize - ObjSize),
4315                                      isImmutable);
4316       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4317       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4318     }
4319 
4320     InVals.push_back(ArgVal);
4321   }
4322 
4323   // Allow for Altivec parameters at the end, if needed.
4324   if (nAltivecParamsAtEnd) {
4325     MinReservedArea = ((MinReservedArea+15)/16)*16;
4326     MinReservedArea += 16*nAltivecParamsAtEnd;
4327   }
4328 
4329   // Area that is at least reserved in the caller of this function.
4330   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4331 
4332   // Set the size that is at least reserved in caller of this function.  Tail
4333   // call optimized functions' reserved stack space needs to be aligned so that
4334   // taking the difference between two stack areas will result in an aligned
4335   // stack.
4336   MinReservedArea =
4337       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4338   FuncInfo->setMinReservedArea(MinReservedArea);
4339 
4340   // If the function takes variable number of arguments, make a frame index for
4341   // the start of the first vararg value... for expansion of llvm.va_start.
4342   if (isVarArg) {
4343     int Depth = ArgOffset;
4344 
4345     FuncInfo->setVarArgsFrameIndex(
4346       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4347                             Depth, true));
4348     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4349 
4350     // If this function is vararg, store any remaining integer argument regs
4351     // to their spots on the stack so that they may be loaded by dereferencing
4352     // the result of va_next.
4353     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4354       unsigned VReg;
4355 
4356       if (isPPC64)
4357         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4358       else
4359         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4360 
4361       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4362       SDValue Store =
4363           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4364       MemOps.push_back(Store);
4365       // Increment the address by four for the next argument to store
4366       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4367       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4368     }
4369   }
4370 
4371   if (!MemOps.empty())
4372     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4373 
4374   return Chain;
4375 }
4376 
4377 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4378 /// adjusted to accommodate the arguments for the tailcall.
4379 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4380                                    unsigned ParamSize) {
4381 
4382   if (!isTailCall) return 0;
4383 
4384   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4385   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4386   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4387   // Remember only if the new adjustment is bigger.
4388   if (SPDiff < FI->getTailCallSPDelta())
4389     FI->setTailCallSPDelta(SPDiff);
4390 
4391   return SPDiff;
4392 }
4393 
4394 static bool isFunctionGlobalAddress(SDValue Callee);
4395 
4396 static bool
4397 callsShareTOCBase(const Function *Caller, SDValue Callee,
4398                     const TargetMachine &TM) {
4399   // If !G, Callee can be an external symbol.
4400   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4401   if (!G)
4402     return false;
4403 
4404   // The medium and large code models are expected to provide a sufficiently
4405   // large TOC to provide all data addressing needs of a module with a
4406   // single TOC. Since each module will be addressed with a single TOC then we
4407   // only need to check that caller and callee don't cross dso boundaries.
4408   if (CodeModel::Medium == TM.getCodeModel() ||
4409       CodeModel::Large == TM.getCodeModel())
4410     return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4411 
4412   // Otherwise we need to ensure callee and caller are in the same section,
4413   // since the linker may allocate multiple TOCs, and we don't know which
4414   // sections will belong to the same TOC base.
4415 
4416   const GlobalValue *GV = G->getGlobal();
4417   if (!GV->isStrongDefinitionForLinker())
4418     return false;
4419 
4420   // Any explicitly-specified sections and section prefixes must also match.
4421   // Also, if we're using -ffunction-sections, then each function is always in
4422   // a different section (the same is true for COMDAT functions).
4423   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4424       GV->getSection() != Caller->getSection())
4425     return false;
4426   if (const auto *F = dyn_cast<Function>(GV)) {
4427     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4428       return false;
4429   }
4430 
4431   // If the callee might be interposed, then we can't assume the ultimate call
4432   // target will be in the same section. Even in cases where we can assume that
4433   // interposition won't happen, in any case where the linker might insert a
4434   // stub to allow for interposition, we must generate code as though
4435   // interposition might occur. To understand why this matters, consider a
4436   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4437   // in the same section, but a is in a different module (i.e. has a different
4438   // TOC base pointer). If the linker allows for interposition between b and c,
4439   // then it will generate a stub for the call edge between b and c which will
4440   // save the TOC pointer into the designated stack slot allocated by b. If we
4441   // return true here, and therefore allow a tail call between b and c, that
4442   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4443   // pointer into the stack slot allocated by a (where the a -> b stub saved
4444   // a's TOC base pointer). If we're not considering a tail call, but rather,
4445   // whether a nop is needed after the call instruction in b, because the linker
4446   // will insert a stub, it might complain about a missing nop if we omit it
4447   // (although many don't complain in this case).
4448   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4449     return false;
4450 
4451   return true;
4452 }
4453 
4454 static bool
4455 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4456                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4457   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4458 
4459   const unsigned PtrByteSize = 8;
4460   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4461 
4462   static const MCPhysReg GPR[] = {
4463     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4464     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4465   };
4466   static const MCPhysReg VR[] = {
4467     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4468     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4469   };
4470 
4471   const unsigned NumGPRs = array_lengthof(GPR);
4472   const unsigned NumFPRs = 13;
4473   const unsigned NumVRs = array_lengthof(VR);
4474   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4475 
4476   unsigned NumBytes = LinkageSize;
4477   unsigned AvailableFPRs = NumFPRs;
4478   unsigned AvailableVRs = NumVRs;
4479 
4480   for (const ISD::OutputArg& Param : Outs) {
4481     if (Param.Flags.isNest()) continue;
4482 
4483     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4484                                PtrByteSize, LinkageSize, ParamAreaSize,
4485                                NumBytes, AvailableFPRs, AvailableVRs,
4486                                Subtarget.hasQPX()))
4487       return true;
4488   }
4489   return false;
4490 }
4491 
4492 static bool
4493 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4494   if (CS.arg_size() != CallerFn->arg_size())
4495     return false;
4496 
4497   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4498   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4499   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4500 
4501   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4502     const Value* CalleeArg = *CalleeArgIter;
4503     const Value* CallerArg = &(*CallerArgIter);
4504     if (CalleeArg == CallerArg)
4505       continue;
4506 
4507     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4508     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4509     //      }
4510     // 1st argument of callee is undef and has the same type as caller.
4511     if (CalleeArg->getType() == CallerArg->getType() &&
4512         isa<UndefValue>(CalleeArg))
4513       continue;
4514 
4515     return false;
4516   }
4517 
4518   return true;
4519 }
4520 
4521 // Returns true if TCO is possible between the callers and callees
4522 // calling conventions.
4523 static bool
4524 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4525                                     CallingConv::ID CalleeCC) {
4526   // Tail calls are possible with fastcc and ccc.
4527   auto isTailCallableCC  = [] (CallingConv::ID CC){
4528       return  CC == CallingConv::C || CC == CallingConv::Fast;
4529   };
4530   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4531     return false;
4532 
4533   // We can safely tail call both fastcc and ccc callees from a c calling
4534   // convention caller. If the caller is fastcc, we may have less stack space
4535   // than a non-fastcc caller with the same signature so disable tail-calls in
4536   // that case.
4537   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4538 }
4539 
4540 bool
4541 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4542                                     SDValue Callee,
4543                                     CallingConv::ID CalleeCC,
4544                                     ImmutableCallSite CS,
4545                                     bool isVarArg,
4546                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4547                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4548                                     SelectionDAG& DAG) const {
4549   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4550 
4551   if (DisableSCO && !TailCallOpt) return false;
4552 
4553   // Variadic argument functions are not supported.
4554   if (isVarArg) return false;
4555 
4556   auto &Caller = DAG.getMachineFunction().getFunction();
4557   // Check that the calling conventions are compatible for tco.
4558   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4559     return false;
4560 
4561   // Caller contains any byval parameter is not supported.
4562   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4563     return false;
4564 
4565   // Callee contains any byval parameter is not supported, too.
4566   // Note: This is a quick work around, because in some cases, e.g.
4567   // caller's stack size > callee's stack size, we are still able to apply
4568   // sibling call optimization. For example, gcc is able to do SCO for caller1
4569   // in the following example, but not for caller2.
4570   //   struct test {
4571   //     long int a;
4572   //     char ary[56];
4573   //   } gTest;
4574   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4575   //     b->a = v.a;
4576   //     return 0;
4577   //   }
4578   //   void caller1(struct test a, struct test c, struct test *b) {
4579   //     callee(gTest, b); }
4580   //   void caller2(struct test *b) { callee(gTest, b); }
4581   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4582     return false;
4583 
4584   // If callee and caller use different calling conventions, we cannot pass
4585   // parameters on stack since offsets for the parameter area may be different.
4586   if (Caller.getCallingConv() != CalleeCC &&
4587       needStackSlotPassParameters(Subtarget, Outs))
4588     return false;
4589 
4590   // No TCO/SCO on indirect call because Caller have to restore its TOC
4591   if (!isFunctionGlobalAddress(Callee) &&
4592       !isa<ExternalSymbolSDNode>(Callee))
4593     return false;
4594 
4595   // If the caller and callee potentially have different TOC bases then we
4596   // cannot tail call since we need to restore the TOC pointer after the call.
4597   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4598   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4599     return false;
4600 
4601   // TCO allows altering callee ABI, so we don't have to check further.
4602   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4603     return true;
4604 
4605   if (DisableSCO) return false;
4606 
4607   // If callee use the same argument list that caller is using, then we can
4608   // apply SCO on this case. If it is not, then we need to check if callee needs
4609   // stack for passing arguments.
4610   if (!hasSameArgumentList(&Caller, CS) &&
4611       needStackSlotPassParameters(Subtarget, Outs)) {
4612     return false;
4613   }
4614 
4615   return true;
4616 }
4617 
4618 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4619 /// for tail call optimization. Targets which want to do tail call
4620 /// optimization should implement this function.
4621 bool
4622 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4623                                                      CallingConv::ID CalleeCC,
4624                                                      bool isVarArg,
4625                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4626                                                      SelectionDAG& DAG) const {
4627   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4628     return false;
4629 
4630   // Variable argument functions are not supported.
4631   if (isVarArg)
4632     return false;
4633 
4634   MachineFunction &MF = DAG.getMachineFunction();
4635   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4636   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4637     // Functions containing by val parameters are not supported.
4638     for (unsigned i = 0; i != Ins.size(); i++) {
4639        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4640        if (Flags.isByVal()) return false;
4641     }
4642 
4643     // Non-PIC/GOT tail calls are supported.
4644     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4645       return true;
4646 
4647     // At the moment we can only do local tail calls (in same module, hidden
4648     // or protected) if we are generating PIC.
4649     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4650       return G->getGlobal()->hasHiddenVisibility()
4651           || G->getGlobal()->hasProtectedVisibility();
4652   }
4653 
4654   return false;
4655 }
4656 
4657 /// isCallCompatibleAddress - Return the immediate to use if the specified
4658 /// 32-bit value is representable in the immediate field of a BxA instruction.
4659 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4660   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4661   if (!C) return nullptr;
4662 
4663   int Addr = C->getZExtValue();
4664   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4665       SignExtend32<26>(Addr) != Addr)
4666     return nullptr;  // Top 6 bits have to be sext of immediate.
4667 
4668   return DAG
4669       .getConstant(
4670           (int)C->getZExtValue() >> 2, SDLoc(Op),
4671           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4672       .getNode();
4673 }
4674 
4675 namespace {
4676 
4677 struct TailCallArgumentInfo {
4678   SDValue Arg;
4679   SDValue FrameIdxOp;
4680   int FrameIdx = 0;
4681 
4682   TailCallArgumentInfo() = default;
4683 };
4684 
4685 } // end anonymous namespace
4686 
4687 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4688 static void StoreTailCallArgumentsToStackSlot(
4689     SelectionDAG &DAG, SDValue Chain,
4690     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4691     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4692   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4693     SDValue Arg = TailCallArgs[i].Arg;
4694     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4695     int FI = TailCallArgs[i].FrameIdx;
4696     // Store relative to framepointer.
4697     MemOpChains.push_back(DAG.getStore(
4698         Chain, dl, Arg, FIN,
4699         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4700   }
4701 }
4702 
4703 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4704 /// the appropriate stack slot for the tail call optimized function call.
4705 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4706                                              SDValue OldRetAddr, SDValue OldFP,
4707                                              int SPDiff, const SDLoc &dl) {
4708   if (SPDiff) {
4709     // Calculate the new stack slot for the return address.
4710     MachineFunction &MF = DAG.getMachineFunction();
4711     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4712     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4713     bool isPPC64 = Subtarget.isPPC64();
4714     int SlotSize = isPPC64 ? 8 : 4;
4715     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4716     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4717                                                          NewRetAddrLoc, true);
4718     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4719     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4720     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4721                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4722 
4723     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4724     // slot as the FP is never overwritten.
4725     if (Subtarget.isDarwinABI()) {
4726       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4727       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4728                                                          true);
4729       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4730       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4731                            MachinePointerInfo::getFixedStack(
4732                                DAG.getMachineFunction(), NewFPIdx));
4733     }
4734   }
4735   return Chain;
4736 }
4737 
4738 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4739 /// the position of the argument.
4740 static void
4741 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4742                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4743                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4744   int Offset = ArgOffset + SPDiff;
4745   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4746   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4747   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4748   SDValue FIN = DAG.getFrameIndex(FI, VT);
4749   TailCallArgumentInfo Info;
4750   Info.Arg = Arg;
4751   Info.FrameIdxOp = FIN;
4752   Info.FrameIdx = FI;
4753   TailCallArguments.push_back(Info);
4754 }
4755 
4756 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4757 /// stack slot. Returns the chain as result and the loaded frame pointers in
4758 /// LROpOut/FPOpout. Used when tail calling.
4759 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4760     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4761     SDValue &FPOpOut, const SDLoc &dl) const {
4762   if (SPDiff) {
4763     // Load the LR and FP stack slot for later adjusting.
4764     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4765     LROpOut = getReturnAddrFrameIndex(DAG);
4766     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4767     Chain = SDValue(LROpOut.getNode(), 1);
4768 
4769     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4770     // slot as the FP is never overwritten.
4771     if (Subtarget.isDarwinABI()) {
4772       FPOpOut = getFramePointerFrameIndex(DAG);
4773       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4774       Chain = SDValue(FPOpOut.getNode(), 1);
4775     }
4776   }
4777   return Chain;
4778 }
4779 
4780 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4781 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4782 /// specified by the specific parameter attribute. The copy will be passed as
4783 /// a byval function parameter.
4784 /// Sometimes what we are copying is the end of a larger object, the part that
4785 /// does not fit in registers.
4786 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4787                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4788                                          SelectionDAG &DAG, const SDLoc &dl) {
4789   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4790   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4791                        false, false, false, MachinePointerInfo(),
4792                        MachinePointerInfo());
4793 }
4794 
4795 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4796 /// tail calls.
4797 static void LowerMemOpCallTo(
4798     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4799     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4800     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4801     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4802   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4803   if (!isTailCall) {
4804     if (isVector) {
4805       SDValue StackPtr;
4806       if (isPPC64)
4807         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4808       else
4809         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4810       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4811                            DAG.getConstant(ArgOffset, dl, PtrVT));
4812     }
4813     MemOpChains.push_back(
4814         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4815     // Calculate and remember argument location.
4816   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4817                                   TailCallArguments);
4818 }
4819 
4820 static void
4821 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4822                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4823                 SDValue FPOp,
4824                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4825   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4826   // might overwrite each other in case of tail call optimization.
4827   SmallVector<SDValue, 8> MemOpChains2;
4828   // Do not flag preceding copytoreg stuff together with the following stuff.
4829   InFlag = SDValue();
4830   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4831                                     MemOpChains2, dl);
4832   if (!MemOpChains2.empty())
4833     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4834 
4835   // Store the return address to the appropriate stack slot.
4836   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4837 
4838   // Emit callseq_end just before tailcall node.
4839   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4840                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4841   InFlag = Chain.getValue(1);
4842 }
4843 
4844 // Is this global address that of a function that can be called by name? (as
4845 // opposed to something that must hold a descriptor for an indirect call).
4846 static bool isFunctionGlobalAddress(SDValue Callee) {
4847   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4848     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4849         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4850       return false;
4851 
4852     return G->getGlobal()->getValueType()->isFunctionTy();
4853   }
4854 
4855   return false;
4856 }
4857 
4858 static unsigned
4859 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4860             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4861             bool isPatchPoint, bool hasNest,
4862             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4863             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4864             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4865   bool isPPC64 = Subtarget.isPPC64();
4866   bool isSVR4ABI = Subtarget.isSVR4ABI();
4867   bool isELFv2ABI = Subtarget.isELFv2ABI();
4868 
4869   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4870   NodeTys.push_back(MVT::Other);   // Returns a chain
4871   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4872 
4873   unsigned CallOpc = PPCISD::CALL;
4874 
4875   bool needIndirectCall = true;
4876   if (!isSVR4ABI || !isPPC64)
4877     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4878       // If this is an absolute destination address, use the munged value.
4879       Callee = SDValue(Dest, 0);
4880       needIndirectCall = false;
4881     }
4882 
4883   // PC-relative references to external symbols should go through $stub, unless
4884   // we're building with the leopard linker or later, which automatically
4885   // synthesizes these stubs.
4886   const TargetMachine &TM = DAG.getTarget();
4887   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4888   const GlobalValue *GV = nullptr;
4889   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4890     GV = G->getGlobal();
4891   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4892   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4893 
4894   if (isFunctionGlobalAddress(Callee)) {
4895     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4896     // A call to a TLS address is actually an indirect call to a
4897     // thread-specific pointer.
4898     unsigned OpFlags = 0;
4899     if (UsePlt)
4900       OpFlags = PPCII::MO_PLT;
4901 
4902     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4903     // every direct call is) turn it into a TargetGlobalAddress /
4904     // TargetExternalSymbol node so that legalize doesn't hack it.
4905     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4906                                         Callee.getValueType(), 0, OpFlags);
4907     needIndirectCall = false;
4908   }
4909 
4910   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4911     unsigned char OpFlags = 0;
4912 
4913     if (UsePlt)
4914       OpFlags = PPCII::MO_PLT;
4915 
4916     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4917                                          OpFlags);
4918     needIndirectCall = false;
4919   }
4920 
4921   if (isPatchPoint) {
4922     // We'll form an invalid direct call when lowering a patchpoint; the full
4923     // sequence for an indirect call is complicated, and many of the
4924     // instructions introduced might have side effects (and, thus, can't be
4925     // removed later). The call itself will be removed as soon as the
4926     // argument/return lowering is complete, so the fact that it has the wrong
4927     // kind of operands should not really matter.
4928     needIndirectCall = false;
4929   }
4930 
4931   if (needIndirectCall) {
4932     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4933     // to do the call, we can't use PPCISD::CALL.
4934     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4935 
4936     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4937       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4938       // entry point, but to the function descriptor (the function entry point
4939       // address is part of the function descriptor though).
4940       // The function descriptor is a three doubleword structure with the
4941       // following fields: function entry point, TOC base address and
4942       // environment pointer.
4943       // Thus for a call through a function pointer, the following actions need
4944       // to be performed:
4945       //   1. Save the TOC of the caller in the TOC save area of its stack
4946       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4947       //   2. Load the address of the function entry point from the function
4948       //      descriptor.
4949       //   3. Load the TOC of the callee from the function descriptor into r2.
4950       //   4. Load the environment pointer from the function descriptor into
4951       //      r11.
4952       //   5. Branch to the function entry point address.
4953       //   6. On return of the callee, the TOC of the caller needs to be
4954       //      restored (this is done in FinishCall()).
4955       //
4956       // The loads are scheduled at the beginning of the call sequence, and the
4957       // register copies are flagged together to ensure that no other
4958       // operations can be scheduled in between. E.g. without flagging the
4959       // copies together, a TOC access in the caller could be scheduled between
4960       // the assignment of the callee TOC and the branch to the callee, which
4961       // results in the TOC access going through the TOC of the callee instead
4962       // of going through the TOC of the caller, which leads to incorrect code.
4963 
4964       // Load the address of the function entry point from the function
4965       // descriptor.
4966       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4967       if (LDChain.getValueType() == MVT::Glue)
4968         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4969 
4970       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4971                           ? (MachineMemOperand::MODereferenceable |
4972                              MachineMemOperand::MOInvariant)
4973                           : MachineMemOperand::MONone;
4974 
4975       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
4976       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4977                                         /* Alignment = */ 8, MMOFlags);
4978 
4979       // Load environment pointer into r11.
4980       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4981       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4982       SDValue LoadEnvPtr =
4983           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4984                       /* Alignment = */ 8, MMOFlags);
4985 
4986       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4987       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4988       SDValue TOCPtr =
4989           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4990                       /* Alignment = */ 8, MMOFlags);
4991 
4992       setUsesTOCBasePtr(DAG);
4993       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4994                                         InFlag);
4995       Chain = TOCVal.getValue(0);
4996       InFlag = TOCVal.getValue(1);
4997 
4998       // If the function call has an explicit 'nest' parameter, it takes the
4999       // place of the environment pointer.
5000       if (!hasNest) {
5001         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
5002                                           InFlag);
5003 
5004         Chain = EnvVal.getValue(0);
5005         InFlag = EnvVal.getValue(1);
5006       }
5007 
5008       MTCTROps[0] = Chain;
5009       MTCTROps[1] = LoadFuncPtr;
5010       MTCTROps[2] = InFlag;
5011     }
5012 
5013     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
5014                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
5015     InFlag = Chain.getValue(1);
5016 
5017     NodeTys.clear();
5018     NodeTys.push_back(MVT::Other);
5019     NodeTys.push_back(MVT::Glue);
5020     Ops.push_back(Chain);
5021     CallOpc = PPCISD::BCTRL;
5022     Callee.setNode(nullptr);
5023     // Add use of X11 (holding environment pointer)
5024     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
5025       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
5026     // Add CTR register as callee so a bctr can be emitted later.
5027     if (isTailCall)
5028       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
5029   }
5030 
5031   // If this is a direct call, pass the chain and the callee.
5032   if (Callee.getNode()) {
5033     Ops.push_back(Chain);
5034     Ops.push_back(Callee);
5035   }
5036   // If this is a tail call add stack pointer delta.
5037   if (isTailCall)
5038     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5039 
5040   // Add argument registers to the end of the list so that they are known live
5041   // into the call.
5042   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5043     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5044                                   RegsToPass[i].second.getValueType()));
5045 
5046   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
5047   // into the call.
5048   // We do need to reserve X2 to appease the verifier for the PATCHPOINT.
5049   if (isSVR4ABI && isPPC64) {
5050     setUsesTOCBasePtr(DAG);
5051 
5052     // We cannot add X2 as an operand here for PATCHPOINT, because there is no
5053     // way to mark dependencies as implicit here. We will add the X2 dependency
5054     // in EmitInstrWithCustomInserter.
5055     if (!isPatchPoint)
5056       Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
5057   }
5058 
5059   return CallOpc;
5060 }
5061 
5062 SDValue PPCTargetLowering::LowerCallResult(
5063     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5064     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5065     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5066   SmallVector<CCValAssign, 16> RVLocs;
5067   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5068                     *DAG.getContext());
5069 
5070   CCRetInfo.AnalyzeCallResult(
5071       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5072                ? RetCC_PPC_Cold
5073                : RetCC_PPC);
5074 
5075   // Copy all of the result registers out of their specified physreg.
5076   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5077     CCValAssign &VA = RVLocs[i];
5078     assert(VA.isRegLoc() && "Can only return in registers!");
5079 
5080     SDValue Val = DAG.getCopyFromReg(Chain, dl,
5081                                      VA.getLocReg(), VA.getLocVT(), InFlag);
5082     Chain = Val.getValue(1);
5083     InFlag = Val.getValue(2);
5084 
5085     switch (VA.getLocInfo()) {
5086     default: llvm_unreachable("Unknown loc info!");
5087     case CCValAssign::Full: break;
5088     case CCValAssign::AExt:
5089       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5090       break;
5091     case CCValAssign::ZExt:
5092       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5093                         DAG.getValueType(VA.getValVT()));
5094       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5095       break;
5096     case CCValAssign::SExt:
5097       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5098                         DAG.getValueType(VA.getValVT()));
5099       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5100       break;
5101     }
5102 
5103     InVals.push_back(Val);
5104   }
5105 
5106   return Chain;
5107 }
5108 
5109 SDValue PPCTargetLowering::FinishCall(
5110     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5111     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5112     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5113     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5114     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5115     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5116   std::vector<EVT> NodeTys;
5117   SmallVector<SDValue, 8> Ops;
5118   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5119                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5120                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5121 
5122   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5123   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5124     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5125 
5126   // When performing tail call optimization the callee pops its arguments off
5127   // the stack. Account for this here so these bytes can be pushed back on in
5128   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5129   int BytesCalleePops =
5130     (CallConv == CallingConv::Fast &&
5131      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5132 
5133   // Add a register mask operand representing the call-preserved registers.
5134   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5135   const uint32_t *Mask =
5136       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5137   assert(Mask && "Missing call preserved mask for calling convention");
5138   Ops.push_back(DAG.getRegisterMask(Mask));
5139 
5140   if (InFlag.getNode())
5141     Ops.push_back(InFlag);
5142 
5143   // Emit tail call.
5144   if (isTailCall) {
5145     assert(((Callee.getOpcode() == ISD::Register &&
5146              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5147             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5148             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5149             isa<ConstantSDNode>(Callee)) &&
5150     "Expecting an global address, external symbol, absolute value or register");
5151 
5152     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5153     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5154   }
5155 
5156   // Add a NOP immediately after the branch instruction when using the 64-bit
5157   // SVR4 ABI. At link time, if caller and callee are in a different module and
5158   // thus have a different TOC, the call will be replaced with a call to a stub
5159   // function which saves the current TOC, loads the TOC of the callee and
5160   // branches to the callee. The NOP will be replaced with a load instruction
5161   // which restores the TOC of the caller from the TOC save slot of the current
5162   // stack frame. If caller and callee belong to the same module (and have the
5163   // same TOC), the NOP will remain unchanged.
5164 
5165   MachineFunction &MF = DAG.getMachineFunction();
5166   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
5167       !isPatchPoint) {
5168     if (CallOpc == PPCISD::BCTRL) {
5169       // This is a call through a function pointer.
5170       // Restore the caller TOC from the save area into R2.
5171       // See PrepareCall() for more information about calls through function
5172       // pointers in the 64-bit SVR4 ABI.
5173       // We are using a target-specific load with r2 hard coded, because the
5174       // result of a target-independent load would never go directly into r2,
5175       // since r2 is a reserved register (which prevents the register allocator
5176       // from allocating it), resulting in an additional register being
5177       // allocated and an unnecessary move instruction being generated.
5178       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5179 
5180       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5181       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5182       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5183       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5184       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5185 
5186       // The address needs to go after the chain input but before the flag (or
5187       // any other variadic arguments).
5188       Ops.insert(std::next(Ops.begin()), AddTOC);
5189     } else if (CallOpc == PPCISD::CALL &&
5190       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5191       // Otherwise insert NOP for non-local calls.
5192       CallOpc = PPCISD::CALL_NOP;
5193     }
5194   }
5195 
5196   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5197   InFlag = Chain.getValue(1);
5198 
5199   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5200                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5201                              InFlag, dl);
5202   if (!Ins.empty())
5203     InFlag = Chain.getValue(1);
5204 
5205   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5206                          Ins, dl, DAG, InVals);
5207 }
5208 
5209 SDValue
5210 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5211                              SmallVectorImpl<SDValue> &InVals) const {
5212   SelectionDAG &DAG                     = CLI.DAG;
5213   SDLoc &dl                             = CLI.DL;
5214   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5215   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5216   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5217   SDValue Chain                         = CLI.Chain;
5218   SDValue Callee                        = CLI.Callee;
5219   bool &isTailCall                      = CLI.IsTailCall;
5220   CallingConv::ID CallConv              = CLI.CallConv;
5221   bool isVarArg                         = CLI.IsVarArg;
5222   bool isPatchPoint                     = CLI.IsPatchPoint;
5223   ImmutableCallSite CS                  = CLI.CS;
5224 
5225   if (isTailCall) {
5226     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5227       isTailCall = false;
5228     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5229       isTailCall =
5230         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5231                                                  isVarArg, Outs, Ins, DAG);
5232     else
5233       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5234                                                      Ins, DAG);
5235     if (isTailCall) {
5236       ++NumTailCalls;
5237       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5238         ++NumSiblingCalls;
5239 
5240       assert(isa<GlobalAddressSDNode>(Callee) &&
5241              "Callee should be an llvm::Function object.");
5242       LLVM_DEBUG(
5243           const GlobalValue *GV =
5244               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5245           const unsigned Width =
5246               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5247           dbgs() << "TCO caller: "
5248                  << left_justify(DAG.getMachineFunction().getName(), Width)
5249                  << ", callee linkage: " << GV->getVisibility() << ", "
5250                  << GV->getLinkage() << "\n");
5251     }
5252   }
5253 
5254   if (!isTailCall && CS && CS.isMustTailCall())
5255     report_fatal_error("failed to perform tail call elimination on a call "
5256                        "site marked musttail");
5257 
5258   // When long calls (i.e. indirect calls) are always used, calls are always
5259   // made via function pointer. If we have a function name, first translate it
5260   // into a pointer.
5261   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5262       !isTailCall)
5263     Callee = LowerGlobalAddress(Callee, DAG);
5264 
5265   if (Subtarget.isSVR4ABI()) {
5266     if (Subtarget.isPPC64())
5267       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5268                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5269                               dl, DAG, InVals, CS);
5270     else
5271       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5272                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5273                               dl, DAG, InVals, CS);
5274   }
5275 
5276   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5277                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5278                           dl, DAG, InVals, CS);
5279 }
5280 
5281 SDValue PPCTargetLowering::LowerCall_32SVR4(
5282     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5283     bool isTailCall, bool isPatchPoint,
5284     const SmallVectorImpl<ISD::OutputArg> &Outs,
5285     const SmallVectorImpl<SDValue> &OutVals,
5286     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5287     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5288     ImmutableCallSite CS) const {
5289   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5290   // of the 32-bit SVR4 ABI stack frame layout.
5291 
5292   assert((CallConv == CallingConv::C ||
5293           CallConv == CallingConv::Cold ||
5294           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5295 
5296   unsigned PtrByteSize = 4;
5297 
5298   MachineFunction &MF = DAG.getMachineFunction();
5299 
5300   // Mark this function as potentially containing a function that contains a
5301   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5302   // and restoring the callers stack pointer in this functions epilog. This is
5303   // done because by tail calling the called function might overwrite the value
5304   // in this function's (MF) stack pointer stack slot 0(SP).
5305   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5306       CallConv == CallingConv::Fast)
5307     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5308 
5309   // Count how many bytes are to be pushed on the stack, including the linkage
5310   // area, parameter list area and the part of the local variable space which
5311   // contains copies of aggregates which are passed by value.
5312 
5313   // Assign locations to all of the outgoing arguments.
5314   SmallVector<CCValAssign, 16> ArgLocs;
5315   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5316 
5317   // Reserve space for the linkage area on the stack.
5318   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5319                        PtrByteSize);
5320   if (useSoftFloat())
5321     CCInfo.PreAnalyzeCallOperands(Outs);
5322 
5323   if (isVarArg) {
5324     // Handle fixed and variable vector arguments differently.
5325     // Fixed vector arguments go into registers as long as registers are
5326     // available. Variable vector arguments always go into memory.
5327     unsigned NumArgs = Outs.size();
5328 
5329     for (unsigned i = 0; i != NumArgs; ++i) {
5330       MVT ArgVT = Outs[i].VT;
5331       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5332       bool Result;
5333 
5334       if (Outs[i].IsFixed) {
5335         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5336                                CCInfo);
5337       } else {
5338         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5339                                       ArgFlags, CCInfo);
5340       }
5341 
5342       if (Result) {
5343 #ifndef NDEBUG
5344         errs() << "Call operand #" << i << " has unhandled type "
5345              << EVT(ArgVT).getEVTString() << "\n";
5346 #endif
5347         llvm_unreachable(nullptr);
5348       }
5349     }
5350   } else {
5351     // All arguments are treated the same.
5352     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5353   }
5354   CCInfo.clearWasPPCF128();
5355 
5356   // Assign locations to all of the outgoing aggregate by value arguments.
5357   SmallVector<CCValAssign, 16> ByValArgLocs;
5358   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5359 
5360   // Reserve stack space for the allocations in CCInfo.
5361   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5362 
5363   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5364 
5365   // Size of the linkage area, parameter list area and the part of the local
5366   // space variable where copies of aggregates which are passed by value are
5367   // stored.
5368   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5369 
5370   // Calculate by how many bytes the stack has to be adjusted in case of tail
5371   // call optimization.
5372   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5373 
5374   // Adjust the stack pointer for the new arguments...
5375   // These operations are automatically eliminated by the prolog/epilog pass
5376   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5377   SDValue CallSeqStart = Chain;
5378 
5379   // Load the return address and frame pointer so it can be moved somewhere else
5380   // later.
5381   SDValue LROp, FPOp;
5382   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5383 
5384   // Set up a copy of the stack pointer for use loading and storing any
5385   // arguments that may not fit in the registers available for argument
5386   // passing.
5387   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5388 
5389   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5390   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5391   SmallVector<SDValue, 8> MemOpChains;
5392 
5393   bool seenFloatArg = false;
5394   // Walk the register/memloc assignments, inserting copies/loads.
5395   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5396        i != e;
5397        ++i) {
5398     CCValAssign &VA = ArgLocs[i];
5399     SDValue Arg = OutVals[i];
5400     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5401 
5402     if (Flags.isByVal()) {
5403       // Argument is an aggregate which is passed by value, thus we need to
5404       // create a copy of it in the local variable space of the current stack
5405       // frame (which is the stack frame of the caller) and pass the address of
5406       // this copy to the callee.
5407       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5408       CCValAssign &ByValVA = ByValArgLocs[j++];
5409       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5410 
5411       // Memory reserved in the local variable space of the callers stack frame.
5412       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5413 
5414       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5415       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5416                            StackPtr, PtrOff);
5417 
5418       // Create a copy of the argument in the local area of the current
5419       // stack frame.
5420       SDValue MemcpyCall =
5421         CreateCopyOfByValArgument(Arg, PtrOff,
5422                                   CallSeqStart.getNode()->getOperand(0),
5423                                   Flags, DAG, dl);
5424 
5425       // This must go outside the CALLSEQ_START..END.
5426       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5427                                                      SDLoc(MemcpyCall));
5428       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5429                              NewCallSeqStart.getNode());
5430       Chain = CallSeqStart = NewCallSeqStart;
5431 
5432       // Pass the address of the aggregate copy on the stack either in a
5433       // physical register or in the parameter list area of the current stack
5434       // frame to the callee.
5435       Arg = PtrOff;
5436     }
5437 
5438     // When useCRBits() is true, there can be i1 arguments.
5439     // It is because getRegisterType(MVT::i1) => MVT::i1,
5440     // and for other integer types getRegisterType() => MVT::i32.
5441     // Extend i1 and ensure callee will get i32.
5442     if (Arg.getValueType() == MVT::i1)
5443       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5444                         dl, MVT::i32, Arg);
5445 
5446     if (VA.isRegLoc()) {
5447       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5448       // Put argument in a physical register.
5449       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5450     } else {
5451       // Put argument in the parameter list area of the current stack frame.
5452       assert(VA.isMemLoc());
5453       unsigned LocMemOffset = VA.getLocMemOffset();
5454 
5455       if (!isTailCall) {
5456         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5457         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5458                              StackPtr, PtrOff);
5459 
5460         MemOpChains.push_back(
5461             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5462       } else {
5463         // Calculate and remember argument location.
5464         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5465                                  TailCallArguments);
5466       }
5467     }
5468   }
5469 
5470   if (!MemOpChains.empty())
5471     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5472 
5473   // Build a sequence of copy-to-reg nodes chained together with token chain
5474   // and flag operands which copy the outgoing args into the appropriate regs.
5475   SDValue InFlag;
5476   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5477     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5478                              RegsToPass[i].second, InFlag);
5479     InFlag = Chain.getValue(1);
5480   }
5481 
5482   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5483   // registers.
5484   if (isVarArg) {
5485     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5486     SDValue Ops[] = { Chain, InFlag };
5487 
5488     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5489                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5490 
5491     InFlag = Chain.getValue(1);
5492   }
5493 
5494   if (isTailCall)
5495     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5496                     TailCallArguments);
5497 
5498   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5499                     /* unused except on PPC64 ELFv1 */ false, DAG,
5500                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5501                     NumBytes, Ins, InVals, CS);
5502 }
5503 
5504 // Copy an argument into memory, being careful to do this outside the
5505 // call sequence for the call to which the argument belongs.
5506 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5507     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5508     SelectionDAG &DAG, const SDLoc &dl) const {
5509   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5510                         CallSeqStart.getNode()->getOperand(0),
5511                         Flags, DAG, dl);
5512   // The MEMCPY must go outside the CALLSEQ_START..END.
5513   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5514   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5515                                                  SDLoc(MemcpyCall));
5516   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5517                          NewCallSeqStart.getNode());
5518   return NewCallSeqStart;
5519 }
5520 
5521 SDValue PPCTargetLowering::LowerCall_64SVR4(
5522     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5523     bool isTailCall, bool isPatchPoint,
5524     const SmallVectorImpl<ISD::OutputArg> &Outs,
5525     const SmallVectorImpl<SDValue> &OutVals,
5526     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5527     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5528     ImmutableCallSite CS) const {
5529   bool isELFv2ABI = Subtarget.isELFv2ABI();
5530   bool isLittleEndian = Subtarget.isLittleEndian();
5531   unsigned NumOps = Outs.size();
5532   bool hasNest = false;
5533   bool IsSibCall = false;
5534 
5535   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5536   unsigned PtrByteSize = 8;
5537 
5538   MachineFunction &MF = DAG.getMachineFunction();
5539 
5540   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5541     IsSibCall = true;
5542 
5543   // Mark this function as potentially containing a function that contains a
5544   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5545   // and restoring the callers stack pointer in this functions epilog. This is
5546   // done because by tail calling the called function might overwrite the value
5547   // in this function's (MF) stack pointer stack slot 0(SP).
5548   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5549       CallConv == CallingConv::Fast)
5550     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5551 
5552   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5553          "fastcc not supported on varargs functions");
5554 
5555   // Count how many bytes are to be pushed on the stack, including the linkage
5556   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5557   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5558   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5559   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5560   unsigned NumBytes = LinkageSize;
5561   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5562   unsigned &QFPR_idx = FPR_idx;
5563 
5564   static const MCPhysReg GPR[] = {
5565     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5566     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5567   };
5568   static const MCPhysReg VR[] = {
5569     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5570     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5571   };
5572 
5573   const unsigned NumGPRs = array_lengthof(GPR);
5574   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5575   const unsigned NumVRs  = array_lengthof(VR);
5576   const unsigned NumQFPRs = NumFPRs;
5577 
5578   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5579   // can be passed to the callee in registers.
5580   // For the fast calling convention, there is another check below.
5581   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5582   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5583   if (!HasParameterArea) {
5584     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5585     unsigned AvailableFPRs = NumFPRs;
5586     unsigned AvailableVRs = NumVRs;
5587     unsigned NumBytesTmp = NumBytes;
5588     for (unsigned i = 0; i != NumOps; ++i) {
5589       if (Outs[i].Flags.isNest()) continue;
5590       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5591                                 PtrByteSize, LinkageSize, ParamAreaSize,
5592                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5593                                 Subtarget.hasQPX()))
5594         HasParameterArea = true;
5595     }
5596   }
5597 
5598   // When using the fast calling convention, we don't provide backing for
5599   // arguments that will be in registers.
5600   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5601 
5602   // Avoid allocating parameter area for fastcc functions if all the arguments
5603   // can be passed in the registers.
5604   if (CallConv == CallingConv::Fast)
5605     HasParameterArea = false;
5606 
5607   // Add up all the space actually used.
5608   for (unsigned i = 0; i != NumOps; ++i) {
5609     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5610     EVT ArgVT = Outs[i].VT;
5611     EVT OrigVT = Outs[i].ArgVT;
5612 
5613     if (Flags.isNest())
5614       continue;
5615 
5616     if (CallConv == CallingConv::Fast) {
5617       if (Flags.isByVal()) {
5618         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5619         if (NumGPRsUsed > NumGPRs)
5620           HasParameterArea = true;
5621       } else {
5622         switch (ArgVT.getSimpleVT().SimpleTy) {
5623         default: llvm_unreachable("Unexpected ValueType for argument!");
5624         case MVT::i1:
5625         case MVT::i32:
5626         case MVT::i64:
5627           if (++NumGPRsUsed <= NumGPRs)
5628             continue;
5629           break;
5630         case MVT::v4i32:
5631         case MVT::v8i16:
5632         case MVT::v16i8:
5633         case MVT::v2f64:
5634         case MVT::v2i64:
5635         case MVT::v1i128:
5636         case MVT::f128:
5637           if (++NumVRsUsed <= NumVRs)
5638             continue;
5639           break;
5640         case MVT::v4f32:
5641           // When using QPX, this is handled like a FP register, otherwise, it
5642           // is an Altivec register.
5643           if (Subtarget.hasQPX()) {
5644             if (++NumFPRsUsed <= NumFPRs)
5645               continue;
5646           } else {
5647             if (++NumVRsUsed <= NumVRs)
5648               continue;
5649           }
5650           break;
5651         case MVT::f32:
5652         case MVT::f64:
5653         case MVT::v4f64: // QPX
5654         case MVT::v4i1:  // QPX
5655           if (++NumFPRsUsed <= NumFPRs)
5656             continue;
5657           break;
5658         }
5659         HasParameterArea = true;
5660       }
5661     }
5662 
5663     /* Respect alignment of argument on the stack.  */
5664     unsigned Align =
5665       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5666     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5667 
5668     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5669     if (Flags.isInConsecutiveRegsLast())
5670       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5671   }
5672 
5673   unsigned NumBytesActuallyUsed = NumBytes;
5674 
5675   // In the old ELFv1 ABI,
5676   // the prolog code of the callee may store up to 8 GPR argument registers to
5677   // the stack, allowing va_start to index over them in memory if its varargs.
5678   // Because we cannot tell if this is needed on the caller side, we have to
5679   // conservatively assume that it is needed.  As such, make sure we have at
5680   // least enough stack space for the caller to store the 8 GPRs.
5681   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5682   // really requires memory operands, e.g. a vararg function.
5683   if (HasParameterArea)
5684     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5685   else
5686     NumBytes = LinkageSize;
5687 
5688   // Tail call needs the stack to be aligned.
5689   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5690       CallConv == CallingConv::Fast)
5691     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5692 
5693   int SPDiff = 0;
5694 
5695   // Calculate by how many bytes the stack has to be adjusted in case of tail
5696   // call optimization.
5697   if (!IsSibCall)
5698     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5699 
5700   // To protect arguments on the stack from being clobbered in a tail call,
5701   // force all the loads to happen before doing any other lowering.
5702   if (isTailCall)
5703     Chain = DAG.getStackArgumentTokenFactor(Chain);
5704 
5705   // Adjust the stack pointer for the new arguments...
5706   // These operations are automatically eliminated by the prolog/epilog pass
5707   if (!IsSibCall)
5708     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5709   SDValue CallSeqStart = Chain;
5710 
5711   // Load the return address and frame pointer so it can be move somewhere else
5712   // later.
5713   SDValue LROp, FPOp;
5714   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5715 
5716   // Set up a copy of the stack pointer for use loading and storing any
5717   // arguments that may not fit in the registers available for argument
5718   // passing.
5719   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5720 
5721   // Figure out which arguments are going to go in registers, and which in
5722   // memory.  Also, if this is a vararg function, floating point operations
5723   // must be stored to our stack, and loaded into integer regs as well, if
5724   // any integer regs are available for argument passing.
5725   unsigned ArgOffset = LinkageSize;
5726 
5727   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5728   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5729 
5730   SmallVector<SDValue, 8> MemOpChains;
5731   for (unsigned i = 0; i != NumOps; ++i) {
5732     SDValue Arg = OutVals[i];
5733     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5734     EVT ArgVT = Outs[i].VT;
5735     EVT OrigVT = Outs[i].ArgVT;
5736 
5737     // PtrOff will be used to store the current argument to the stack if a
5738     // register cannot be found for it.
5739     SDValue PtrOff;
5740 
5741     // We re-align the argument offset for each argument, except when using the
5742     // fast calling convention, when we need to make sure we do that only when
5743     // we'll actually use a stack slot.
5744     auto ComputePtrOff = [&]() {
5745       /* Respect alignment of argument on the stack.  */
5746       unsigned Align =
5747         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5748       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5749 
5750       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5751 
5752       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5753     };
5754 
5755     if (CallConv != CallingConv::Fast) {
5756       ComputePtrOff();
5757 
5758       /* Compute GPR index associated with argument offset.  */
5759       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5760       GPR_idx = std::min(GPR_idx, NumGPRs);
5761     }
5762 
5763     // Promote integers to 64-bit values.
5764     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5765       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5766       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5767       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5768     }
5769 
5770     // FIXME memcpy is used way more than necessary.  Correctness first.
5771     // Note: "by value" is code for passing a structure by value, not
5772     // basic types.
5773     if (Flags.isByVal()) {
5774       // Note: Size includes alignment padding, so
5775       //   struct x { short a; char b; }
5776       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5777       // These are the proper values we need for right-justifying the
5778       // aggregate in a parameter register.
5779       unsigned Size = Flags.getByValSize();
5780 
5781       // An empty aggregate parameter takes up no storage and no
5782       // registers.
5783       if (Size == 0)
5784         continue;
5785 
5786       if (CallConv == CallingConv::Fast)
5787         ComputePtrOff();
5788 
5789       // All aggregates smaller than 8 bytes must be passed right-justified.
5790       if (Size==1 || Size==2 || Size==4) {
5791         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5792         if (GPR_idx != NumGPRs) {
5793           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5794                                         MachinePointerInfo(), VT);
5795           MemOpChains.push_back(Load.getValue(1));
5796           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5797 
5798           ArgOffset += PtrByteSize;
5799           continue;
5800         }
5801       }
5802 
5803       if (GPR_idx == NumGPRs && Size < 8) {
5804         SDValue AddPtr = PtrOff;
5805         if (!isLittleEndian) {
5806           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5807                                           PtrOff.getValueType());
5808           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5809         }
5810         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5811                                                           CallSeqStart,
5812                                                           Flags, DAG, dl);
5813         ArgOffset += PtrByteSize;
5814         continue;
5815       }
5816       // Copy entire object into memory.  There are cases where gcc-generated
5817       // code assumes it is there, even if it could be put entirely into
5818       // registers.  (This is not what the doc says.)
5819 
5820       // FIXME: The above statement is likely due to a misunderstanding of the
5821       // documents.  All arguments must be copied into the parameter area BY
5822       // THE CALLEE in the event that the callee takes the address of any
5823       // formal argument.  That has not yet been implemented.  However, it is
5824       // reasonable to use the stack area as a staging area for the register
5825       // load.
5826 
5827       // Skip this for small aggregates, as we will use the same slot for a
5828       // right-justified copy, below.
5829       if (Size >= 8)
5830         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5831                                                           CallSeqStart,
5832                                                           Flags, DAG, dl);
5833 
5834       // When a register is available, pass a small aggregate right-justified.
5835       if (Size < 8 && GPR_idx != NumGPRs) {
5836         // The easiest way to get this right-justified in a register
5837         // is to copy the structure into the rightmost portion of a
5838         // local variable slot, then load the whole slot into the
5839         // register.
5840         // FIXME: The memcpy seems to produce pretty awful code for
5841         // small aggregates, particularly for packed ones.
5842         // FIXME: It would be preferable to use the slot in the
5843         // parameter save area instead of a new local variable.
5844         SDValue AddPtr = PtrOff;
5845         if (!isLittleEndian) {
5846           SDValue Const = DAG.getConstant(8 - Size, dl, 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 
5853         // Load the slot into the register.
5854         SDValue Load =
5855             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5856         MemOpChains.push_back(Load.getValue(1));
5857         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5858 
5859         // Done with this argument.
5860         ArgOffset += PtrByteSize;
5861         continue;
5862       }
5863 
5864       // For aggregates larger than PtrByteSize, copy the pieces of the
5865       // object that fit into registers from the parameter save area.
5866       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5867         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5868         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5869         if (GPR_idx != NumGPRs) {
5870           SDValue Load =
5871               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5872           MemOpChains.push_back(Load.getValue(1));
5873           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5874           ArgOffset += PtrByteSize;
5875         } else {
5876           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5877           break;
5878         }
5879       }
5880       continue;
5881     }
5882 
5883     switch (Arg.getSimpleValueType().SimpleTy) {
5884     default: llvm_unreachable("Unexpected ValueType for argument!");
5885     case MVT::i1:
5886     case MVT::i32:
5887     case MVT::i64:
5888       if (Flags.isNest()) {
5889         // The 'nest' parameter, if any, is passed in R11.
5890         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5891         hasNest = true;
5892         break;
5893       }
5894 
5895       // These can be scalar arguments or elements of an integer array type
5896       // passed directly.  Clang may use those instead of "byval" aggregate
5897       // types to avoid forcing arguments to memory unnecessarily.
5898       if (GPR_idx != NumGPRs) {
5899         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5900       } else {
5901         if (CallConv == CallingConv::Fast)
5902           ComputePtrOff();
5903 
5904         assert(HasParameterArea &&
5905                "Parameter area must exist to pass an argument in memory.");
5906         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5907                          true, isTailCall, false, MemOpChains,
5908                          TailCallArguments, dl);
5909         if (CallConv == CallingConv::Fast)
5910           ArgOffset += PtrByteSize;
5911       }
5912       if (CallConv != CallingConv::Fast)
5913         ArgOffset += PtrByteSize;
5914       break;
5915     case MVT::f32:
5916     case MVT::f64: {
5917       // These can be scalar arguments or elements of a float array type
5918       // passed directly.  The latter are used to implement ELFv2 homogenous
5919       // float aggregates.
5920 
5921       // Named arguments go into FPRs first, and once they overflow, the
5922       // remaining arguments go into GPRs and then the parameter save area.
5923       // Unnamed arguments for vararg functions always go to GPRs and
5924       // then the parameter save area.  For now, put all arguments to vararg
5925       // routines always in both locations (FPR *and* GPR or stack slot).
5926       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5927       bool NeededLoad = false;
5928 
5929       // First load the argument into the next available FPR.
5930       if (FPR_idx != NumFPRs)
5931         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5932 
5933       // Next, load the argument into GPR or stack slot if needed.
5934       if (!NeedGPROrStack)
5935         ;
5936       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5937         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5938         // once we support fp <-> gpr moves.
5939 
5940         // In the non-vararg case, this can only ever happen in the
5941         // presence of f32 array types, since otherwise we never run
5942         // out of FPRs before running out of GPRs.
5943         SDValue ArgVal;
5944 
5945         // Double values are always passed in a single GPR.
5946         if (Arg.getValueType() != MVT::f32) {
5947           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5948 
5949         // Non-array float values are extended and passed in a GPR.
5950         } else if (!Flags.isInConsecutiveRegs()) {
5951           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5952           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5953 
5954         // If we have an array of floats, we collect every odd element
5955         // together with its predecessor into one GPR.
5956         } else if (ArgOffset % PtrByteSize != 0) {
5957           SDValue Lo, Hi;
5958           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5959           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5960           if (!isLittleEndian)
5961             std::swap(Lo, Hi);
5962           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5963 
5964         // The final element, if even, goes into the first half of a GPR.
5965         } else if (Flags.isInConsecutiveRegsLast()) {
5966           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5967           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5968           if (!isLittleEndian)
5969             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5970                                  DAG.getConstant(32, dl, MVT::i32));
5971 
5972         // Non-final even elements are skipped; they will be handled
5973         // together the with subsequent argument on the next go-around.
5974         } else
5975           ArgVal = SDValue();
5976 
5977         if (ArgVal.getNode())
5978           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5979       } else {
5980         if (CallConv == CallingConv::Fast)
5981           ComputePtrOff();
5982 
5983         // Single-precision floating-point values are mapped to the
5984         // second (rightmost) word of the stack doubleword.
5985         if (Arg.getValueType() == MVT::f32 &&
5986             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5987           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5988           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5989         }
5990 
5991         assert(HasParameterArea &&
5992                "Parameter area must exist to pass an argument in memory.");
5993         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5994                          true, isTailCall, false, MemOpChains,
5995                          TailCallArguments, dl);
5996 
5997         NeededLoad = true;
5998       }
5999       // When passing an array of floats, the array occupies consecutive
6000       // space in the argument area; only round up to the next doubleword
6001       // at the end of the array.  Otherwise, each float takes 8 bytes.
6002       if (CallConv != CallingConv::Fast || NeededLoad) {
6003         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6004                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6005         if (Flags.isInConsecutiveRegsLast())
6006           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6007       }
6008       break;
6009     }
6010     case MVT::v4f32:
6011     case MVT::v4i32:
6012     case MVT::v8i16:
6013     case MVT::v16i8:
6014     case MVT::v2f64:
6015     case MVT::v2i64:
6016     case MVT::v1i128:
6017     case MVT::f128:
6018       if (!Subtarget.hasQPX()) {
6019       // These can be scalar arguments or elements of a vector array type
6020       // passed directly.  The latter are used to implement ELFv2 homogenous
6021       // vector aggregates.
6022 
6023       // For a varargs call, named arguments go into VRs or on the stack as
6024       // usual; unnamed arguments always go to the stack or the corresponding
6025       // GPRs when within range.  For now, we always put the value in both
6026       // locations (or even all three).
6027       if (isVarArg) {
6028         assert(HasParameterArea &&
6029                "Parameter area must exist if we have a varargs call.");
6030         // We could elide this store in the case where the object fits
6031         // entirely in R registers.  Maybe later.
6032         SDValue Store =
6033             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6034         MemOpChains.push_back(Store);
6035         if (VR_idx != NumVRs) {
6036           SDValue Load =
6037               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6038           MemOpChains.push_back(Load.getValue(1));
6039           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6040         }
6041         ArgOffset += 16;
6042         for (unsigned i=0; i<16; i+=PtrByteSize) {
6043           if (GPR_idx == NumGPRs)
6044             break;
6045           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6046                                    DAG.getConstant(i, dl, PtrVT));
6047           SDValue Load =
6048               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6049           MemOpChains.push_back(Load.getValue(1));
6050           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6051         }
6052         break;
6053       }
6054 
6055       // Non-varargs Altivec params go into VRs or on the stack.
6056       if (VR_idx != NumVRs) {
6057         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6058       } else {
6059         if (CallConv == CallingConv::Fast)
6060           ComputePtrOff();
6061 
6062         assert(HasParameterArea &&
6063                "Parameter area must exist to pass an argument in memory.");
6064         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6065                          true, isTailCall, true, MemOpChains,
6066                          TailCallArguments, dl);
6067         if (CallConv == CallingConv::Fast)
6068           ArgOffset += 16;
6069       }
6070 
6071       if (CallConv != CallingConv::Fast)
6072         ArgOffset += 16;
6073       break;
6074       } // not QPX
6075 
6076       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6077              "Invalid QPX parameter type");
6078 
6079       LLVM_FALLTHROUGH;
6080     case MVT::v4f64:
6081     case MVT::v4i1: {
6082       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6083       if (isVarArg) {
6084         assert(HasParameterArea &&
6085                "Parameter area must exist if we have a varargs call.");
6086         // We could elide this store in the case where the object fits
6087         // entirely in R registers.  Maybe later.
6088         SDValue Store =
6089             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6090         MemOpChains.push_back(Store);
6091         if (QFPR_idx != NumQFPRs) {
6092           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6093                                      PtrOff, MachinePointerInfo());
6094           MemOpChains.push_back(Load.getValue(1));
6095           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6096         }
6097         ArgOffset += (IsF32 ? 16 : 32);
6098         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6099           if (GPR_idx == NumGPRs)
6100             break;
6101           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6102                                    DAG.getConstant(i, dl, PtrVT));
6103           SDValue Load =
6104               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6105           MemOpChains.push_back(Load.getValue(1));
6106           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6107         }
6108         break;
6109       }
6110 
6111       // Non-varargs QPX params go into registers or on the stack.
6112       if (QFPR_idx != NumQFPRs) {
6113         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6114       } else {
6115         if (CallConv == CallingConv::Fast)
6116           ComputePtrOff();
6117 
6118         assert(HasParameterArea &&
6119                "Parameter area must exist to pass an argument in memory.");
6120         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6121                          true, isTailCall, true, MemOpChains,
6122                          TailCallArguments, dl);
6123         if (CallConv == CallingConv::Fast)
6124           ArgOffset += (IsF32 ? 16 : 32);
6125       }
6126 
6127       if (CallConv != CallingConv::Fast)
6128         ArgOffset += (IsF32 ? 16 : 32);
6129       break;
6130       }
6131     }
6132   }
6133 
6134   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6135          "mismatch in size of parameter area");
6136   (void)NumBytesActuallyUsed;
6137 
6138   if (!MemOpChains.empty())
6139     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6140 
6141   // Check if this is an indirect call (MTCTR/BCTRL).
6142   // See PrepareCall() for more information about calls through function
6143   // pointers in the 64-bit SVR4 ABI.
6144   if (!isTailCall && !isPatchPoint &&
6145       !isFunctionGlobalAddress(Callee) &&
6146       !isa<ExternalSymbolSDNode>(Callee)) {
6147     // Load r2 into a virtual register and store it to the TOC save area.
6148     setUsesTOCBasePtr(DAG);
6149     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6150     // TOC save area offset.
6151     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6152     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6153     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6154     Chain = DAG.getStore(
6155         Val.getValue(1), dl, Val, AddPtr,
6156         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6157     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6158     // This does not mean the MTCTR instruction must use R12; it's easier
6159     // to model this as an extra parameter, so do that.
6160     if (isELFv2ABI && !isPatchPoint)
6161       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6162   }
6163 
6164   // Build a sequence of copy-to-reg nodes chained together with token chain
6165   // and flag operands which copy the outgoing args into the appropriate regs.
6166   SDValue InFlag;
6167   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6168     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6169                              RegsToPass[i].second, InFlag);
6170     InFlag = Chain.getValue(1);
6171   }
6172 
6173   if (isTailCall && !IsSibCall)
6174     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6175                     TailCallArguments);
6176 
6177   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6178                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6179                     SPDiff, NumBytes, Ins, InVals, CS);
6180 }
6181 
6182 SDValue PPCTargetLowering::LowerCall_Darwin(
6183     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6184     bool isTailCall, bool isPatchPoint,
6185     const SmallVectorImpl<ISD::OutputArg> &Outs,
6186     const SmallVectorImpl<SDValue> &OutVals,
6187     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6188     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6189     ImmutableCallSite CS) const {
6190   unsigned NumOps = Outs.size();
6191 
6192   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6193   bool isPPC64 = PtrVT == MVT::i64;
6194   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6195 
6196   MachineFunction &MF = DAG.getMachineFunction();
6197 
6198   // Mark this function as potentially containing a function that contains a
6199   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6200   // and restoring the callers stack pointer in this functions epilog. This is
6201   // done because by tail calling the called function might overwrite the value
6202   // in this function's (MF) stack pointer stack slot 0(SP).
6203   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6204       CallConv == CallingConv::Fast)
6205     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6206 
6207   // Count how many bytes are to be pushed on the stack, including the linkage
6208   // area, and parameter passing area.  We start with 24/48 bytes, which is
6209   // prereserved space for [SP][CR][LR][3 x unused].
6210   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6211   unsigned NumBytes = LinkageSize;
6212 
6213   // Add up all the space actually used.
6214   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6215   // they all go in registers, but we must reserve stack space for them for
6216   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6217   // assigned stack space in order, with padding so Altivec parameters are
6218   // 16-byte aligned.
6219   unsigned nAltivecParamsAtEnd = 0;
6220   for (unsigned i = 0; i != NumOps; ++i) {
6221     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6222     EVT ArgVT = Outs[i].VT;
6223     // Varargs Altivec parameters are padded to a 16 byte boundary.
6224     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6225         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6226         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6227       if (!isVarArg && !isPPC64) {
6228         // Non-varargs Altivec parameters go after all the non-Altivec
6229         // parameters; handle those later so we know how much padding we need.
6230         nAltivecParamsAtEnd++;
6231         continue;
6232       }
6233       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6234       NumBytes = ((NumBytes+15)/16)*16;
6235     }
6236     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6237   }
6238 
6239   // Allow for Altivec parameters at the end, if needed.
6240   if (nAltivecParamsAtEnd) {
6241     NumBytes = ((NumBytes+15)/16)*16;
6242     NumBytes += 16*nAltivecParamsAtEnd;
6243   }
6244 
6245   // The prolog code of the callee may store up to 8 GPR argument registers to
6246   // the stack, allowing va_start to index over them in memory if its varargs.
6247   // Because we cannot tell if this is needed on the caller side, we have to
6248   // conservatively assume that it is needed.  As such, make sure we have at
6249   // least enough stack space for the caller to store the 8 GPRs.
6250   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6251 
6252   // Tail call needs the stack to be aligned.
6253   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6254       CallConv == CallingConv::Fast)
6255     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6256 
6257   // Calculate by how many bytes the stack has to be adjusted in case of tail
6258   // call optimization.
6259   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6260 
6261   // To protect arguments on the stack from being clobbered in a tail call,
6262   // force all the loads to happen before doing any other lowering.
6263   if (isTailCall)
6264     Chain = DAG.getStackArgumentTokenFactor(Chain);
6265 
6266   // Adjust the stack pointer for the new arguments...
6267   // These operations are automatically eliminated by the prolog/epilog pass
6268   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6269   SDValue CallSeqStart = Chain;
6270 
6271   // Load the return address and frame pointer so it can be move somewhere else
6272   // later.
6273   SDValue LROp, FPOp;
6274   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6275 
6276   // Set up a copy of the stack pointer for use loading and storing any
6277   // arguments that may not fit in the registers available for argument
6278   // passing.
6279   SDValue StackPtr;
6280   if (isPPC64)
6281     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6282   else
6283     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6284 
6285   // Figure out which arguments are going to go in registers, and which in
6286   // memory.  Also, if this is a vararg function, floating point operations
6287   // must be stored to our stack, and loaded into integer regs as well, if
6288   // any integer regs are available for argument passing.
6289   unsigned ArgOffset = LinkageSize;
6290   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6291 
6292   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6293     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6294     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6295   };
6296   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6297     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6298     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6299   };
6300   static const MCPhysReg VR[] = {
6301     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6302     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6303   };
6304   const unsigned NumGPRs = array_lengthof(GPR_32);
6305   const unsigned NumFPRs = 13;
6306   const unsigned NumVRs  = array_lengthof(VR);
6307 
6308   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6309 
6310   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6311   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6312 
6313   SmallVector<SDValue, 8> MemOpChains;
6314   for (unsigned i = 0; i != NumOps; ++i) {
6315     SDValue Arg = OutVals[i];
6316     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6317 
6318     // PtrOff will be used to store the current argument to the stack if a
6319     // register cannot be found for it.
6320     SDValue PtrOff;
6321 
6322     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6323 
6324     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6325 
6326     // On PPC64, promote integers to 64-bit values.
6327     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6328       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6329       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6330       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6331     }
6332 
6333     // FIXME memcpy is used way more than necessary.  Correctness first.
6334     // Note: "by value" is code for passing a structure by value, not
6335     // basic types.
6336     if (Flags.isByVal()) {
6337       unsigned Size = Flags.getByValSize();
6338       // Very small objects are passed right-justified.  Everything else is
6339       // passed left-justified.
6340       if (Size==1 || Size==2) {
6341         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6342         if (GPR_idx != NumGPRs) {
6343           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6344                                         MachinePointerInfo(), VT);
6345           MemOpChains.push_back(Load.getValue(1));
6346           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6347 
6348           ArgOffset += PtrByteSize;
6349         } else {
6350           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6351                                           PtrOff.getValueType());
6352           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6353           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6354                                                             CallSeqStart,
6355                                                             Flags, DAG, dl);
6356           ArgOffset += PtrByteSize;
6357         }
6358         continue;
6359       }
6360       // Copy entire object into memory.  There are cases where gcc-generated
6361       // code assumes it is there, even if it could be put entirely into
6362       // registers.  (This is not what the doc says.)
6363       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6364                                                         CallSeqStart,
6365                                                         Flags, DAG, dl);
6366 
6367       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6368       // copy the pieces of the object that fit into registers from the
6369       // parameter save area.
6370       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6371         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6372         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6373         if (GPR_idx != NumGPRs) {
6374           SDValue Load =
6375               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6376           MemOpChains.push_back(Load.getValue(1));
6377           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6378           ArgOffset += PtrByteSize;
6379         } else {
6380           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6381           break;
6382         }
6383       }
6384       continue;
6385     }
6386 
6387     switch (Arg.getSimpleValueType().SimpleTy) {
6388     default: llvm_unreachable("Unexpected ValueType for argument!");
6389     case MVT::i1:
6390     case MVT::i32:
6391     case MVT::i64:
6392       if (GPR_idx != NumGPRs) {
6393         if (Arg.getValueType() == MVT::i1)
6394           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6395 
6396         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6397       } else {
6398         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6399                          isPPC64, isTailCall, false, MemOpChains,
6400                          TailCallArguments, dl);
6401       }
6402       ArgOffset += PtrByteSize;
6403       break;
6404     case MVT::f32:
6405     case MVT::f64:
6406       if (FPR_idx != NumFPRs) {
6407         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6408 
6409         if (isVarArg) {
6410           SDValue Store =
6411               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6412           MemOpChains.push_back(Store);
6413 
6414           // Float varargs are always shadowed in available integer registers
6415           if (GPR_idx != NumGPRs) {
6416             SDValue Load =
6417                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6418             MemOpChains.push_back(Load.getValue(1));
6419             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6420           }
6421           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6422             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6423             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6424             SDValue Load =
6425                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6426             MemOpChains.push_back(Load.getValue(1));
6427             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6428           }
6429         } else {
6430           // If we have any FPRs remaining, we may also have GPRs remaining.
6431           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6432           // GPRs.
6433           if (GPR_idx != NumGPRs)
6434             ++GPR_idx;
6435           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6436               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6437             ++GPR_idx;
6438         }
6439       } else
6440         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6441                          isPPC64, isTailCall, false, MemOpChains,
6442                          TailCallArguments, dl);
6443       if (isPPC64)
6444         ArgOffset += 8;
6445       else
6446         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6447       break;
6448     case MVT::v4f32:
6449     case MVT::v4i32:
6450     case MVT::v8i16:
6451     case MVT::v16i8:
6452       if (isVarArg) {
6453         // These go aligned on the stack, or in the corresponding R registers
6454         // when within range.  The Darwin PPC ABI doc claims they also go in
6455         // V registers; in fact gcc does this only for arguments that are
6456         // prototyped, not for those that match the ...  We do it for all
6457         // arguments, seems to work.
6458         while (ArgOffset % 16 !=0) {
6459           ArgOffset += PtrByteSize;
6460           if (GPR_idx != NumGPRs)
6461             GPR_idx++;
6462         }
6463         // We could elide this store in the case where the object fits
6464         // entirely in R registers.  Maybe later.
6465         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6466                              DAG.getConstant(ArgOffset, dl, PtrVT));
6467         SDValue Store =
6468             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6469         MemOpChains.push_back(Store);
6470         if (VR_idx != NumVRs) {
6471           SDValue Load =
6472               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6473           MemOpChains.push_back(Load.getValue(1));
6474           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6475         }
6476         ArgOffset += 16;
6477         for (unsigned i=0; i<16; i+=PtrByteSize) {
6478           if (GPR_idx == NumGPRs)
6479             break;
6480           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6481                                    DAG.getConstant(i, dl, PtrVT));
6482           SDValue Load =
6483               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6484           MemOpChains.push_back(Load.getValue(1));
6485           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6486         }
6487         break;
6488       }
6489 
6490       // Non-varargs Altivec params generally go in registers, but have
6491       // stack space allocated at the end.
6492       if (VR_idx != NumVRs) {
6493         // Doesn't have GPR space allocated.
6494         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6495       } else if (nAltivecParamsAtEnd==0) {
6496         // We are emitting Altivec params in order.
6497         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6498                          isPPC64, isTailCall, true, MemOpChains,
6499                          TailCallArguments, dl);
6500         ArgOffset += 16;
6501       }
6502       break;
6503     }
6504   }
6505   // If all Altivec parameters fit in registers, as they usually do,
6506   // they get stack space following the non-Altivec parameters.  We
6507   // don't track this here because nobody below needs it.
6508   // If there are more Altivec parameters than fit in registers emit
6509   // the stores here.
6510   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6511     unsigned j = 0;
6512     // Offset is aligned; skip 1st 12 params which go in V registers.
6513     ArgOffset = ((ArgOffset+15)/16)*16;
6514     ArgOffset += 12*16;
6515     for (unsigned i = 0; i != NumOps; ++i) {
6516       SDValue Arg = OutVals[i];
6517       EVT ArgType = Outs[i].VT;
6518       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6519           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6520         if (++j > NumVRs) {
6521           SDValue PtrOff;
6522           // We are emitting Altivec params in order.
6523           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6524                            isPPC64, isTailCall, true, MemOpChains,
6525                            TailCallArguments, dl);
6526           ArgOffset += 16;
6527         }
6528       }
6529     }
6530   }
6531 
6532   if (!MemOpChains.empty())
6533     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6534 
6535   // On Darwin, R12 must contain the address of an indirect callee.  This does
6536   // not mean the MTCTR instruction must use R12; it's easier to model this as
6537   // an extra parameter, so do that.
6538   if (!isTailCall &&
6539       !isFunctionGlobalAddress(Callee) &&
6540       !isa<ExternalSymbolSDNode>(Callee) &&
6541       !isBLACompatibleAddress(Callee, DAG))
6542     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6543                                                    PPC::R12), Callee));
6544 
6545   // Build a sequence of copy-to-reg nodes chained together with token chain
6546   // and flag operands which copy the outgoing args into the appropriate regs.
6547   SDValue InFlag;
6548   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6549     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6550                              RegsToPass[i].second, InFlag);
6551     InFlag = Chain.getValue(1);
6552   }
6553 
6554   if (isTailCall)
6555     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6556                     TailCallArguments);
6557 
6558   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6559                     /* unused except on PPC64 ELFv1 */ false, DAG,
6560                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6561                     NumBytes, Ins, InVals, CS);
6562 }
6563 
6564 bool
6565 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6566                                   MachineFunction &MF, bool isVarArg,
6567                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6568                                   LLVMContext &Context) const {
6569   SmallVector<CCValAssign, 16> RVLocs;
6570   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6571   return CCInfo.CheckReturn(
6572       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6573                 ? RetCC_PPC_Cold
6574                 : RetCC_PPC);
6575 }
6576 
6577 SDValue
6578 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6579                                bool isVarArg,
6580                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6581                                const SmallVectorImpl<SDValue> &OutVals,
6582                                const SDLoc &dl, SelectionDAG &DAG) const {
6583   SmallVector<CCValAssign, 16> RVLocs;
6584   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6585                  *DAG.getContext());
6586   CCInfo.AnalyzeReturn(Outs,
6587                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6588                            ? RetCC_PPC_Cold
6589                            : RetCC_PPC);
6590 
6591   SDValue Flag;
6592   SmallVector<SDValue, 4> RetOps(1, Chain);
6593 
6594   // Copy the result values into the output registers.
6595   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6596     CCValAssign &VA = RVLocs[i];
6597     assert(VA.isRegLoc() && "Can only return in registers!");
6598 
6599     SDValue Arg = OutVals[i];
6600 
6601     switch (VA.getLocInfo()) {
6602     default: llvm_unreachable("Unknown loc info!");
6603     case CCValAssign::Full: break;
6604     case CCValAssign::AExt:
6605       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6606       break;
6607     case CCValAssign::ZExt:
6608       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6609       break;
6610     case CCValAssign::SExt:
6611       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6612       break;
6613     }
6614 
6615     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6616     Flag = Chain.getValue(1);
6617     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6618   }
6619 
6620   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6621   const MCPhysReg *I =
6622     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6623   if (I) {
6624     for (; *I; ++I) {
6625 
6626       if (PPC::G8RCRegClass.contains(*I))
6627         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6628       else if (PPC::F8RCRegClass.contains(*I))
6629         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6630       else if (PPC::CRRCRegClass.contains(*I))
6631         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6632       else if (PPC::VRRCRegClass.contains(*I))
6633         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6634       else
6635         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6636     }
6637   }
6638 
6639   RetOps[0] = Chain;  // Update chain.
6640 
6641   // Add the flag if we have it.
6642   if (Flag.getNode())
6643     RetOps.push_back(Flag);
6644 
6645   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6646 }
6647 
6648 SDValue
6649 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6650                                                 SelectionDAG &DAG) const {
6651   SDLoc dl(Op);
6652 
6653   // Get the correct type for integers.
6654   EVT IntVT = Op.getValueType();
6655 
6656   // Get the inputs.
6657   SDValue Chain = Op.getOperand(0);
6658   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6659   // Build a DYNAREAOFFSET node.
6660   SDValue Ops[2] = {Chain, FPSIdx};
6661   SDVTList VTs = DAG.getVTList(IntVT);
6662   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6663 }
6664 
6665 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6666                                              SelectionDAG &DAG) const {
6667   // When we pop the dynamic allocation we need to restore the SP link.
6668   SDLoc dl(Op);
6669 
6670   // Get the correct type for pointers.
6671   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6672 
6673   // Construct the stack pointer operand.
6674   bool isPPC64 = Subtarget.isPPC64();
6675   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6676   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6677 
6678   // Get the operands for the STACKRESTORE.
6679   SDValue Chain = Op.getOperand(0);
6680   SDValue SaveSP = Op.getOperand(1);
6681 
6682   // Load the old link SP.
6683   SDValue LoadLinkSP =
6684       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6685 
6686   // Restore the stack pointer.
6687   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6688 
6689   // Store the old link SP.
6690   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6691 }
6692 
6693 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6694   MachineFunction &MF = DAG.getMachineFunction();
6695   bool isPPC64 = Subtarget.isPPC64();
6696   EVT PtrVT = getPointerTy(MF.getDataLayout());
6697 
6698   // Get current frame pointer save index.  The users of this index will be
6699   // primarily DYNALLOC instructions.
6700   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6701   int RASI = FI->getReturnAddrSaveIndex();
6702 
6703   // If the frame pointer save index hasn't been defined yet.
6704   if (!RASI) {
6705     // Find out what the fix offset of the frame pointer save area.
6706     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6707     // Allocate the frame index for frame pointer save area.
6708     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6709     // Save the result.
6710     FI->setReturnAddrSaveIndex(RASI);
6711   }
6712   return DAG.getFrameIndex(RASI, PtrVT);
6713 }
6714 
6715 SDValue
6716 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6717   MachineFunction &MF = DAG.getMachineFunction();
6718   bool isPPC64 = Subtarget.isPPC64();
6719   EVT PtrVT = getPointerTy(MF.getDataLayout());
6720 
6721   // Get current frame pointer save index.  The users of this index will be
6722   // primarily DYNALLOC instructions.
6723   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6724   int FPSI = FI->getFramePointerSaveIndex();
6725 
6726   // If the frame pointer save index hasn't been defined yet.
6727   if (!FPSI) {
6728     // Find out what the fix offset of the frame pointer save area.
6729     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6730     // Allocate the frame index for frame pointer save area.
6731     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6732     // Save the result.
6733     FI->setFramePointerSaveIndex(FPSI);
6734   }
6735   return DAG.getFrameIndex(FPSI, PtrVT);
6736 }
6737 
6738 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6739                                                    SelectionDAG &DAG) const {
6740   // Get the inputs.
6741   SDValue Chain = Op.getOperand(0);
6742   SDValue Size  = Op.getOperand(1);
6743   SDLoc dl(Op);
6744 
6745   // Get the correct type for pointers.
6746   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6747   // Negate the size.
6748   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6749                                 DAG.getConstant(0, dl, PtrVT), Size);
6750   // Construct a node for the frame pointer save index.
6751   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6752   // Build a DYNALLOC node.
6753   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6754   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6755   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6756 }
6757 
6758 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6759                                                      SelectionDAG &DAG) const {
6760   MachineFunction &MF = DAG.getMachineFunction();
6761 
6762   bool isPPC64 = Subtarget.isPPC64();
6763   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6764 
6765   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6766   return DAG.getFrameIndex(FI, PtrVT);
6767 }
6768 
6769 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6770                                                SelectionDAG &DAG) const {
6771   SDLoc DL(Op);
6772   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6773                      DAG.getVTList(MVT::i32, MVT::Other),
6774                      Op.getOperand(0), Op.getOperand(1));
6775 }
6776 
6777 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6778                                                 SelectionDAG &DAG) const {
6779   SDLoc DL(Op);
6780   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6781                      Op.getOperand(0), Op.getOperand(1));
6782 }
6783 
6784 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6785   if (Op.getValueType().isVector())
6786     return LowerVectorLoad(Op, DAG);
6787 
6788   assert(Op.getValueType() == MVT::i1 &&
6789          "Custom lowering only for i1 loads");
6790 
6791   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6792 
6793   SDLoc dl(Op);
6794   LoadSDNode *LD = cast<LoadSDNode>(Op);
6795 
6796   SDValue Chain = LD->getChain();
6797   SDValue BasePtr = LD->getBasePtr();
6798   MachineMemOperand *MMO = LD->getMemOperand();
6799 
6800   SDValue NewLD =
6801       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6802                      BasePtr, MVT::i8, MMO);
6803   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6804 
6805   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6806   return DAG.getMergeValues(Ops, dl);
6807 }
6808 
6809 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6810   if (Op.getOperand(1).getValueType().isVector())
6811     return LowerVectorStore(Op, DAG);
6812 
6813   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6814          "Custom lowering only for i1 stores");
6815 
6816   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6817 
6818   SDLoc dl(Op);
6819   StoreSDNode *ST = cast<StoreSDNode>(Op);
6820 
6821   SDValue Chain = ST->getChain();
6822   SDValue BasePtr = ST->getBasePtr();
6823   SDValue Value = ST->getValue();
6824   MachineMemOperand *MMO = ST->getMemOperand();
6825 
6826   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6827                       Value);
6828   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6829 }
6830 
6831 // FIXME: Remove this once the ANDI glue bug is fixed:
6832 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6833   assert(Op.getValueType() == MVT::i1 &&
6834          "Custom lowering only for i1 results");
6835 
6836   SDLoc DL(Op);
6837   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6838                      Op.getOperand(0));
6839 }
6840 
6841 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
6842                                                SelectionDAG &DAG) const {
6843 
6844   // Implements a vector truncate that fits in a vector register as a shuffle.
6845   // We want to legalize vector truncates down to where the source fits in
6846   // a vector register (and target is therefore smaller than vector register
6847   // size).  At that point legalization will try to custom lower the sub-legal
6848   // result and get here - where we can contain the truncate as a single target
6849   // operation.
6850 
6851   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
6852   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
6853   //
6854   // We will implement it for big-endian ordering as this (where x denotes
6855   // undefined):
6856   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
6857   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
6858   //
6859   // The same operation in little-endian ordering will be:
6860   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
6861   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
6862 
6863   assert(Op.getValueType().isVector() && "Vector type expected.");
6864 
6865   SDLoc DL(Op);
6866   SDValue N1 = Op.getOperand(0);
6867   unsigned SrcSize = N1.getValueType().getSizeInBits();
6868   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
6869   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
6870 
6871   EVT TrgVT = Op.getValueType();
6872   unsigned TrgNumElts = TrgVT.getVectorNumElements();
6873   EVT EltVT = TrgVT.getVectorElementType();
6874   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
6875   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
6876 
6877   // First list the elements we want to keep.
6878   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
6879   SmallVector<int, 16> ShuffV;
6880   if (Subtarget.isLittleEndian())
6881     for (unsigned i = 0; i < TrgNumElts; ++i)
6882       ShuffV.push_back(i * SizeMult);
6883   else
6884     for (unsigned i = 1; i <= TrgNumElts; ++i)
6885       ShuffV.push_back(i * SizeMult - 1);
6886 
6887   // Populate the remaining elements with undefs.
6888   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
6889     // ShuffV.push_back(i + WideNumElts);
6890     ShuffV.push_back(WideNumElts + 1);
6891 
6892   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
6893   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
6894 }
6895 
6896 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6897 /// possible.
6898 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6899   // Not FP? Not a fsel.
6900   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6901       !Op.getOperand(2).getValueType().isFloatingPoint())
6902     return Op;
6903 
6904   // We might be able to do better than this under some circumstances, but in
6905   // general, fsel-based lowering of select is a finite-math-only optimization.
6906   // For more information, see section F.3 of the 2.06 ISA specification.
6907   if (!DAG.getTarget().Options.NoInfsFPMath ||
6908       !DAG.getTarget().Options.NoNaNsFPMath)
6909     return Op;
6910   // TODO: Propagate flags from the select rather than global settings.
6911   SDNodeFlags Flags;
6912   Flags.setNoInfs(true);
6913   Flags.setNoNaNs(true);
6914 
6915   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6916 
6917   EVT ResVT = Op.getValueType();
6918   EVT CmpVT = Op.getOperand(0).getValueType();
6919   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6920   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6921   SDLoc dl(Op);
6922 
6923   // If the RHS of the comparison is a 0.0, we don't need to do the
6924   // subtraction at all.
6925   SDValue Sel1;
6926   if (isFloatingPointZero(RHS))
6927     switch (CC) {
6928     default: break;       // SETUO etc aren't handled by fsel.
6929     case ISD::SETNE:
6930       std::swap(TV, FV);
6931       LLVM_FALLTHROUGH;
6932     case ISD::SETEQ:
6933       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6934         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6935       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6936       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6937         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6938       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6939                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6940     case ISD::SETULT:
6941     case ISD::SETLT:
6942       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6943       LLVM_FALLTHROUGH;
6944     case ISD::SETOGE:
6945     case ISD::SETGE:
6946       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6947         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6948       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6949     case ISD::SETUGT:
6950     case ISD::SETGT:
6951       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6952       LLVM_FALLTHROUGH;
6953     case ISD::SETOLE:
6954     case ISD::SETLE:
6955       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6956         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6957       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6958                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6959     }
6960 
6961   SDValue Cmp;
6962   switch (CC) {
6963   default: break;       // SETUO etc aren't handled by fsel.
6964   case ISD::SETNE:
6965     std::swap(TV, FV);
6966     LLVM_FALLTHROUGH;
6967   case ISD::SETEQ:
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     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6972     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6973       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6974     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6975                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6976   case ISD::SETULT:
6977   case ISD::SETLT:
6978     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6979     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6980       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6981     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6982   case ISD::SETOGE:
6983   case ISD::SETGE:
6984     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6985     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6986       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6987     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6988   case ISD::SETUGT:
6989   case ISD::SETGT:
6990     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6991     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6992       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6993     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6994   case ISD::SETOLE:
6995   case ISD::SETLE:
6996     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6997     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6998       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6999     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7000   }
7001   return Op;
7002 }
7003 
7004 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7005                                                SelectionDAG &DAG,
7006                                                const SDLoc &dl) const {
7007   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7008   SDValue Src = Op.getOperand(0);
7009   if (Src.getValueType() == MVT::f32)
7010     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7011 
7012   SDValue Tmp;
7013   switch (Op.getSimpleValueType().SimpleTy) {
7014   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7015   case MVT::i32:
7016     Tmp = DAG.getNode(
7017         Op.getOpcode() == ISD::FP_TO_SINT
7018             ? PPCISD::FCTIWZ
7019             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7020         dl, MVT::f64, Src);
7021     break;
7022   case MVT::i64:
7023     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7024            "i64 FP_TO_UINT is supported only with FPCVT");
7025     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7026                                                         PPCISD::FCTIDUZ,
7027                       dl, MVT::f64, Src);
7028     break;
7029   }
7030 
7031   // Convert the FP value to an int value through memory.
7032   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7033     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7034   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7035   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7036   MachinePointerInfo MPI =
7037       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7038 
7039   // Emit a store to the stack slot.
7040   SDValue Chain;
7041   if (i32Stack) {
7042     MachineFunction &MF = DAG.getMachineFunction();
7043     MachineMemOperand *MMO =
7044       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7045     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7046     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7047               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7048   } else
7049     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7050 
7051   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7052   // add in a bias on big endian.
7053   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7054     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7055                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7056     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7057   }
7058 
7059   RLI.Chain = Chain;
7060   RLI.Ptr = FIPtr;
7061   RLI.MPI = MPI;
7062 }
7063 
7064 /// Custom lowers floating point to integer conversions to use
7065 /// the direct move instructions available in ISA 2.07 to avoid the
7066 /// need for load/store combinations.
7067 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7068                                                     SelectionDAG &DAG,
7069                                                     const SDLoc &dl) const {
7070   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7071   SDValue Src = Op.getOperand(0);
7072 
7073   if (Src.getValueType() == MVT::f32)
7074     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7075 
7076   SDValue Tmp;
7077   switch (Op.getSimpleValueType().SimpleTy) {
7078   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7079   case MVT::i32:
7080     Tmp = DAG.getNode(
7081         Op.getOpcode() == ISD::FP_TO_SINT
7082             ? PPCISD::FCTIWZ
7083             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7084         dl, MVT::f64, Src);
7085     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7086     break;
7087   case MVT::i64:
7088     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7089            "i64 FP_TO_UINT is supported only with FPCVT");
7090     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7091                                                         PPCISD::FCTIDUZ,
7092                       dl, MVT::f64, Src);
7093     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7094     break;
7095   }
7096   return Tmp;
7097 }
7098 
7099 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7100                                           const SDLoc &dl) const {
7101 
7102   // FP to INT conversions are legal for f128.
7103   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7104     return Op;
7105 
7106   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7107   // PPC (the libcall is not available).
7108   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7109     if (Op.getValueType() == MVT::i32) {
7110       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7111         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7112                                  MVT::f64, Op.getOperand(0),
7113                                  DAG.getIntPtrConstant(0, dl));
7114         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7115                                  MVT::f64, Op.getOperand(0),
7116                                  DAG.getIntPtrConstant(1, dl));
7117 
7118         // Add the two halves of the long double in round-to-zero mode.
7119         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7120 
7121         // Now use a smaller FP_TO_SINT.
7122         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7123       }
7124       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7125         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7126         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7127         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7128         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7129         // FIXME: generated code sucks.
7130         // TODO: Are there fast-math-flags to propagate to this FSUB?
7131         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7132                                    Op.getOperand(0), Tmp);
7133         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7134         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7135                            DAG.getConstant(0x80000000, dl, MVT::i32));
7136         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7137                                     Op.getOperand(0));
7138         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7139                                ISD::SETGE);
7140       }
7141     }
7142 
7143     return SDValue();
7144   }
7145 
7146   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7147     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7148 
7149   ReuseLoadInfo RLI;
7150   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7151 
7152   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7153                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7154 }
7155 
7156 // We're trying to insert a regular store, S, and then a load, L. If the
7157 // incoming value, O, is a load, we might just be able to have our load use the
7158 // address used by O. However, we don't know if anything else will store to
7159 // that address before we can load from it. To prevent this situation, we need
7160 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7161 // the same chain operand as O, we create a token factor from the chain results
7162 // of O and L, and we replace all uses of O's chain result with that token
7163 // factor (see spliceIntoChain below for this last part).
7164 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7165                                             ReuseLoadInfo &RLI,
7166                                             SelectionDAG &DAG,
7167                                             ISD::LoadExtType ET) const {
7168   SDLoc dl(Op);
7169   if (ET == ISD::NON_EXTLOAD &&
7170       (Op.getOpcode() == ISD::FP_TO_UINT ||
7171        Op.getOpcode() == ISD::FP_TO_SINT) &&
7172       isOperationLegalOrCustom(Op.getOpcode(),
7173                                Op.getOperand(0).getValueType())) {
7174 
7175     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7176     return true;
7177   }
7178 
7179   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7180   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7181       LD->isNonTemporal())
7182     return false;
7183   if (LD->getMemoryVT() != MemVT)
7184     return false;
7185 
7186   RLI.Ptr = LD->getBasePtr();
7187   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7188     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7189            "Non-pre-inc AM on PPC?");
7190     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7191                           LD->getOffset());
7192   }
7193 
7194   RLI.Chain = LD->getChain();
7195   RLI.MPI = LD->getPointerInfo();
7196   RLI.IsDereferenceable = LD->isDereferenceable();
7197   RLI.IsInvariant = LD->isInvariant();
7198   RLI.Alignment = LD->getAlignment();
7199   RLI.AAInfo = LD->getAAInfo();
7200   RLI.Ranges = LD->getRanges();
7201 
7202   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7203   return true;
7204 }
7205 
7206 // Given the head of the old chain, ResChain, insert a token factor containing
7207 // it and NewResChain, and make users of ResChain now be users of that token
7208 // factor.
7209 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7210 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7211                                         SDValue NewResChain,
7212                                         SelectionDAG &DAG) const {
7213   if (!ResChain)
7214     return;
7215 
7216   SDLoc dl(NewResChain);
7217 
7218   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7219                            NewResChain, DAG.getUNDEF(MVT::Other));
7220   assert(TF.getNode() != NewResChain.getNode() &&
7221          "A new TF really is required here");
7222 
7223   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7224   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7225 }
7226 
7227 /// Analyze profitability of direct move
7228 /// prefer float load to int load plus direct move
7229 /// when there is no integer use of int load
7230 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7231   SDNode *Origin = Op.getOperand(0).getNode();
7232   if (Origin->getOpcode() != ISD::LOAD)
7233     return true;
7234 
7235   // If there is no LXSIBZX/LXSIHZX, like Power8,
7236   // prefer direct move if the memory size is 1 or 2 bytes.
7237   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7238   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7239     return true;
7240 
7241   for (SDNode::use_iterator UI = Origin->use_begin(),
7242                             UE = Origin->use_end();
7243        UI != UE; ++UI) {
7244 
7245     // Only look at the users of the loaded value.
7246     if (UI.getUse().get().getResNo() != 0)
7247       continue;
7248 
7249     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7250         UI->getOpcode() != ISD::UINT_TO_FP)
7251       return true;
7252   }
7253 
7254   return false;
7255 }
7256 
7257 /// Custom lowers integer to floating point conversions to use
7258 /// the direct move instructions available in ISA 2.07 to avoid the
7259 /// need for load/store combinations.
7260 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7261                                                     SelectionDAG &DAG,
7262                                                     const SDLoc &dl) const {
7263   assert((Op.getValueType() == MVT::f32 ||
7264           Op.getValueType() == MVT::f64) &&
7265          "Invalid floating point type as target of conversion");
7266   assert(Subtarget.hasFPCVT() &&
7267          "Int to FP conversions with direct moves require FPCVT");
7268   SDValue FP;
7269   SDValue Src = Op.getOperand(0);
7270   bool SinglePrec = Op.getValueType() == MVT::f32;
7271   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7272   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7273   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7274                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7275 
7276   if (WordInt) {
7277     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7278                      dl, MVT::f64, Src);
7279     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7280   }
7281   else {
7282     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7283     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7284   }
7285 
7286   return FP;
7287 }
7288 
7289 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7290 
7291   EVT VecVT = Vec.getValueType();
7292   assert(VecVT.isVector() && "Expected a vector type.");
7293   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7294 
7295   EVT EltVT = VecVT.getVectorElementType();
7296   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7297   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7298 
7299   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7300   SmallVector<SDValue, 16> Ops(NumConcat);
7301   Ops[0] = Vec;
7302   SDValue UndefVec = DAG.getUNDEF(VecVT);
7303   for (unsigned i = 1; i < NumConcat; ++i)
7304     Ops[i] = UndefVec;
7305 
7306   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7307 }
7308 
7309 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7310                                                 const SDLoc &dl) const {
7311 
7312   unsigned Opc = Op.getOpcode();
7313   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7314          "Unexpected conversion type");
7315   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7316          "Supports conversions to v2f64/v4f32 only.");
7317 
7318   bool SignedConv = Opc == ISD::SINT_TO_FP;
7319   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7320 
7321   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7322   EVT WideVT = Wide.getValueType();
7323   unsigned WideNumElts = WideVT.getVectorNumElements();
7324   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7325 
7326   SmallVector<int, 16> ShuffV;
7327   for (unsigned i = 0; i < WideNumElts; ++i)
7328     ShuffV.push_back(i + WideNumElts);
7329 
7330   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7331   int SaveElts = FourEltRes ? 4 : 2;
7332   if (Subtarget.isLittleEndian())
7333     for (int i = 0; i < SaveElts; i++)
7334       ShuffV[i * Stride] = i;
7335   else
7336     for (int i = 1; i <= SaveElts; i++)
7337       ShuffV[i * Stride - 1] = i - 1;
7338 
7339   SDValue ShuffleSrc2 =
7340       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7341   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7342   unsigned ExtendOp =
7343       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7344 
7345   SDValue Extend;
7346   if (!Subtarget.hasP9Altivec() && SignedConv) {
7347     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7348     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7349                          DAG.getValueType(Op.getOperand(0).getValueType()));
7350   } else
7351     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7352 
7353   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7354 }
7355 
7356 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7357                                           SelectionDAG &DAG) const {
7358   SDLoc dl(Op);
7359 
7360   EVT InVT = Op.getOperand(0).getValueType();
7361   EVT OutVT = Op.getValueType();
7362   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7363       isOperationCustom(Op.getOpcode(), InVT))
7364     return LowerINT_TO_FPVector(Op, DAG, dl);
7365 
7366   // Conversions to f128 are legal.
7367   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7368     return Op;
7369 
7370   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7371     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7372       return SDValue();
7373 
7374     SDValue Value = Op.getOperand(0);
7375     // The values are now known to be -1 (false) or 1 (true). To convert this
7376     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7377     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7378     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7379 
7380     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7381 
7382     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7383 
7384     if (Op.getValueType() != MVT::v4f64)
7385       Value = DAG.getNode(ISD::FP_ROUND, dl,
7386                           Op.getValueType(), Value,
7387                           DAG.getIntPtrConstant(1, dl));
7388     return Value;
7389   }
7390 
7391   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7392   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7393     return SDValue();
7394 
7395   if (Op.getOperand(0).getValueType() == MVT::i1)
7396     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7397                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7398                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7399 
7400   // If we have direct moves, we can do all the conversion, skip the store/load
7401   // however, without FPCVT we can't do most conversions.
7402   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7403       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7404     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7405 
7406   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7407          "UINT_TO_FP is supported only with FPCVT");
7408 
7409   // If we have FCFIDS, then use it when converting to single-precision.
7410   // Otherwise, convert to double-precision and then round.
7411   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7412                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7413                                                             : PPCISD::FCFIDS)
7414                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7415                                                             : PPCISD::FCFID);
7416   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7417                   ? MVT::f32
7418                   : MVT::f64;
7419 
7420   if (Op.getOperand(0).getValueType() == MVT::i64) {
7421     SDValue SINT = Op.getOperand(0);
7422     // When converting to single-precision, we actually need to convert
7423     // to double-precision first and then round to single-precision.
7424     // To avoid double-rounding effects during that operation, we have
7425     // to prepare the input operand.  Bits that might be truncated when
7426     // converting to double-precision are replaced by a bit that won't
7427     // be lost at this stage, but is below the single-precision rounding
7428     // position.
7429     //
7430     // However, if -enable-unsafe-fp-math is in effect, accept double
7431     // rounding to avoid the extra overhead.
7432     if (Op.getValueType() == MVT::f32 &&
7433         !Subtarget.hasFPCVT() &&
7434         !DAG.getTarget().Options.UnsafeFPMath) {
7435 
7436       // Twiddle input to make sure the low 11 bits are zero.  (If this
7437       // is the case, we are guaranteed the value will fit into the 53 bit
7438       // mantissa of an IEEE double-precision value without rounding.)
7439       // If any of those low 11 bits were not zero originally, make sure
7440       // bit 12 (value 2048) is set instead, so that the final rounding
7441       // to single-precision gets the correct result.
7442       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7443                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7444       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7445                           Round, DAG.getConstant(2047, dl, MVT::i64));
7446       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7447       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7448                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7449 
7450       // However, we cannot use that value unconditionally: if the magnitude
7451       // of the input value is small, the bit-twiddling we did above might
7452       // end up visibly changing the output.  Fortunately, in that case, we
7453       // don't need to twiddle bits since the original input will convert
7454       // exactly to double-precision floating-point already.  Therefore,
7455       // construct a conditional to use the original value if the top 11
7456       // bits are all sign-bit copies, and use the rounded value computed
7457       // above otherwise.
7458       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7459                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7460       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7461                          Cond, DAG.getConstant(1, dl, MVT::i64));
7462       Cond = DAG.getSetCC(dl, MVT::i32,
7463                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7464 
7465       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7466     }
7467 
7468     ReuseLoadInfo RLI;
7469     SDValue Bits;
7470 
7471     MachineFunction &MF = DAG.getMachineFunction();
7472     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7473       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7474                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7475       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7476     } else if (Subtarget.hasLFIWAX() &&
7477                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7478       MachineMemOperand *MMO =
7479         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7480                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7481       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7482       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7483                                      DAG.getVTList(MVT::f64, MVT::Other),
7484                                      Ops, MVT::i32, MMO);
7485       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7486     } else if (Subtarget.hasFPCVT() &&
7487                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7488       MachineMemOperand *MMO =
7489         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7490                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7491       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7492       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7493                                      DAG.getVTList(MVT::f64, MVT::Other),
7494                                      Ops, MVT::i32, MMO);
7495       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7496     } else if (((Subtarget.hasLFIWAX() &&
7497                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7498                 (Subtarget.hasFPCVT() &&
7499                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7500                SINT.getOperand(0).getValueType() == MVT::i32) {
7501       MachineFrameInfo &MFI = MF.getFrameInfo();
7502       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7503 
7504       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7505       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7506 
7507       SDValue Store =
7508           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7509                        MachinePointerInfo::getFixedStack(
7510                            DAG.getMachineFunction(), FrameIdx));
7511 
7512       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7513              "Expected an i32 store");
7514 
7515       RLI.Ptr = FIdx;
7516       RLI.Chain = Store;
7517       RLI.MPI =
7518           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7519       RLI.Alignment = 4;
7520 
7521       MachineMemOperand *MMO =
7522         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7523                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7524       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7525       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7526                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7527                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7528                                      Ops, MVT::i32, MMO);
7529     } else
7530       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7531 
7532     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7533 
7534     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7535       FP = DAG.getNode(ISD::FP_ROUND, dl,
7536                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7537     return FP;
7538   }
7539 
7540   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7541          "Unhandled INT_TO_FP type in custom expander!");
7542   // Since we only generate this in 64-bit mode, we can take advantage of
7543   // 64-bit registers.  In particular, sign extend the input value into the
7544   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7545   // then lfd it and fcfid it.
7546   MachineFunction &MF = DAG.getMachineFunction();
7547   MachineFrameInfo &MFI = MF.getFrameInfo();
7548   EVT PtrVT = getPointerTy(MF.getDataLayout());
7549 
7550   SDValue Ld;
7551   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7552     ReuseLoadInfo RLI;
7553     bool ReusingLoad;
7554     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7555                                             DAG))) {
7556       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7557       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7558 
7559       SDValue Store =
7560           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7561                        MachinePointerInfo::getFixedStack(
7562                            DAG.getMachineFunction(), FrameIdx));
7563 
7564       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7565              "Expected an i32 store");
7566 
7567       RLI.Ptr = FIdx;
7568       RLI.Chain = Store;
7569       RLI.MPI =
7570           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7571       RLI.Alignment = 4;
7572     }
7573 
7574     MachineMemOperand *MMO =
7575       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7576                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7577     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7578     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7579                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7580                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7581                                  Ops, MVT::i32, MMO);
7582     if (ReusingLoad)
7583       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7584   } else {
7585     assert(Subtarget.isPPC64() &&
7586            "i32->FP without LFIWAX supported only on PPC64");
7587 
7588     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7589     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7590 
7591     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7592                                 Op.getOperand(0));
7593 
7594     // STD the extended value into the stack slot.
7595     SDValue Store = DAG.getStore(
7596         DAG.getEntryNode(), dl, Ext64, FIdx,
7597         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7598 
7599     // Load the value as a double.
7600     Ld = DAG.getLoad(
7601         MVT::f64, dl, Store, FIdx,
7602         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7603   }
7604 
7605   // FCFID it and return it.
7606   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7607   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7608     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7609                      DAG.getIntPtrConstant(0, dl));
7610   return FP;
7611 }
7612 
7613 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7614                                             SelectionDAG &DAG) const {
7615   SDLoc dl(Op);
7616   /*
7617    The rounding mode is in bits 30:31 of FPSR, and has the following
7618    settings:
7619      00 Round to nearest
7620      01 Round to 0
7621      10 Round to +inf
7622      11 Round to -inf
7623 
7624   FLT_ROUNDS, on the other hand, expects the following:
7625     -1 Undefined
7626      0 Round to 0
7627      1 Round to nearest
7628      2 Round to +inf
7629      3 Round to -inf
7630 
7631   To perform the conversion, we do:
7632     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7633   */
7634 
7635   MachineFunction &MF = DAG.getMachineFunction();
7636   EVT VT = Op.getValueType();
7637   EVT PtrVT = getPointerTy(MF.getDataLayout());
7638 
7639   // Save FP Control Word to register
7640   EVT NodeTys[] = {
7641     MVT::f64,    // return register
7642     MVT::Glue    // unused in this context
7643   };
7644   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7645 
7646   // Save FP register to stack slot
7647   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7648   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7649   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7650                                MachinePointerInfo());
7651 
7652   // Load FP Control Word from low 32 bits of stack slot.
7653   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7654   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7655   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7656 
7657   // Transform as necessary
7658   SDValue CWD1 =
7659     DAG.getNode(ISD::AND, dl, MVT::i32,
7660                 CWD, DAG.getConstant(3, dl, MVT::i32));
7661   SDValue CWD2 =
7662     DAG.getNode(ISD::SRL, dl, MVT::i32,
7663                 DAG.getNode(ISD::AND, dl, MVT::i32,
7664                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7665                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7666                             DAG.getConstant(3, dl, MVT::i32)),
7667                 DAG.getConstant(1, dl, MVT::i32));
7668 
7669   SDValue RetVal =
7670     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7671 
7672   return DAG.getNode((VT.getSizeInBits() < 16 ?
7673                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7674 }
7675 
7676 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7677   EVT VT = Op.getValueType();
7678   unsigned BitWidth = VT.getSizeInBits();
7679   SDLoc dl(Op);
7680   assert(Op.getNumOperands() == 3 &&
7681          VT == Op.getOperand(1).getValueType() &&
7682          "Unexpected SHL!");
7683 
7684   // Expand into a bunch of logical ops.  Note that these ops
7685   // depend on the PPC behavior for oversized shift amounts.
7686   SDValue Lo = Op.getOperand(0);
7687   SDValue Hi = Op.getOperand(1);
7688   SDValue Amt = Op.getOperand(2);
7689   EVT AmtVT = Amt.getValueType();
7690 
7691   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7692                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7693   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7694   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7695   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7696   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7697                              DAG.getConstant(-BitWidth, dl, AmtVT));
7698   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7699   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7700   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7701   SDValue OutOps[] = { OutLo, OutHi };
7702   return DAG.getMergeValues(OutOps, dl);
7703 }
7704 
7705 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7706   EVT VT = Op.getValueType();
7707   SDLoc dl(Op);
7708   unsigned BitWidth = VT.getSizeInBits();
7709   assert(Op.getNumOperands() == 3 &&
7710          VT == Op.getOperand(1).getValueType() &&
7711          "Unexpected SRL!");
7712 
7713   // Expand into a bunch of logical ops.  Note that these ops
7714   // depend on the PPC behavior for oversized shift amounts.
7715   SDValue Lo = Op.getOperand(0);
7716   SDValue Hi = Op.getOperand(1);
7717   SDValue Amt = Op.getOperand(2);
7718   EVT AmtVT = Amt.getValueType();
7719 
7720   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7721                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7722   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7723   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7724   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7725   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7726                              DAG.getConstant(-BitWidth, dl, AmtVT));
7727   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7728   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7729   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7730   SDValue OutOps[] = { OutLo, OutHi };
7731   return DAG.getMergeValues(OutOps, dl);
7732 }
7733 
7734 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7735   SDLoc dl(Op);
7736   EVT VT = Op.getValueType();
7737   unsigned BitWidth = VT.getSizeInBits();
7738   assert(Op.getNumOperands() == 3 &&
7739          VT == Op.getOperand(1).getValueType() &&
7740          "Unexpected SRA!");
7741 
7742   // Expand into a bunch of logical ops, followed by a select_cc.
7743   SDValue Lo = Op.getOperand(0);
7744   SDValue Hi = Op.getOperand(1);
7745   SDValue Amt = Op.getOperand(2);
7746   EVT AmtVT = Amt.getValueType();
7747 
7748   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7749                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7750   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7751   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7752   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7753   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7754                              DAG.getConstant(-BitWidth, dl, AmtVT));
7755   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7756   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7757   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7758                                   Tmp4, Tmp6, ISD::SETLE);
7759   SDValue OutOps[] = { OutLo, OutHi };
7760   return DAG.getMergeValues(OutOps, dl);
7761 }
7762 
7763 //===----------------------------------------------------------------------===//
7764 // Vector related lowering.
7765 //
7766 
7767 /// BuildSplatI - Build a canonical splati of Val with an element size of
7768 /// SplatSize.  Cast the result to VT.
7769 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7770                            SelectionDAG &DAG, const SDLoc &dl) {
7771   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7772 
7773   static const MVT VTys[] = { // canonical VT to use for each size.
7774     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7775   };
7776 
7777   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7778 
7779   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7780   if (Val == -1)
7781     SplatSize = 1;
7782 
7783   EVT CanonicalVT = VTys[SplatSize-1];
7784 
7785   // Build a canonical splat for this value.
7786   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7787 }
7788 
7789 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7790 /// specified intrinsic ID.
7791 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7792                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7793   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7794   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7795                      DAG.getConstant(IID, dl, MVT::i32), Op);
7796 }
7797 
7798 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7799 /// specified intrinsic ID.
7800 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7801                                 SelectionDAG &DAG, const SDLoc &dl,
7802                                 EVT DestVT = MVT::Other) {
7803   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7804   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7805                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7806 }
7807 
7808 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7809 /// specified intrinsic ID.
7810 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7811                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7812                                 EVT DestVT = MVT::Other) {
7813   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7814   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7815                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7816 }
7817 
7818 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7819 /// amount.  The result has the specified value type.
7820 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7821                            SelectionDAG &DAG, const SDLoc &dl) {
7822   // Force LHS/RHS to be the right type.
7823   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7824   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7825 
7826   int Ops[16];
7827   for (unsigned i = 0; i != 16; ++i)
7828     Ops[i] = i + Amt;
7829   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7830   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7831 }
7832 
7833 /// Do we have an efficient pattern in a .td file for this node?
7834 ///
7835 /// \param V - pointer to the BuildVectorSDNode being matched
7836 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7837 ///
7838 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7839 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7840 /// the opposite is true (expansion is beneficial) are:
7841 /// - The node builds a vector out of integers that are not 32 or 64-bits
7842 /// - The node builds a vector out of constants
7843 /// - The node is a "load-and-splat"
7844 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7845 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7846                                             bool HasDirectMove,
7847                                             bool HasP8Vector) {
7848   EVT VecVT = V->getValueType(0);
7849   bool RightType = VecVT == MVT::v2f64 ||
7850     (HasP8Vector && VecVT == MVT::v4f32) ||
7851     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7852   if (!RightType)
7853     return false;
7854 
7855   bool IsSplat = true;
7856   bool IsLoad = false;
7857   SDValue Op0 = V->getOperand(0);
7858 
7859   // This function is called in a block that confirms the node is not a constant
7860   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7861   // different constants.
7862   if (V->isConstant())
7863     return false;
7864   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7865     if (V->getOperand(i).isUndef())
7866       return false;
7867     // We want to expand nodes that represent load-and-splat even if the
7868     // loaded value is a floating point truncation or conversion to int.
7869     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7870         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7871          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7872         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7873          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7874         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7875          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7876       IsLoad = true;
7877     // If the operands are different or the input is not a load and has more
7878     // uses than just this BV node, then it isn't a splat.
7879     if (V->getOperand(i) != Op0 ||
7880         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7881       IsSplat = false;
7882   }
7883   return !(IsSplat && IsLoad);
7884 }
7885 
7886 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
7887 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
7888 
7889   SDLoc dl(Op);
7890   SDValue Op0 = Op->getOperand(0);
7891 
7892   if (!EnableQuadPrecision ||
7893       (Op.getValueType() != MVT::f128 ) ||
7894       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
7895       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
7896       (Op0.getOperand(1).getValueType() != MVT::i64))
7897     return SDValue();
7898 
7899   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
7900                      Op0.getOperand(1));
7901 }
7902 
7903 // If this is a case we can't handle, return null and let the default
7904 // expansion code take care of it.  If we CAN select this case, and if it
7905 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7906 // this case more efficiently than a constant pool load, lower it to the
7907 // sequence of ops that should be used.
7908 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7909                                              SelectionDAG &DAG) const {
7910   SDLoc dl(Op);
7911   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7912   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7913 
7914   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7915     // We first build an i32 vector, load it into a QPX register,
7916     // then convert it to a floating-point vector and compare it
7917     // to a zero vector to get the boolean result.
7918     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7919     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7920     MachinePointerInfo PtrInfo =
7921         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7922     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7923     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7924 
7925     assert(BVN->getNumOperands() == 4 &&
7926       "BUILD_VECTOR for v4i1 does not have 4 operands");
7927 
7928     bool IsConst = true;
7929     for (unsigned i = 0; i < 4; ++i) {
7930       if (BVN->getOperand(i).isUndef()) continue;
7931       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7932         IsConst = false;
7933         break;
7934       }
7935     }
7936 
7937     if (IsConst) {
7938       Constant *One =
7939         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7940       Constant *NegOne =
7941         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7942 
7943       Constant *CV[4];
7944       for (unsigned i = 0; i < 4; ++i) {
7945         if (BVN->getOperand(i).isUndef())
7946           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7947         else if (isNullConstant(BVN->getOperand(i)))
7948           CV[i] = NegOne;
7949         else
7950           CV[i] = One;
7951       }
7952 
7953       Constant *CP = ConstantVector::get(CV);
7954       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7955                                           16 /* alignment */);
7956 
7957       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7958       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7959       return DAG.getMemIntrinsicNode(
7960           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7961           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7962     }
7963 
7964     SmallVector<SDValue, 4> Stores;
7965     for (unsigned i = 0; i < 4; ++i) {
7966       if (BVN->getOperand(i).isUndef()) continue;
7967 
7968       unsigned Offset = 4*i;
7969       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7970       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7971 
7972       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7973       if (StoreSize > 4) {
7974         Stores.push_back(
7975             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7976                               PtrInfo.getWithOffset(Offset), MVT::i32));
7977       } else {
7978         SDValue StoreValue = BVN->getOperand(i);
7979         if (StoreSize < 4)
7980           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7981 
7982         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7983                                       PtrInfo.getWithOffset(Offset)));
7984       }
7985     }
7986 
7987     SDValue StoreChain;
7988     if (!Stores.empty())
7989       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7990     else
7991       StoreChain = DAG.getEntryNode();
7992 
7993     // Now load from v4i32 into the QPX register; this will extend it to
7994     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7995     // is typed as v4f64 because the QPX register integer states are not
7996     // explicitly represented.
7997 
7998     SDValue Ops[] = {StoreChain,
7999                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8000                      FIdx};
8001     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8002 
8003     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8004       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8005     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8006       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8007       LoadedVect);
8008 
8009     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8010 
8011     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8012   }
8013 
8014   // All other QPX vectors are handled by generic code.
8015   if (Subtarget.hasQPX())
8016     return SDValue();
8017 
8018   // Check if this is a splat of a constant value.
8019   APInt APSplatBits, APSplatUndef;
8020   unsigned SplatBitSize;
8021   bool HasAnyUndefs;
8022   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8023                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8024       SplatBitSize > 32) {
8025     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8026     // lowered to VSX instructions under certain conditions.
8027     // Without VSX, there is no pattern more efficient than expanding the node.
8028     if (Subtarget.hasVSX() &&
8029         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8030                                         Subtarget.hasP8Vector()))
8031       return Op;
8032     return SDValue();
8033   }
8034 
8035   unsigned SplatBits = APSplatBits.getZExtValue();
8036   unsigned SplatUndef = APSplatUndef.getZExtValue();
8037   unsigned SplatSize = SplatBitSize / 8;
8038 
8039   // First, handle single instruction cases.
8040 
8041   // All zeros?
8042   if (SplatBits == 0) {
8043     // Canonicalize all zero vectors to be v4i32.
8044     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8045       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8046       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8047     }
8048     return Op;
8049   }
8050 
8051   // We have XXSPLTIB for constant splats one byte wide
8052   if (Subtarget.hasP9Vector() && SplatSize == 1) {
8053     // This is a splat of 1-byte elements with some elements potentially undef.
8054     // Rather than trying to match undef in the SDAG patterns, ensure that all
8055     // elements are the same constant.
8056     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8057       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8058                                                        dl, MVT::i32));
8059       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8060       if (Op.getValueType() != MVT::v16i8)
8061         return DAG.getBitcast(Op.getValueType(), NewBV);
8062       return NewBV;
8063     }
8064 
8065     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8066     // detect that constant splats like v8i16: 0xABAB are really just splats
8067     // of a 1-byte constant. In this case, we need to convert the node to a
8068     // splat of v16i8 and a bitcast.
8069     if (Op.getValueType() != MVT::v16i8)
8070       return DAG.getBitcast(Op.getValueType(),
8071                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
8072 
8073     return Op;
8074   }
8075 
8076   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8077   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8078                     (32-SplatBitSize));
8079   if (SextVal >= -16 && SextVal <= 15)
8080     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8081 
8082   // Two instruction sequences.
8083 
8084   // If this value is in the range [-32,30] and is even, use:
8085   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8086   // If this value is in the range [17,31] and is odd, use:
8087   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8088   // If this value is in the range [-31,-17] and is odd, use:
8089   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8090   // Note the last two are three-instruction sequences.
8091   if (SextVal >= -32 && SextVal <= 31) {
8092     // To avoid having these optimizations undone by constant folding,
8093     // we convert to a pseudo that will be expanded later into one of
8094     // the above forms.
8095     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8096     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8097               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8098     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8099     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8100     if (VT == Op.getValueType())
8101       return RetVal;
8102     else
8103       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8104   }
8105 
8106   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8107   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8108   // for fneg/fabs.
8109   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8110     // Make -1 and vspltisw -1:
8111     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8112 
8113     // Make the VSLW intrinsic, computing 0x8000_0000.
8114     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8115                                    OnesV, DAG, dl);
8116 
8117     // xor by OnesV to invert it.
8118     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8119     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8120   }
8121 
8122   // Check to see if this is a wide variety of vsplti*, binop self cases.
8123   static const signed char SplatCsts[] = {
8124     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8125     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8126   };
8127 
8128   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8129     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8130     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8131     int i = SplatCsts[idx];
8132 
8133     // Figure out what shift amount will be used by altivec if shifted by i in
8134     // this splat size.
8135     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8136 
8137     // vsplti + shl self.
8138     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8139       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8140       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8141         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8142         Intrinsic::ppc_altivec_vslw
8143       };
8144       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8145       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8146     }
8147 
8148     // vsplti + srl self.
8149     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8150       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8151       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8152         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8153         Intrinsic::ppc_altivec_vsrw
8154       };
8155       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8156       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8157     }
8158 
8159     // vsplti + sra self.
8160     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8161       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8162       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8163         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8164         Intrinsic::ppc_altivec_vsraw
8165       };
8166       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8167       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8168     }
8169 
8170     // vsplti + rol self.
8171     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8172                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8173       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8174       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8175         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8176         Intrinsic::ppc_altivec_vrlw
8177       };
8178       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8179       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8180     }
8181 
8182     // t = vsplti c, result = vsldoi t, t, 1
8183     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8184       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8185       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8186       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8187     }
8188     // t = vsplti c, result = vsldoi t, t, 2
8189     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8190       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8191       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8192       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8193     }
8194     // t = vsplti c, result = vsldoi t, t, 3
8195     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8196       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8197       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8198       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8199     }
8200   }
8201 
8202   return SDValue();
8203 }
8204 
8205 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8206 /// the specified operations to build the shuffle.
8207 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8208                                       SDValue RHS, SelectionDAG &DAG,
8209                                       const SDLoc &dl) {
8210   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8211   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8212   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8213 
8214   enum {
8215     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8216     OP_VMRGHW,
8217     OP_VMRGLW,
8218     OP_VSPLTISW0,
8219     OP_VSPLTISW1,
8220     OP_VSPLTISW2,
8221     OP_VSPLTISW3,
8222     OP_VSLDOI4,
8223     OP_VSLDOI8,
8224     OP_VSLDOI12
8225   };
8226 
8227   if (OpNum == OP_COPY) {
8228     if (LHSID == (1*9+2)*9+3) return LHS;
8229     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8230     return RHS;
8231   }
8232 
8233   SDValue OpLHS, OpRHS;
8234   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8235   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8236 
8237   int ShufIdxs[16];
8238   switch (OpNum) {
8239   default: llvm_unreachable("Unknown i32 permute!");
8240   case OP_VMRGHW:
8241     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8242     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8243     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8244     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8245     break;
8246   case OP_VMRGLW:
8247     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8248     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8249     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8250     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8251     break;
8252   case OP_VSPLTISW0:
8253     for (unsigned i = 0; i != 16; ++i)
8254       ShufIdxs[i] = (i&3)+0;
8255     break;
8256   case OP_VSPLTISW1:
8257     for (unsigned i = 0; i != 16; ++i)
8258       ShufIdxs[i] = (i&3)+4;
8259     break;
8260   case OP_VSPLTISW2:
8261     for (unsigned i = 0; i != 16; ++i)
8262       ShufIdxs[i] = (i&3)+8;
8263     break;
8264   case OP_VSPLTISW3:
8265     for (unsigned i = 0; i != 16; ++i)
8266       ShufIdxs[i] = (i&3)+12;
8267     break;
8268   case OP_VSLDOI4:
8269     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8270   case OP_VSLDOI8:
8271     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8272   case OP_VSLDOI12:
8273     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8274   }
8275   EVT VT = OpLHS.getValueType();
8276   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8277   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8278   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8279   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8280 }
8281 
8282 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8283 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8284 /// SDValue.
8285 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8286                                            SelectionDAG &DAG) const {
8287   const unsigned BytesInVector = 16;
8288   bool IsLE = Subtarget.isLittleEndian();
8289   SDLoc dl(N);
8290   SDValue V1 = N->getOperand(0);
8291   SDValue V2 = N->getOperand(1);
8292   unsigned ShiftElts = 0, InsertAtByte = 0;
8293   bool Swap = false;
8294 
8295   // Shifts required to get the byte we want at element 7.
8296   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8297                                    0, 15, 14, 13, 12, 11, 10, 9};
8298   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8299                                 1, 2,  3,  4,  5,  6,  7,  8};
8300 
8301   ArrayRef<int> Mask = N->getMask();
8302   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8303 
8304   // For each mask element, find out if we're just inserting something
8305   // from V2 into V1 or vice versa.
8306   // Possible permutations inserting an element from V2 into V1:
8307   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8308   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8309   //   ...
8310   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8311   // Inserting from V1 into V2 will be similar, except mask range will be
8312   // [16,31].
8313 
8314   bool FoundCandidate = false;
8315   // If both vector operands for the shuffle are the same vector, the mask
8316   // will contain only elements from the first one and the second one will be
8317   // undef.
8318   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8319   // Go through the mask of half-words to find an element that's being moved
8320   // from one vector to the other.
8321   for (unsigned i = 0; i < BytesInVector; ++i) {
8322     unsigned CurrentElement = Mask[i];
8323     // If 2nd operand is undefined, we should only look for element 7 in the
8324     // Mask.
8325     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8326       continue;
8327 
8328     bool OtherElementsInOrder = true;
8329     // Examine the other elements in the Mask to see if they're in original
8330     // order.
8331     for (unsigned j = 0; j < BytesInVector; ++j) {
8332       if (j == i)
8333         continue;
8334       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8335       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8336       // in which we always assume we're always picking from the 1st operand.
8337       int MaskOffset =
8338           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8339       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8340         OtherElementsInOrder = false;
8341         break;
8342       }
8343     }
8344     // If other elements are in original order, we record the number of shifts
8345     // we need to get the element we want into element 7. Also record which byte
8346     // in the vector we should insert into.
8347     if (OtherElementsInOrder) {
8348       // If 2nd operand is undefined, we assume no shifts and no swapping.
8349       if (V2.isUndef()) {
8350         ShiftElts = 0;
8351         Swap = false;
8352       } else {
8353         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8354         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8355                          : BigEndianShifts[CurrentElement & 0xF];
8356         Swap = CurrentElement < BytesInVector;
8357       }
8358       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8359       FoundCandidate = true;
8360       break;
8361     }
8362   }
8363 
8364   if (!FoundCandidate)
8365     return SDValue();
8366 
8367   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8368   // optionally with VECSHL if shift is required.
8369   if (Swap)
8370     std::swap(V1, V2);
8371   if (V2.isUndef())
8372     V2 = V1;
8373   if (ShiftElts) {
8374     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8375                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8376     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8377                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8378   }
8379   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8380                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8381 }
8382 
8383 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8384 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8385 /// SDValue.
8386 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8387                                            SelectionDAG &DAG) const {
8388   const unsigned NumHalfWords = 8;
8389   const unsigned BytesInVector = NumHalfWords * 2;
8390   // Check that the shuffle is on half-words.
8391   if (!isNByteElemShuffleMask(N, 2, 1))
8392     return SDValue();
8393 
8394   bool IsLE = Subtarget.isLittleEndian();
8395   SDLoc dl(N);
8396   SDValue V1 = N->getOperand(0);
8397   SDValue V2 = N->getOperand(1);
8398   unsigned ShiftElts = 0, InsertAtByte = 0;
8399   bool Swap = false;
8400 
8401   // Shifts required to get the half-word we want at element 3.
8402   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8403   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8404 
8405   uint32_t Mask = 0;
8406   uint32_t OriginalOrderLow = 0x1234567;
8407   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8408   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8409   // 32-bit space, only need 4-bit nibbles per element.
8410   for (unsigned i = 0; i < NumHalfWords; ++i) {
8411     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8412     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8413   }
8414 
8415   // For each mask element, find out if we're just inserting something
8416   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8417   // from V2 into V1:
8418   //   X, 1, 2, 3, 4, 5, 6, 7
8419   //   0, X, 2, 3, 4, 5, 6, 7
8420   //   0, 1, X, 3, 4, 5, 6, 7
8421   //   0, 1, 2, X, 4, 5, 6, 7
8422   //   0, 1, 2, 3, X, 5, 6, 7
8423   //   0, 1, 2, 3, 4, X, 6, 7
8424   //   0, 1, 2, 3, 4, 5, X, 7
8425   //   0, 1, 2, 3, 4, 5, 6, X
8426   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8427 
8428   bool FoundCandidate = false;
8429   // Go through the mask of half-words to find an element that's being moved
8430   // from one vector to the other.
8431   for (unsigned i = 0; i < NumHalfWords; ++i) {
8432     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8433     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8434     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8435     uint32_t TargetOrder = 0x0;
8436 
8437     // If both vector operands for the shuffle are the same vector, the mask
8438     // will contain only elements from the first one and the second one will be
8439     // undef.
8440     if (V2.isUndef()) {
8441       ShiftElts = 0;
8442       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8443       TargetOrder = OriginalOrderLow;
8444       Swap = false;
8445       // Skip if not the correct element or mask of other elements don't equal
8446       // to our expected order.
8447       if (MaskOneElt == VINSERTHSrcElem &&
8448           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8449         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8450         FoundCandidate = true;
8451         break;
8452       }
8453     } else { // If both operands are defined.
8454       // Target order is [8,15] if the current mask is between [0,7].
8455       TargetOrder =
8456           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8457       // Skip if mask of other elements don't equal our expected order.
8458       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8459         // We only need the last 3 bits for the number of shifts.
8460         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8461                          : BigEndianShifts[MaskOneElt & 0x7];
8462         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8463         Swap = MaskOneElt < NumHalfWords;
8464         FoundCandidate = true;
8465         break;
8466       }
8467     }
8468   }
8469 
8470   if (!FoundCandidate)
8471     return SDValue();
8472 
8473   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8474   // optionally with VECSHL if shift is required.
8475   if (Swap)
8476     std::swap(V1, V2);
8477   if (V2.isUndef())
8478     V2 = V1;
8479   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8480   if (ShiftElts) {
8481     // Double ShiftElts because we're left shifting on v16i8 type.
8482     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8483                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8484     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8485     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8486                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8487     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8488   }
8489   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8490   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8491                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8492   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8493 }
8494 
8495 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8496 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8497 /// return the code it can be lowered into.  Worst case, it can always be
8498 /// lowered into a vperm.
8499 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8500                                                SelectionDAG &DAG) const {
8501   SDLoc dl(Op);
8502   SDValue V1 = Op.getOperand(0);
8503   SDValue V2 = Op.getOperand(1);
8504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8505   EVT VT = Op.getValueType();
8506   bool isLittleEndian = Subtarget.isLittleEndian();
8507 
8508   unsigned ShiftElts, InsertAtByte;
8509   bool Swap = false;
8510   if (Subtarget.hasP9Vector() &&
8511       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8512                            isLittleEndian)) {
8513     if (Swap)
8514       std::swap(V1, V2);
8515     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8516     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8517     if (ShiftElts) {
8518       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8519                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8520       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8521                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8522       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8523     }
8524     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8525                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8526     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8527   }
8528 
8529   if (Subtarget.hasP9Altivec()) {
8530     SDValue NewISDNode;
8531     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8532       return NewISDNode;
8533 
8534     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8535       return NewISDNode;
8536   }
8537 
8538   if (Subtarget.hasVSX() &&
8539       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8540     if (Swap)
8541       std::swap(V1, V2);
8542     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8543     SDValue Conv2 =
8544         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8545 
8546     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8547                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8548     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8549   }
8550 
8551   if (Subtarget.hasVSX() &&
8552     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8553     if (Swap)
8554       std::swap(V1, V2);
8555     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8556     SDValue Conv2 =
8557         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8558 
8559     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8560                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8561     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8562   }
8563 
8564   if (Subtarget.hasP9Vector()) {
8565      if (PPC::isXXBRHShuffleMask(SVOp)) {
8566       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8567       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8568       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8569     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8570       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8571       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8572       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8573     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8574       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8575       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8576       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8577     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8578       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8579       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8580       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8581     }
8582   }
8583 
8584   if (Subtarget.hasVSX()) {
8585     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8586       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8587 
8588       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8589       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8590                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8591       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8592     }
8593 
8594     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8595     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8596       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8597       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8598       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8599     }
8600   }
8601 
8602   if (Subtarget.hasQPX()) {
8603     if (VT.getVectorNumElements() != 4)
8604       return SDValue();
8605 
8606     if (V2.isUndef()) V2 = V1;
8607 
8608     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8609     if (AlignIdx != -1) {
8610       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8611                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8612     } else if (SVOp->isSplat()) {
8613       int SplatIdx = SVOp->getSplatIndex();
8614       if (SplatIdx >= 4) {
8615         std::swap(V1, V2);
8616         SplatIdx -= 4;
8617       }
8618 
8619       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8620                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8621     }
8622 
8623     // Lower this into a qvgpci/qvfperm pair.
8624 
8625     // Compute the qvgpci literal
8626     unsigned idx = 0;
8627     for (unsigned i = 0; i < 4; ++i) {
8628       int m = SVOp->getMaskElt(i);
8629       unsigned mm = m >= 0 ? (unsigned) m : i;
8630       idx |= mm << (3-i)*3;
8631     }
8632 
8633     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8634                              DAG.getConstant(idx, dl, MVT::i32));
8635     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8636   }
8637 
8638   // Cases that are handled by instructions that take permute immediates
8639   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8640   // selected by the instruction selector.
8641   if (V2.isUndef()) {
8642     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8643         PPC::isSplatShuffleMask(SVOp, 2) ||
8644         PPC::isSplatShuffleMask(SVOp, 4) ||
8645         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8646         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8647         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8648         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8649         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8650         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8651         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8652         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8653         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8654         (Subtarget.hasP8Altivec() && (
8655          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8656          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8657          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8658       return Op;
8659     }
8660   }
8661 
8662   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8663   // and produce a fixed permutation.  If any of these match, do not lower to
8664   // VPERM.
8665   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8666   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8667       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8668       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8669       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8670       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8671       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8672       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8673       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8674       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8675       (Subtarget.hasP8Altivec() && (
8676        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8677        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8678        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8679     return Op;
8680 
8681   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8682   // perfect shuffle table to emit an optimal matching sequence.
8683   ArrayRef<int> PermMask = SVOp->getMask();
8684 
8685   unsigned PFIndexes[4];
8686   bool isFourElementShuffle = true;
8687   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8688     unsigned EltNo = 8;   // Start out undef.
8689     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8690       if (PermMask[i*4+j] < 0)
8691         continue;   // Undef, ignore it.
8692 
8693       unsigned ByteSource = PermMask[i*4+j];
8694       if ((ByteSource & 3) != j) {
8695         isFourElementShuffle = false;
8696         break;
8697       }
8698 
8699       if (EltNo == 8) {
8700         EltNo = ByteSource/4;
8701       } else if (EltNo != ByteSource/4) {
8702         isFourElementShuffle = false;
8703         break;
8704       }
8705     }
8706     PFIndexes[i] = EltNo;
8707   }
8708 
8709   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8710   // perfect shuffle vector to determine if it is cost effective to do this as
8711   // discrete instructions, or whether we should use a vperm.
8712   // For now, we skip this for little endian until such time as we have a
8713   // little-endian perfect shuffle table.
8714   if (isFourElementShuffle && !isLittleEndian) {
8715     // Compute the index in the perfect shuffle table.
8716     unsigned PFTableIndex =
8717       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8718 
8719     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8720     unsigned Cost  = (PFEntry >> 30);
8721 
8722     // Determining when to avoid vperm is tricky.  Many things affect the cost
8723     // of vperm, particularly how many times the perm mask needs to be computed.
8724     // For example, if the perm mask can be hoisted out of a loop or is already
8725     // used (perhaps because there are multiple permutes with the same shuffle
8726     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8727     // the loop requires an extra register.
8728     //
8729     // As a compromise, we only emit discrete instructions if the shuffle can be
8730     // generated in 3 or fewer operations.  When we have loop information
8731     // available, if this block is within a loop, we should avoid using vperm
8732     // for 3-operation perms and use a constant pool load instead.
8733     if (Cost < 3)
8734       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8735   }
8736 
8737   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8738   // vector that will get spilled to the constant pool.
8739   if (V2.isUndef()) V2 = V1;
8740 
8741   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8742   // that it is in input element units, not in bytes.  Convert now.
8743 
8744   // For little endian, the order of the input vectors is reversed, and
8745   // the permutation mask is complemented with respect to 31.  This is
8746   // necessary to produce proper semantics with the big-endian-biased vperm
8747   // instruction.
8748   EVT EltVT = V1.getValueType().getVectorElementType();
8749   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8750 
8751   SmallVector<SDValue, 16> ResultMask;
8752   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8753     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8754 
8755     for (unsigned j = 0; j != BytesPerElement; ++j)
8756       if (isLittleEndian)
8757         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8758                                              dl, MVT::i32));
8759       else
8760         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8761                                              MVT::i32));
8762   }
8763 
8764   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8765   if (isLittleEndian)
8766     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8767                        V2, V1, VPermMask);
8768   else
8769     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8770                        V1, V2, VPermMask);
8771 }
8772 
8773 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8774 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8775 /// information about the intrinsic.
8776 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8777                                  bool &isDot, const PPCSubtarget &Subtarget) {
8778   unsigned IntrinsicID =
8779       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8780   CompareOpc = -1;
8781   isDot = false;
8782   switch (IntrinsicID) {
8783   default:
8784     return false;
8785   // Comparison predicates.
8786   case Intrinsic::ppc_altivec_vcmpbfp_p:
8787     CompareOpc = 966;
8788     isDot = true;
8789     break;
8790   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8791     CompareOpc = 198;
8792     isDot = true;
8793     break;
8794   case Intrinsic::ppc_altivec_vcmpequb_p:
8795     CompareOpc = 6;
8796     isDot = true;
8797     break;
8798   case Intrinsic::ppc_altivec_vcmpequh_p:
8799     CompareOpc = 70;
8800     isDot = true;
8801     break;
8802   case Intrinsic::ppc_altivec_vcmpequw_p:
8803     CompareOpc = 134;
8804     isDot = true;
8805     break;
8806   case Intrinsic::ppc_altivec_vcmpequd_p:
8807     if (Subtarget.hasP8Altivec()) {
8808       CompareOpc = 199;
8809       isDot = true;
8810     } else
8811       return false;
8812     break;
8813   case Intrinsic::ppc_altivec_vcmpneb_p:
8814   case Intrinsic::ppc_altivec_vcmpneh_p:
8815   case Intrinsic::ppc_altivec_vcmpnew_p:
8816   case Intrinsic::ppc_altivec_vcmpnezb_p:
8817   case Intrinsic::ppc_altivec_vcmpnezh_p:
8818   case Intrinsic::ppc_altivec_vcmpnezw_p:
8819     if (Subtarget.hasP9Altivec()) {
8820       switch (IntrinsicID) {
8821       default:
8822         llvm_unreachable("Unknown comparison intrinsic.");
8823       case Intrinsic::ppc_altivec_vcmpneb_p:
8824         CompareOpc = 7;
8825         break;
8826       case Intrinsic::ppc_altivec_vcmpneh_p:
8827         CompareOpc = 71;
8828         break;
8829       case Intrinsic::ppc_altivec_vcmpnew_p:
8830         CompareOpc = 135;
8831         break;
8832       case Intrinsic::ppc_altivec_vcmpnezb_p:
8833         CompareOpc = 263;
8834         break;
8835       case Intrinsic::ppc_altivec_vcmpnezh_p:
8836         CompareOpc = 327;
8837         break;
8838       case Intrinsic::ppc_altivec_vcmpnezw_p:
8839         CompareOpc = 391;
8840         break;
8841       }
8842       isDot = true;
8843     } else
8844       return false;
8845     break;
8846   case Intrinsic::ppc_altivec_vcmpgefp_p:
8847     CompareOpc = 454;
8848     isDot = true;
8849     break;
8850   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8851     CompareOpc = 710;
8852     isDot = true;
8853     break;
8854   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8855     CompareOpc = 774;
8856     isDot = true;
8857     break;
8858   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8859     CompareOpc = 838;
8860     isDot = true;
8861     break;
8862   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8863     CompareOpc = 902;
8864     isDot = true;
8865     break;
8866   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8867     if (Subtarget.hasP8Altivec()) {
8868       CompareOpc = 967;
8869       isDot = true;
8870     } else
8871       return false;
8872     break;
8873   case Intrinsic::ppc_altivec_vcmpgtub_p:
8874     CompareOpc = 518;
8875     isDot = true;
8876     break;
8877   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8878     CompareOpc = 582;
8879     isDot = true;
8880     break;
8881   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8882     CompareOpc = 646;
8883     isDot = true;
8884     break;
8885   case Intrinsic::ppc_altivec_vcmpgtud_p:
8886     if (Subtarget.hasP8Altivec()) {
8887       CompareOpc = 711;
8888       isDot = true;
8889     } else
8890       return false;
8891     break;
8892 
8893   // VSX predicate comparisons use the same infrastructure
8894   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8895   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8896   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8897   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8898   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8899   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8900     if (Subtarget.hasVSX()) {
8901       switch (IntrinsicID) {
8902       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8903         CompareOpc = 99;
8904         break;
8905       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8906         CompareOpc = 115;
8907         break;
8908       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8909         CompareOpc = 107;
8910         break;
8911       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8912         CompareOpc = 67;
8913         break;
8914       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8915         CompareOpc = 83;
8916         break;
8917       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8918         CompareOpc = 75;
8919         break;
8920       }
8921       isDot = true;
8922     } else
8923       return false;
8924     break;
8925 
8926   // Normal Comparisons.
8927   case Intrinsic::ppc_altivec_vcmpbfp:
8928     CompareOpc = 966;
8929     break;
8930   case Intrinsic::ppc_altivec_vcmpeqfp:
8931     CompareOpc = 198;
8932     break;
8933   case Intrinsic::ppc_altivec_vcmpequb:
8934     CompareOpc = 6;
8935     break;
8936   case Intrinsic::ppc_altivec_vcmpequh:
8937     CompareOpc = 70;
8938     break;
8939   case Intrinsic::ppc_altivec_vcmpequw:
8940     CompareOpc = 134;
8941     break;
8942   case Intrinsic::ppc_altivec_vcmpequd:
8943     if (Subtarget.hasP8Altivec())
8944       CompareOpc = 199;
8945     else
8946       return false;
8947     break;
8948   case Intrinsic::ppc_altivec_vcmpneb:
8949   case Intrinsic::ppc_altivec_vcmpneh:
8950   case Intrinsic::ppc_altivec_vcmpnew:
8951   case Intrinsic::ppc_altivec_vcmpnezb:
8952   case Intrinsic::ppc_altivec_vcmpnezh:
8953   case Intrinsic::ppc_altivec_vcmpnezw:
8954     if (Subtarget.hasP9Altivec())
8955       switch (IntrinsicID) {
8956       default:
8957         llvm_unreachable("Unknown comparison intrinsic.");
8958       case Intrinsic::ppc_altivec_vcmpneb:
8959         CompareOpc = 7;
8960         break;
8961       case Intrinsic::ppc_altivec_vcmpneh:
8962         CompareOpc = 71;
8963         break;
8964       case Intrinsic::ppc_altivec_vcmpnew:
8965         CompareOpc = 135;
8966         break;
8967       case Intrinsic::ppc_altivec_vcmpnezb:
8968         CompareOpc = 263;
8969         break;
8970       case Intrinsic::ppc_altivec_vcmpnezh:
8971         CompareOpc = 327;
8972         break;
8973       case Intrinsic::ppc_altivec_vcmpnezw:
8974         CompareOpc = 391;
8975         break;
8976       }
8977     else
8978       return false;
8979     break;
8980   case Intrinsic::ppc_altivec_vcmpgefp:
8981     CompareOpc = 454;
8982     break;
8983   case Intrinsic::ppc_altivec_vcmpgtfp:
8984     CompareOpc = 710;
8985     break;
8986   case Intrinsic::ppc_altivec_vcmpgtsb:
8987     CompareOpc = 774;
8988     break;
8989   case Intrinsic::ppc_altivec_vcmpgtsh:
8990     CompareOpc = 838;
8991     break;
8992   case Intrinsic::ppc_altivec_vcmpgtsw:
8993     CompareOpc = 902;
8994     break;
8995   case Intrinsic::ppc_altivec_vcmpgtsd:
8996     if (Subtarget.hasP8Altivec())
8997       CompareOpc = 967;
8998     else
8999       return false;
9000     break;
9001   case Intrinsic::ppc_altivec_vcmpgtub:
9002     CompareOpc = 518;
9003     break;
9004   case Intrinsic::ppc_altivec_vcmpgtuh:
9005     CompareOpc = 582;
9006     break;
9007   case Intrinsic::ppc_altivec_vcmpgtuw:
9008     CompareOpc = 646;
9009     break;
9010   case Intrinsic::ppc_altivec_vcmpgtud:
9011     if (Subtarget.hasP8Altivec())
9012       CompareOpc = 711;
9013     else
9014       return false;
9015     break;
9016   }
9017   return true;
9018 }
9019 
9020 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9021 /// lower, do it, otherwise return null.
9022 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9023                                                    SelectionDAG &DAG) const {
9024   unsigned IntrinsicID =
9025     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9026 
9027   SDLoc dl(Op);
9028 
9029   if (IntrinsicID == Intrinsic::thread_pointer) {
9030     // Reads the thread pointer register, used for __builtin_thread_pointer.
9031     if (Subtarget.isPPC64())
9032       return DAG.getRegister(PPC::X13, MVT::i64);
9033     return DAG.getRegister(PPC::R2, MVT::i32);
9034   }
9035 
9036   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9037   // opcode number of the comparison.
9038   int CompareOpc;
9039   bool isDot;
9040   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9041     return SDValue();    // Don't custom lower most intrinsics.
9042 
9043   // If this is a non-dot comparison, make the VCMP node and we are done.
9044   if (!isDot) {
9045     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9046                               Op.getOperand(1), Op.getOperand(2),
9047                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9048     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9049   }
9050 
9051   // Create the PPCISD altivec 'dot' comparison node.
9052   SDValue Ops[] = {
9053     Op.getOperand(2),  // LHS
9054     Op.getOperand(3),  // RHS
9055     DAG.getConstant(CompareOpc, dl, MVT::i32)
9056   };
9057   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9058   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9059 
9060   // Now that we have the comparison, emit a copy from the CR to a GPR.
9061   // This is flagged to the above dot comparison.
9062   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9063                                 DAG.getRegister(PPC::CR6, MVT::i32),
9064                                 CompNode.getValue(1));
9065 
9066   // Unpack the result based on how the target uses it.
9067   unsigned BitNo;   // Bit # of CR6.
9068   bool InvertBit;   // Invert result?
9069   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9070   default:  // Can't happen, don't crash on invalid number though.
9071   case 0:   // Return the value of the EQ bit of CR6.
9072     BitNo = 0; InvertBit = false;
9073     break;
9074   case 1:   // Return the inverted value of the EQ bit of CR6.
9075     BitNo = 0; InvertBit = true;
9076     break;
9077   case 2:   // Return the value of the LT bit of CR6.
9078     BitNo = 2; InvertBit = false;
9079     break;
9080   case 3:   // Return the inverted value of the LT bit of CR6.
9081     BitNo = 2; InvertBit = true;
9082     break;
9083   }
9084 
9085   // Shift the bit into the low position.
9086   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9087                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9088   // Isolate the bit.
9089   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9090                       DAG.getConstant(1, dl, MVT::i32));
9091 
9092   // If we are supposed to, toggle the bit.
9093   if (InvertBit)
9094     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9095                         DAG.getConstant(1, dl, MVT::i32));
9096   return Flags;
9097 }
9098 
9099 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9100                                                SelectionDAG &DAG) const {
9101   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9102   // the beginning of the argument list.
9103   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9104   SDLoc DL(Op);
9105   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9106   case Intrinsic::ppc_cfence: {
9107     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9108     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9109     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9110                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9111                                                   Op.getOperand(ArgStart + 1)),
9112                                       Op.getOperand(0)),
9113                    0);
9114   }
9115   default:
9116     break;
9117   }
9118   return SDValue();
9119 }
9120 
9121 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9122   // Check for a DIV with the same operands as this REM.
9123   for (auto UI : Op.getOperand(1)->uses()) {
9124     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9125         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9126       if (UI->getOperand(0) == Op.getOperand(0) &&
9127           UI->getOperand(1) == Op.getOperand(1))
9128         return SDValue();
9129   }
9130   return Op;
9131 }
9132 
9133 // Lower scalar BSWAP64 to xxbrd.
9134 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9135   SDLoc dl(Op);
9136   // MTVSRDD
9137   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9138                    Op.getOperand(0));
9139   // XXBRD
9140   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9141   // MFVSRD
9142   int VectorIndex = 0;
9143   if (Subtarget.isLittleEndian())
9144     VectorIndex = 1;
9145   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9146                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9147   return Op;
9148 }
9149 
9150 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9151 // compared to a value that is atomically loaded (atomic loads zero-extend).
9152 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9153                                                 SelectionDAG &DAG) const {
9154   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9155          "Expecting an atomic compare-and-swap here.");
9156   SDLoc dl(Op);
9157   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9158   EVT MemVT = AtomicNode->getMemoryVT();
9159   if (MemVT.getSizeInBits() >= 32)
9160     return Op;
9161 
9162   SDValue CmpOp = Op.getOperand(2);
9163   // If this is already correctly zero-extended, leave it alone.
9164   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9165   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9166     return Op;
9167 
9168   // Clear the high bits of the compare operand.
9169   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9170   SDValue NewCmpOp =
9171     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9172                 DAG.getConstant(MaskVal, dl, MVT::i32));
9173 
9174   // Replace the existing compare operand with the properly zero-extended one.
9175   SmallVector<SDValue, 4> Ops;
9176   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9177     Ops.push_back(AtomicNode->getOperand(i));
9178   Ops[2] = NewCmpOp;
9179   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9180   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9181   auto NodeTy =
9182     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9183   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9184 }
9185 
9186 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9187                                                  SelectionDAG &DAG) const {
9188   SDLoc dl(Op);
9189   // Create a stack slot that is 16-byte aligned.
9190   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9191   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9192   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9193   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9194 
9195   // Store the input value into Value#0 of the stack slot.
9196   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9197                                MachinePointerInfo());
9198   // Load it out.
9199   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9200 }
9201 
9202 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9203                                                   SelectionDAG &DAG) const {
9204   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9205          "Should only be called for ISD::INSERT_VECTOR_ELT");
9206 
9207   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9208   // We have legal lowering for constant indices but not for variable ones.
9209   if (!C)
9210     return SDValue();
9211 
9212   EVT VT = Op.getValueType();
9213   SDLoc dl(Op);
9214   SDValue V1 = Op.getOperand(0);
9215   SDValue V2 = Op.getOperand(1);
9216   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9217   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9218     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9219     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9220     unsigned InsertAtElement = C->getZExtValue();
9221     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9222     if (Subtarget.isLittleEndian()) {
9223       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9224     }
9225     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9226                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9227   }
9228   return Op;
9229 }
9230 
9231 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9232                                                    SelectionDAG &DAG) const {
9233   SDLoc dl(Op);
9234   SDNode *N = Op.getNode();
9235 
9236   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9237          "Unknown extract_vector_elt type");
9238 
9239   SDValue Value = N->getOperand(0);
9240 
9241   // The first part of this is like the store lowering except that we don't
9242   // need to track the chain.
9243 
9244   // The values are now known to be -1 (false) or 1 (true). To convert this
9245   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9246   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9247   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9248 
9249   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9250   // understand how to form the extending load.
9251   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9252 
9253   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9254 
9255   // Now convert to an integer and store.
9256   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9257     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9258     Value);
9259 
9260   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9261   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9262   MachinePointerInfo PtrInfo =
9263       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9264   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9265   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9266 
9267   SDValue StoreChain = DAG.getEntryNode();
9268   SDValue Ops[] = {StoreChain,
9269                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9270                    Value, FIdx};
9271   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9272 
9273   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9274     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9275 
9276   // Extract the value requested.
9277   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9278   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9279   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9280 
9281   SDValue IntVal =
9282       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9283 
9284   if (!Subtarget.useCRBits())
9285     return IntVal;
9286 
9287   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9288 }
9289 
9290 /// Lowering for QPX v4i1 loads
9291 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9292                                            SelectionDAG &DAG) const {
9293   SDLoc dl(Op);
9294   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9295   SDValue LoadChain = LN->getChain();
9296   SDValue BasePtr = LN->getBasePtr();
9297 
9298   if (Op.getValueType() == MVT::v4f64 ||
9299       Op.getValueType() == MVT::v4f32) {
9300     EVT MemVT = LN->getMemoryVT();
9301     unsigned Alignment = LN->getAlignment();
9302 
9303     // If this load is properly aligned, then it is legal.
9304     if (Alignment >= MemVT.getStoreSize())
9305       return Op;
9306 
9307     EVT ScalarVT = Op.getValueType().getScalarType(),
9308         ScalarMemVT = MemVT.getScalarType();
9309     unsigned Stride = ScalarMemVT.getStoreSize();
9310 
9311     SDValue Vals[4], LoadChains[4];
9312     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9313       SDValue Load;
9314       if (ScalarVT != ScalarMemVT)
9315         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9316                               BasePtr,
9317                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9318                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9319                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9320       else
9321         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9322                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9323                            MinAlign(Alignment, Idx * Stride),
9324                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9325 
9326       if (Idx == 0 && LN->isIndexed()) {
9327         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9328                "Unknown addressing mode on vector load");
9329         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9330                                   LN->getAddressingMode());
9331       }
9332 
9333       Vals[Idx] = Load;
9334       LoadChains[Idx] = Load.getValue(1);
9335 
9336       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9337                             DAG.getConstant(Stride, dl,
9338                                             BasePtr.getValueType()));
9339     }
9340 
9341     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9342     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9343 
9344     if (LN->isIndexed()) {
9345       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9346       return DAG.getMergeValues(RetOps, dl);
9347     }
9348 
9349     SDValue RetOps[] = { Value, TF };
9350     return DAG.getMergeValues(RetOps, dl);
9351   }
9352 
9353   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9354   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9355 
9356   // To lower v4i1 from a byte array, we load the byte elements of the
9357   // vector and then reuse the BUILD_VECTOR logic.
9358 
9359   SDValue VectElmts[4], VectElmtChains[4];
9360   for (unsigned i = 0; i < 4; ++i) {
9361     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9362     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9363 
9364     VectElmts[i] = DAG.getExtLoad(
9365         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9366         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9367         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9368     VectElmtChains[i] = VectElmts[i].getValue(1);
9369   }
9370 
9371   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9372   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9373 
9374   SDValue RVals[] = { Value, LoadChain };
9375   return DAG.getMergeValues(RVals, dl);
9376 }
9377 
9378 /// Lowering for QPX v4i1 stores
9379 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9380                                             SelectionDAG &DAG) const {
9381   SDLoc dl(Op);
9382   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9383   SDValue StoreChain = SN->getChain();
9384   SDValue BasePtr = SN->getBasePtr();
9385   SDValue Value = SN->getValue();
9386 
9387   if (Value.getValueType() == MVT::v4f64 ||
9388       Value.getValueType() == MVT::v4f32) {
9389     EVT MemVT = SN->getMemoryVT();
9390     unsigned Alignment = SN->getAlignment();
9391 
9392     // If this store is properly aligned, then it is legal.
9393     if (Alignment >= MemVT.getStoreSize())
9394       return Op;
9395 
9396     EVT ScalarVT = Value.getValueType().getScalarType(),
9397         ScalarMemVT = MemVT.getScalarType();
9398     unsigned Stride = ScalarMemVT.getStoreSize();
9399 
9400     SDValue Stores[4];
9401     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9402       SDValue Ex = DAG.getNode(
9403           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9404           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9405       SDValue Store;
9406       if (ScalarVT != ScalarMemVT)
9407         Store =
9408             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9409                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9410                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9411                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9412       else
9413         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9414                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9415                              MinAlign(Alignment, Idx * Stride),
9416                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9417 
9418       if (Idx == 0 && SN->isIndexed()) {
9419         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9420                "Unknown addressing mode on vector store");
9421         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9422                                     SN->getAddressingMode());
9423       }
9424 
9425       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9426                             DAG.getConstant(Stride, dl,
9427                                             BasePtr.getValueType()));
9428       Stores[Idx] = Store;
9429     }
9430 
9431     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9432 
9433     if (SN->isIndexed()) {
9434       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9435       return DAG.getMergeValues(RetOps, dl);
9436     }
9437 
9438     return TF;
9439   }
9440 
9441   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9442   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9443 
9444   // The values are now known to be -1 (false) or 1 (true). To convert this
9445   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9446   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9447   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9448 
9449   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9450   // understand how to form the extending load.
9451   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9452 
9453   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9454 
9455   // Now convert to an integer and store.
9456   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9457     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9458     Value);
9459 
9460   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9461   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9462   MachinePointerInfo PtrInfo =
9463       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9464   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9465   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9466 
9467   SDValue Ops[] = {StoreChain,
9468                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9469                    Value, FIdx};
9470   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9471 
9472   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9473     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9474 
9475   // Move data into the byte array.
9476   SDValue Loads[4], LoadChains[4];
9477   for (unsigned i = 0; i < 4; ++i) {
9478     unsigned Offset = 4*i;
9479     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9480     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9481 
9482     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9483                            PtrInfo.getWithOffset(Offset));
9484     LoadChains[i] = Loads[i].getValue(1);
9485   }
9486 
9487   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9488 
9489   SDValue Stores[4];
9490   for (unsigned i = 0; i < 4; ++i) {
9491     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9492     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9493 
9494     Stores[i] = DAG.getTruncStore(
9495         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9496         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9497         SN->getAAInfo());
9498   }
9499 
9500   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9501 
9502   return StoreChain;
9503 }
9504 
9505 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9506   SDLoc dl(Op);
9507   if (Op.getValueType() == MVT::v4i32) {
9508     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9509 
9510     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9511     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9512 
9513     SDValue RHSSwap =   // = vrlw RHS, 16
9514       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9515 
9516     // Shrinkify inputs to v8i16.
9517     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9518     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9519     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9520 
9521     // Low parts multiplied together, generating 32-bit results (we ignore the
9522     // top parts).
9523     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9524                                         LHS, RHS, DAG, dl, MVT::v4i32);
9525 
9526     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9527                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9528     // Shift the high parts up 16 bits.
9529     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9530                               Neg16, DAG, dl);
9531     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9532   } else if (Op.getValueType() == MVT::v8i16) {
9533     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9534 
9535     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9536 
9537     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9538                             LHS, RHS, Zero, DAG, dl);
9539   } else if (Op.getValueType() == MVT::v16i8) {
9540     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9541     bool isLittleEndian = Subtarget.isLittleEndian();
9542 
9543     // Multiply the even 8-bit parts, producing 16-bit sums.
9544     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9545                                            LHS, RHS, DAG, dl, MVT::v8i16);
9546     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9547 
9548     // Multiply the odd 8-bit parts, producing 16-bit sums.
9549     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9550                                           LHS, RHS, DAG, dl, MVT::v8i16);
9551     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9552 
9553     // Merge the results together.  Because vmuleub and vmuloub are
9554     // instructions with a big-endian bias, we must reverse the
9555     // element numbering and reverse the meaning of "odd" and "even"
9556     // when generating little endian code.
9557     int Ops[16];
9558     for (unsigned i = 0; i != 8; ++i) {
9559       if (isLittleEndian) {
9560         Ops[i*2  ] = 2*i;
9561         Ops[i*2+1] = 2*i+16;
9562       } else {
9563         Ops[i*2  ] = 2*i+1;
9564         Ops[i*2+1] = 2*i+1+16;
9565       }
9566     }
9567     if (isLittleEndian)
9568       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9569     else
9570       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9571   } else {
9572     llvm_unreachable("Unknown mul to lower!");
9573   }
9574 }
9575 
9576 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
9577 
9578   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
9579 
9580   EVT VT = Op.getValueType();
9581   assert(VT.isVector() &&
9582          "Only set vector abs as custom, scalar abs shouldn't reach here!");
9583   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
9584           VT == MVT::v16i8) &&
9585          "Unexpected vector element type!");
9586   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
9587          "Current subtarget doesn't support smax v2i64!");
9588 
9589   // For vector abs, it can be lowered to:
9590   // abs x
9591   // ==>
9592   // y = -x
9593   // smax(x, y)
9594 
9595   SDLoc dl(Op);
9596   SDValue X = Op.getOperand(0);
9597   SDValue Zero = DAG.getConstant(0, dl, VT);
9598   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
9599 
9600   // SMAX patch https://reviews.llvm.org/D47332
9601   // hasn't landed yet, so use intrinsic first here.
9602   // TODO: Should use SMAX directly once SMAX patch landed
9603   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
9604   if (VT == MVT::v2i64)
9605     BifID = Intrinsic::ppc_altivec_vmaxsd;
9606   else if (VT == MVT::v8i16)
9607     BifID = Intrinsic::ppc_altivec_vmaxsh;
9608   else if (VT == MVT::v16i8)
9609     BifID = Intrinsic::ppc_altivec_vmaxsb;
9610 
9611   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
9612 }
9613 
9614 // Custom lowering for fpext vf32 to v2f64
9615 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
9616 
9617   assert(Op.getOpcode() == ISD::FP_EXTEND &&
9618          "Should only be called for ISD::FP_EXTEND");
9619 
9620   // We only want to custom lower an extend from v2f32 to v2f64.
9621   if (Op.getValueType() != MVT::v2f64 ||
9622       Op.getOperand(0).getValueType() != MVT::v2f32)
9623     return SDValue();
9624 
9625   SDLoc dl(Op);
9626   SDValue Op0 = Op.getOperand(0);
9627 
9628   switch (Op0.getOpcode()) {
9629   default:
9630     return SDValue();
9631   case ISD::FADD:
9632   case ISD::FMUL:
9633   case ISD::FSUB: {
9634     SDValue NewLoad[2];
9635     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
9636       // Ensure both input are loads.
9637       SDValue LdOp = Op0.getOperand(i);
9638       if (LdOp.getOpcode() != ISD::LOAD)
9639         return SDValue();
9640       // Generate new load node.
9641       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
9642       SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9643       NewLoad[i] =
9644         DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9645                                 DAG.getVTList(MVT::v4f32, MVT::Other),
9646                                 LoadOps, LD->getMemoryVT(),
9647                                 LD->getMemOperand());
9648     }
9649     SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32,
9650                               NewLoad[0], NewLoad[1],
9651                               Op0.getNode()->getFlags());
9652     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp);
9653   }
9654   case ISD::LOAD: {
9655     LoadSDNode *LD = cast<LoadSDNode>(Op0);
9656     SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9657     SDValue NewLd =
9658       DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9659                               DAG.getVTList(MVT::v4f32, MVT::Other),
9660                               LoadOps, LD->getMemoryVT(), LD->getMemOperand());
9661     return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd);
9662   }
9663   }
9664   llvm_unreachable("ERROR:Should return for all cases within swtich.");
9665 }
9666 
9667 /// LowerOperation - Provide custom lowering hooks for some operations.
9668 ///
9669 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9670   switch (Op.getOpcode()) {
9671   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9672   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9673   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9674   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9675   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9676   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9677   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9678   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9679   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9680 
9681   // Variable argument lowering.
9682   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9683   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9684   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9685 
9686   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9687   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9688   case ISD::GET_DYNAMIC_AREA_OFFSET:
9689     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9690 
9691   // Exception handling lowering.
9692   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9693   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9694   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9695 
9696   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9697   case ISD::STORE:              return LowerSTORE(Op, DAG);
9698   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9699   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9700   case ISD::FP_TO_UINT:
9701   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9702   case ISD::UINT_TO_FP:
9703   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9704   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9705 
9706   // Lower 64-bit shifts.
9707   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9708   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9709   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9710 
9711   // Vector-related lowering.
9712   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9713   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9714   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9715   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9716   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9717   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9718   case ISD::MUL:                return LowerMUL(Op, DAG);
9719   case ISD::ABS:                return LowerABS(Op, DAG);
9720   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
9721 
9722   // For counter-based loop handling.
9723   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9724 
9725   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9726 
9727   // Frame & Return address.
9728   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9729   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9730 
9731   case ISD::INTRINSIC_VOID:
9732     return LowerINTRINSIC_VOID(Op, DAG);
9733   case ISD::SREM:
9734   case ISD::UREM:
9735     return LowerREM(Op, DAG);
9736   case ISD::BSWAP:
9737     return LowerBSWAP(Op, DAG);
9738   case ISD::ATOMIC_CMP_SWAP:
9739     return LowerATOMIC_CMP_SWAP(Op, DAG);
9740   }
9741 }
9742 
9743 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9744                                            SmallVectorImpl<SDValue>&Results,
9745                                            SelectionDAG &DAG) const {
9746   SDLoc dl(N);
9747   switch (N->getOpcode()) {
9748   default:
9749     llvm_unreachable("Do not know how to custom type legalize this operation!");
9750   case ISD::READCYCLECOUNTER: {
9751     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9752     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9753 
9754     Results.push_back(RTB);
9755     Results.push_back(RTB.getValue(1));
9756     Results.push_back(RTB.getValue(2));
9757     break;
9758   }
9759   case ISD::INTRINSIC_W_CHAIN: {
9760     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9761         Intrinsic::ppc_is_decremented_ctr_nonzero)
9762       break;
9763 
9764     assert(N->getValueType(0) == MVT::i1 &&
9765            "Unexpected result type for CTR decrement intrinsic");
9766     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9767                                  N->getValueType(0));
9768     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9769     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9770                                  N->getOperand(1));
9771 
9772     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
9773     Results.push_back(NewInt.getValue(1));
9774     break;
9775   }
9776   case ISD::VAARG: {
9777     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9778       return;
9779 
9780     EVT VT = N->getValueType(0);
9781 
9782     if (VT == MVT::i64) {
9783       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9784 
9785       Results.push_back(NewNode);
9786       Results.push_back(NewNode.getValue(1));
9787     }
9788     return;
9789   }
9790   case ISD::FP_TO_SINT:
9791   case ISD::FP_TO_UINT:
9792     // LowerFP_TO_INT() can only handle f32 and f64.
9793     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9794       return;
9795     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9796     return;
9797   case ISD::TRUNCATE: {
9798     EVT TrgVT = N->getValueType(0);
9799     if (TrgVT.isVector() &&
9800         isOperationCustom(N->getOpcode(), TrgVT) &&
9801         N->getOperand(0).getValueType().getSizeInBits() <= 128)
9802       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
9803     return;
9804   }
9805   case ISD::BITCAST:
9806     // Don't handle bitcast here.
9807     return;
9808   }
9809 }
9810 
9811 //===----------------------------------------------------------------------===//
9812 //  Other Lowering Code
9813 //===----------------------------------------------------------------------===//
9814 
9815 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9816   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9817   Function *Func = Intrinsic::getDeclaration(M, Id);
9818   return Builder.CreateCall(Func, {});
9819 }
9820 
9821 // The mappings for emitLeading/TrailingFence is taken from
9822 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9823 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9824                                                  Instruction *Inst,
9825                                                  AtomicOrdering Ord) const {
9826   if (Ord == AtomicOrdering::SequentiallyConsistent)
9827     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9828   if (isReleaseOrStronger(Ord))
9829     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9830   return nullptr;
9831 }
9832 
9833 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9834                                                   Instruction *Inst,
9835                                                   AtomicOrdering Ord) const {
9836   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9837     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9838     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9839     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9840     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9841       return Builder.CreateCall(
9842           Intrinsic::getDeclaration(
9843               Builder.GetInsertBlock()->getParent()->getParent(),
9844               Intrinsic::ppc_cfence, {Inst->getType()}),
9845           {Inst});
9846     // FIXME: Can use isync for rmw operation.
9847     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9848   }
9849   return nullptr;
9850 }
9851 
9852 MachineBasicBlock *
9853 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9854                                     unsigned AtomicSize,
9855                                     unsigned BinOpcode,
9856                                     unsigned CmpOpcode,
9857                                     unsigned CmpPred) const {
9858   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9859   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9860 
9861   auto LoadMnemonic = PPC::LDARX;
9862   auto StoreMnemonic = PPC::STDCX;
9863   switch (AtomicSize) {
9864   default:
9865     llvm_unreachable("Unexpected size of atomic entity");
9866   case 1:
9867     LoadMnemonic = PPC::LBARX;
9868     StoreMnemonic = PPC::STBCX;
9869     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9870     break;
9871   case 2:
9872     LoadMnemonic = PPC::LHARX;
9873     StoreMnemonic = PPC::STHCX;
9874     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9875     break;
9876   case 4:
9877     LoadMnemonic = PPC::LWARX;
9878     StoreMnemonic = PPC::STWCX;
9879     break;
9880   case 8:
9881     LoadMnemonic = PPC::LDARX;
9882     StoreMnemonic = PPC::STDCX;
9883     break;
9884   }
9885 
9886   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9887   MachineFunction *F = BB->getParent();
9888   MachineFunction::iterator It = ++BB->getIterator();
9889 
9890   unsigned dest = MI.getOperand(0).getReg();
9891   unsigned ptrA = MI.getOperand(1).getReg();
9892   unsigned ptrB = MI.getOperand(2).getReg();
9893   unsigned incr = MI.getOperand(3).getReg();
9894   DebugLoc dl = MI.getDebugLoc();
9895 
9896   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9897   MachineBasicBlock *loop2MBB =
9898     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9899   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9900   F->insert(It, loopMBB);
9901   if (CmpOpcode)
9902     F->insert(It, loop2MBB);
9903   F->insert(It, exitMBB);
9904   exitMBB->splice(exitMBB->begin(), BB,
9905                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9906   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9907 
9908   MachineRegisterInfo &RegInfo = F->getRegInfo();
9909   unsigned TmpReg = (!BinOpcode) ? incr :
9910     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9911                                            : &PPC::GPRCRegClass);
9912 
9913   //  thisMBB:
9914   //   ...
9915   //   fallthrough --> loopMBB
9916   BB->addSuccessor(loopMBB);
9917 
9918   //  loopMBB:
9919   //   l[wd]arx dest, ptr
9920   //   add r0, dest, incr
9921   //   st[wd]cx. r0, ptr
9922   //   bne- loopMBB
9923   //   fallthrough --> exitMBB
9924 
9925   // For max/min...
9926   //  loopMBB:
9927   //   l[wd]arx dest, ptr
9928   //   cmpl?[wd] incr, dest
9929   //   bgt exitMBB
9930   //  loop2MBB:
9931   //   st[wd]cx. dest, ptr
9932   //   bne- loopMBB
9933   //   fallthrough --> exitMBB
9934 
9935   BB = loopMBB;
9936   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9937     .addReg(ptrA).addReg(ptrB);
9938   if (BinOpcode)
9939     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9940   if (CmpOpcode) {
9941     // Signed comparisons of byte or halfword values must be sign-extended.
9942     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9943       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9944       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9945               ExtReg).addReg(dest);
9946       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9947         .addReg(incr).addReg(ExtReg);
9948     } else
9949       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9950         .addReg(incr).addReg(dest);
9951 
9952     BuildMI(BB, dl, TII->get(PPC::BCC))
9953       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9954     BB->addSuccessor(loop2MBB);
9955     BB->addSuccessor(exitMBB);
9956     BB = loop2MBB;
9957   }
9958   BuildMI(BB, dl, TII->get(StoreMnemonic))
9959     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9960   BuildMI(BB, dl, TII->get(PPC::BCC))
9961     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9962   BB->addSuccessor(loopMBB);
9963   BB->addSuccessor(exitMBB);
9964 
9965   //  exitMBB:
9966   //   ...
9967   BB = exitMBB;
9968   return BB;
9969 }
9970 
9971 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
9972     MachineInstr &MI, MachineBasicBlock *BB,
9973     bool is8bit, // operation
9974     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
9975   // If we support part-word atomic mnemonics, just use them
9976   if (Subtarget.hasPartwordAtomics())
9977     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
9978                             CmpPred);
9979 
9980   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9981   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9982   // In 64 bit mode we have to use 64 bits for addresses, even though the
9983   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9984   // registers without caring whether they're 32 or 64, but here we're
9985   // doing actual arithmetic on the addresses.
9986   bool is64bit = Subtarget.isPPC64();
9987   bool isLittleEndian = Subtarget.isLittleEndian();
9988   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9989 
9990   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9991   MachineFunction *F = BB->getParent();
9992   MachineFunction::iterator It = ++BB->getIterator();
9993 
9994   unsigned dest = MI.getOperand(0).getReg();
9995   unsigned ptrA = MI.getOperand(1).getReg();
9996   unsigned ptrB = MI.getOperand(2).getReg();
9997   unsigned incr = MI.getOperand(3).getReg();
9998   DebugLoc dl = MI.getDebugLoc();
9999 
10000   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10001   MachineBasicBlock *loop2MBB =
10002       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10003   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10004   F->insert(It, loopMBB);
10005   if (CmpOpcode)
10006     F->insert(It, loop2MBB);
10007   F->insert(It, exitMBB);
10008   exitMBB->splice(exitMBB->begin(), BB,
10009                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10010   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10011 
10012   MachineRegisterInfo &RegInfo = F->getRegInfo();
10013   const TargetRegisterClass *RC =
10014       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10015   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10016 
10017   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10018   unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10019   unsigned ShiftReg =
10020       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10021   unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10022   unsigned MaskReg = RegInfo.createVirtualRegister(GPRC);
10023   unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10024   unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10025   unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10026   unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10027   unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10028   unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10029   unsigned Ptr1Reg;
10030   unsigned TmpReg =
10031       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10032 
10033   //  thisMBB:
10034   //   ...
10035   //   fallthrough --> loopMBB
10036   BB->addSuccessor(loopMBB);
10037 
10038   // The 4-byte load must be aligned, while a char or short may be
10039   // anywhere in the word.  Hence all this nasty bookkeeping code.
10040   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10041   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10042   //   xori shift, shift1, 24 [16]
10043   //   rlwinm ptr, ptr1, 0, 0, 29
10044   //   slw incr2, incr, shift
10045   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10046   //   slw mask, mask2, shift
10047   //  loopMBB:
10048   //   lwarx tmpDest, ptr
10049   //   add tmp, tmpDest, incr2
10050   //   andc tmp2, tmpDest, mask
10051   //   and tmp3, tmp, mask
10052   //   or tmp4, tmp3, tmp2
10053   //   stwcx. tmp4, ptr
10054   //   bne- loopMBB
10055   //   fallthrough --> exitMBB
10056   //   srw dest, tmpDest, shift
10057   if (ptrA != ZeroReg) {
10058     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10059     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10060         .addReg(ptrA)
10061         .addReg(ptrB);
10062   } else {
10063     Ptr1Reg = ptrB;
10064   }
10065   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10066   // mode.
10067   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10068       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10069       .addImm(3)
10070       .addImm(27)
10071       .addImm(is8bit ? 28 : 27);
10072   if (!isLittleEndian)
10073     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10074         .addReg(Shift1Reg)
10075         .addImm(is8bit ? 24 : 16);
10076   if (is64bit)
10077     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10078         .addReg(Ptr1Reg)
10079         .addImm(0)
10080         .addImm(61);
10081   else
10082     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10083         .addReg(Ptr1Reg)
10084         .addImm(0)
10085         .addImm(0)
10086         .addImm(29);
10087   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10088   if (is8bit)
10089     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10090   else {
10091     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10092     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10093         .addReg(Mask3Reg)
10094         .addImm(65535);
10095   }
10096   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10097       .addReg(Mask2Reg)
10098       .addReg(ShiftReg);
10099 
10100   BB = loopMBB;
10101   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10102       .addReg(ZeroReg)
10103       .addReg(PtrReg);
10104   if (BinOpcode)
10105     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10106         .addReg(Incr2Reg)
10107         .addReg(TmpDestReg);
10108   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10109       .addReg(TmpDestReg)
10110       .addReg(MaskReg);
10111   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10112   if (CmpOpcode) {
10113     // For unsigned comparisons, we can directly compare the shifted values.
10114     // For signed comparisons we shift and sign extend.
10115     unsigned SReg = RegInfo.createVirtualRegister(GPRC);
10116     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10117         .addReg(TmpDestReg)
10118         .addReg(MaskReg);
10119     unsigned ValueReg = SReg;
10120     unsigned CmpReg = Incr2Reg;
10121     if (CmpOpcode == PPC::CMPW) {
10122       ValueReg = RegInfo.createVirtualRegister(GPRC);
10123       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10124           .addReg(SReg)
10125           .addReg(ShiftReg);
10126       unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC);
10127       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10128           .addReg(ValueReg);
10129       ValueReg = ValueSReg;
10130       CmpReg = incr;
10131     }
10132     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10133         .addReg(CmpReg)
10134         .addReg(ValueReg);
10135     BuildMI(BB, dl, TII->get(PPC::BCC))
10136         .addImm(CmpPred)
10137         .addReg(PPC::CR0)
10138         .addMBB(exitMBB);
10139     BB->addSuccessor(loop2MBB);
10140     BB->addSuccessor(exitMBB);
10141     BB = loop2MBB;
10142   }
10143   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10144   BuildMI(BB, dl, TII->get(PPC::STWCX))
10145       .addReg(Tmp4Reg)
10146       .addReg(ZeroReg)
10147       .addReg(PtrReg);
10148   BuildMI(BB, dl, TII->get(PPC::BCC))
10149       .addImm(PPC::PRED_NE)
10150       .addReg(PPC::CR0)
10151       .addMBB(loopMBB);
10152   BB->addSuccessor(loopMBB);
10153   BB->addSuccessor(exitMBB);
10154 
10155   //  exitMBB:
10156   //   ...
10157   BB = exitMBB;
10158   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10159       .addReg(TmpDestReg)
10160       .addReg(ShiftReg);
10161   return BB;
10162 }
10163 
10164 llvm::MachineBasicBlock *
10165 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10166                                     MachineBasicBlock *MBB) const {
10167   DebugLoc DL = MI.getDebugLoc();
10168   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10169   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10170 
10171   MachineFunction *MF = MBB->getParent();
10172   MachineRegisterInfo &MRI = MF->getRegInfo();
10173 
10174   const BasicBlock *BB = MBB->getBasicBlock();
10175   MachineFunction::iterator I = ++MBB->getIterator();
10176 
10177   unsigned DstReg = MI.getOperand(0).getReg();
10178   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10179   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10180   unsigned mainDstReg = MRI.createVirtualRegister(RC);
10181   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
10182 
10183   MVT PVT = getPointerTy(MF->getDataLayout());
10184   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10185          "Invalid Pointer Size!");
10186   // For v = setjmp(buf), we generate
10187   //
10188   // thisMBB:
10189   //  SjLjSetup mainMBB
10190   //  bl mainMBB
10191   //  v_restore = 1
10192   //  b sinkMBB
10193   //
10194   // mainMBB:
10195   //  buf[LabelOffset] = LR
10196   //  v_main = 0
10197   //
10198   // sinkMBB:
10199   //  v = phi(main, restore)
10200   //
10201 
10202   MachineBasicBlock *thisMBB = MBB;
10203   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10204   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10205   MF->insert(I, mainMBB);
10206   MF->insert(I, sinkMBB);
10207 
10208   MachineInstrBuilder MIB;
10209 
10210   // Transfer the remainder of BB and its successor edges to sinkMBB.
10211   sinkMBB->splice(sinkMBB->begin(), MBB,
10212                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10213   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10214 
10215   // Note that the structure of the jmp_buf used here is not compatible
10216   // with that used by libc, and is not designed to be. Specifically, it
10217   // stores only those 'reserved' registers that LLVM does not otherwise
10218   // understand how to spill. Also, by convention, by the time this
10219   // intrinsic is called, Clang has already stored the frame address in the
10220   // first slot of the buffer and stack address in the third. Following the
10221   // X86 target code, we'll store the jump address in the second slot. We also
10222   // need to save the TOC pointer (R2) to handle jumps between shared
10223   // libraries, and that will be stored in the fourth slot. The thread
10224   // identifier (R13) is not affected.
10225 
10226   // thisMBB:
10227   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10228   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10229   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10230 
10231   // Prepare IP either in reg.
10232   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10233   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
10234   unsigned BufReg = MI.getOperand(1).getReg();
10235 
10236   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
10237     setUsesTOCBasePtr(*MBB->getParent());
10238     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10239               .addReg(PPC::X2)
10240               .addImm(TOCOffset)
10241               .addReg(BufReg)
10242               .cloneMemRefs(MI);
10243   }
10244 
10245   // Naked functions never have a base pointer, and so we use r1. For all
10246   // other functions, this decision must be delayed until during PEI.
10247   unsigned BaseReg;
10248   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10249     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10250   else
10251     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10252 
10253   MIB = BuildMI(*thisMBB, MI, DL,
10254                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10255             .addReg(BaseReg)
10256             .addImm(BPOffset)
10257             .addReg(BufReg)
10258             .cloneMemRefs(MI);
10259 
10260   // Setup
10261   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10262   MIB.addRegMask(TRI->getNoPreservedMask());
10263 
10264   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10265 
10266   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10267           .addMBB(mainMBB);
10268   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10269 
10270   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10271   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10272 
10273   // mainMBB:
10274   //  mainDstReg = 0
10275   MIB =
10276       BuildMI(mainMBB, DL,
10277               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10278 
10279   // Store IP
10280   if (Subtarget.isPPC64()) {
10281     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10282             .addReg(LabelReg)
10283             .addImm(LabelOffset)
10284             .addReg(BufReg);
10285   } else {
10286     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10287             .addReg(LabelReg)
10288             .addImm(LabelOffset)
10289             .addReg(BufReg);
10290   }
10291   MIB.cloneMemRefs(MI);
10292 
10293   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10294   mainMBB->addSuccessor(sinkMBB);
10295 
10296   // sinkMBB:
10297   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10298           TII->get(PPC::PHI), DstReg)
10299     .addReg(mainDstReg).addMBB(mainMBB)
10300     .addReg(restoreDstReg).addMBB(thisMBB);
10301 
10302   MI.eraseFromParent();
10303   return sinkMBB;
10304 }
10305 
10306 MachineBasicBlock *
10307 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10308                                      MachineBasicBlock *MBB) const {
10309   DebugLoc DL = MI.getDebugLoc();
10310   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10311 
10312   MachineFunction *MF = MBB->getParent();
10313   MachineRegisterInfo &MRI = MF->getRegInfo();
10314 
10315   MVT PVT = getPointerTy(MF->getDataLayout());
10316   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10317          "Invalid Pointer Size!");
10318 
10319   const TargetRegisterClass *RC =
10320     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10321   unsigned Tmp = MRI.createVirtualRegister(RC);
10322   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10323   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10324   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10325   unsigned BP =
10326       (PVT == MVT::i64)
10327           ? PPC::X30
10328           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10329                                                               : PPC::R30);
10330 
10331   MachineInstrBuilder MIB;
10332 
10333   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10334   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10335   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10336   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10337 
10338   unsigned BufReg = MI.getOperand(0).getReg();
10339 
10340   // Reload FP (the jumped-to function may not have had a
10341   // frame pointer, and if so, then its r31 will be restored
10342   // as necessary).
10343   if (PVT == MVT::i64) {
10344     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10345             .addImm(0)
10346             .addReg(BufReg);
10347   } else {
10348     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10349             .addImm(0)
10350             .addReg(BufReg);
10351   }
10352   MIB.cloneMemRefs(MI);
10353 
10354   // Reload IP
10355   if (PVT == MVT::i64) {
10356     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10357             .addImm(LabelOffset)
10358             .addReg(BufReg);
10359   } else {
10360     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10361             .addImm(LabelOffset)
10362             .addReg(BufReg);
10363   }
10364   MIB.cloneMemRefs(MI);
10365 
10366   // Reload SP
10367   if (PVT == MVT::i64) {
10368     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10369             .addImm(SPOffset)
10370             .addReg(BufReg);
10371   } else {
10372     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10373             .addImm(SPOffset)
10374             .addReg(BufReg);
10375   }
10376   MIB.cloneMemRefs(MI);
10377 
10378   // Reload BP
10379   if (PVT == MVT::i64) {
10380     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10381             .addImm(BPOffset)
10382             .addReg(BufReg);
10383   } else {
10384     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10385             .addImm(BPOffset)
10386             .addReg(BufReg);
10387   }
10388   MIB.cloneMemRefs(MI);
10389 
10390   // Reload TOC
10391   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10392     setUsesTOCBasePtr(*MBB->getParent());
10393     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10394               .addImm(TOCOffset)
10395               .addReg(BufReg)
10396               .cloneMemRefs(MI);
10397   }
10398 
10399   // Jump
10400   BuildMI(*MBB, MI, DL,
10401           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10402   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10403 
10404   MI.eraseFromParent();
10405   return MBB;
10406 }
10407 
10408 MachineBasicBlock *
10409 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10410                                                MachineBasicBlock *BB) const {
10411   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10412       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10413     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10414         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10415       // Call lowering should have added an r2 operand to indicate a dependence
10416       // on the TOC base pointer value. It can't however, because there is no
10417       // way to mark the dependence as implicit there, and so the stackmap code
10418       // will confuse it with a regular operand. Instead, add the dependence
10419       // here.
10420       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10421     }
10422 
10423     return emitPatchPoint(MI, BB);
10424   }
10425 
10426   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10427       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10428     return emitEHSjLjSetJmp(MI, BB);
10429   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10430              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10431     return emitEHSjLjLongJmp(MI, BB);
10432   }
10433 
10434   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10435 
10436   // To "insert" these instructions we actually have to insert their
10437   // control-flow patterns.
10438   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10439   MachineFunction::iterator It = ++BB->getIterator();
10440 
10441   MachineFunction *F = BB->getParent();
10442 
10443   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10444       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
10445       MI.getOpcode() == PPC::SELECT_I8) {
10446     SmallVector<MachineOperand, 2> Cond;
10447     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10448         MI.getOpcode() == PPC::SELECT_CC_I8)
10449       Cond.push_back(MI.getOperand(4));
10450     else
10451       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10452     Cond.push_back(MI.getOperand(1));
10453 
10454     DebugLoc dl = MI.getDebugLoc();
10455     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10456                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10457   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10458              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10459              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10460              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10461              MI.getOpcode() == PPC::SELECT_CC_F16 ||
10462              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10463              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10464              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10465              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10466              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10467              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10468              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10469              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10470              MI.getOpcode() == PPC::SELECT_CC_SPE ||
10471              MI.getOpcode() == PPC::SELECT_I4 ||
10472              MI.getOpcode() == PPC::SELECT_I8 ||
10473              MI.getOpcode() == PPC::SELECT_F4 ||
10474              MI.getOpcode() == PPC::SELECT_F8 ||
10475              MI.getOpcode() == PPC::SELECT_F16 ||
10476              MI.getOpcode() == PPC::SELECT_QFRC ||
10477              MI.getOpcode() == PPC::SELECT_QSRC ||
10478              MI.getOpcode() == PPC::SELECT_QBRC ||
10479              MI.getOpcode() == PPC::SELECT_SPE ||
10480              MI.getOpcode() == PPC::SELECT_SPE4 ||
10481              MI.getOpcode() == PPC::SELECT_VRRC ||
10482              MI.getOpcode() == PPC::SELECT_VSFRC ||
10483              MI.getOpcode() == PPC::SELECT_VSSRC ||
10484              MI.getOpcode() == PPC::SELECT_VSRC) {
10485     // The incoming instruction knows the destination vreg to set, the
10486     // condition code register to branch on, the true/false values to
10487     // select between, and a branch opcode to use.
10488 
10489     //  thisMBB:
10490     //  ...
10491     //   TrueVal = ...
10492     //   cmpTY ccX, r1, r2
10493     //   bCC copy1MBB
10494     //   fallthrough --> copy0MBB
10495     MachineBasicBlock *thisMBB = BB;
10496     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10497     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10498     DebugLoc dl = MI.getDebugLoc();
10499     F->insert(It, copy0MBB);
10500     F->insert(It, sinkMBB);
10501 
10502     // Transfer the remainder of BB and its successor edges to sinkMBB.
10503     sinkMBB->splice(sinkMBB->begin(), BB,
10504                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10505     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10506 
10507     // Next, add the true and fallthrough blocks as its successors.
10508     BB->addSuccessor(copy0MBB);
10509     BB->addSuccessor(sinkMBB);
10510 
10511     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10512         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10513         MI.getOpcode() == PPC::SELECT_F16 ||
10514         MI.getOpcode() == PPC::SELECT_SPE4 ||
10515         MI.getOpcode() == PPC::SELECT_SPE ||
10516         MI.getOpcode() == PPC::SELECT_QFRC ||
10517         MI.getOpcode() == PPC::SELECT_QSRC ||
10518         MI.getOpcode() == PPC::SELECT_QBRC ||
10519         MI.getOpcode() == PPC::SELECT_VRRC ||
10520         MI.getOpcode() == PPC::SELECT_VSFRC ||
10521         MI.getOpcode() == PPC::SELECT_VSSRC ||
10522         MI.getOpcode() == PPC::SELECT_VSRC) {
10523       BuildMI(BB, dl, TII->get(PPC::BC))
10524           .addReg(MI.getOperand(1).getReg())
10525           .addMBB(sinkMBB);
10526     } else {
10527       unsigned SelectPred = MI.getOperand(4).getImm();
10528       BuildMI(BB, dl, TII->get(PPC::BCC))
10529           .addImm(SelectPred)
10530           .addReg(MI.getOperand(1).getReg())
10531           .addMBB(sinkMBB);
10532     }
10533 
10534     //  copy0MBB:
10535     //   %FalseValue = ...
10536     //   # fallthrough to sinkMBB
10537     BB = copy0MBB;
10538 
10539     // Update machine-CFG edges
10540     BB->addSuccessor(sinkMBB);
10541 
10542     //  sinkMBB:
10543     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10544     //  ...
10545     BB = sinkMBB;
10546     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10547         .addReg(MI.getOperand(3).getReg())
10548         .addMBB(copy0MBB)
10549         .addReg(MI.getOperand(2).getReg())
10550         .addMBB(thisMBB);
10551   } else if (MI.getOpcode() == PPC::ReadTB) {
10552     // To read the 64-bit time-base register on a 32-bit target, we read the
10553     // two halves. Should the counter have wrapped while it was being read, we
10554     // need to try again.
10555     // ...
10556     // readLoop:
10557     // mfspr Rx,TBU # load from TBU
10558     // mfspr Ry,TB  # load from TB
10559     // mfspr Rz,TBU # load from TBU
10560     // cmpw crX,Rx,Rz # check if 'old'='new'
10561     // bne readLoop   # branch if they're not equal
10562     // ...
10563 
10564     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10565     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10566     DebugLoc dl = MI.getDebugLoc();
10567     F->insert(It, readMBB);
10568     F->insert(It, sinkMBB);
10569 
10570     // Transfer the remainder of BB and its successor edges to sinkMBB.
10571     sinkMBB->splice(sinkMBB->begin(), BB,
10572                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10573     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10574 
10575     BB->addSuccessor(readMBB);
10576     BB = readMBB;
10577 
10578     MachineRegisterInfo &RegInfo = F->getRegInfo();
10579     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10580     unsigned LoReg = MI.getOperand(0).getReg();
10581     unsigned HiReg = MI.getOperand(1).getReg();
10582 
10583     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10584     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10585     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10586 
10587     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10588 
10589     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10590         .addReg(HiReg)
10591         .addReg(ReadAgainReg);
10592     BuildMI(BB, dl, TII->get(PPC::BCC))
10593         .addImm(PPC::PRED_NE)
10594         .addReg(CmpReg)
10595         .addMBB(readMBB);
10596 
10597     BB->addSuccessor(readMBB);
10598     BB->addSuccessor(sinkMBB);
10599   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10600     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10601   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10602     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10603   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10604     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10605   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10606     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10607 
10608   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10609     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10610   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10611     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10612   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10613     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10614   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10615     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10616 
10617   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10618     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10619   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10620     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10621   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10622     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10623   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10624     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10625 
10626   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10627     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10628   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10629     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10630   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10631     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10632   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10633     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10634 
10635   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10636     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10637   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10638     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10639   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10640     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10641   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10642     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10643 
10644   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10645     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10646   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10647     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10648   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10649     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10650   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10651     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10652 
10653   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10654     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10655   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10656     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10657   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10658     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10659   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10660     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10661 
10662   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10663     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10664   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10665     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10666   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10667     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10668   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10669     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10670 
10671   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10672     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10673   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10674     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10675   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10676     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10677   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10678     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10679 
10680   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10681     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10682   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10683     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10684   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10685     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10686   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10687     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10688 
10689   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10690     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10691   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10692     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10693   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10694     BB = EmitAtomicBinary(MI, BB, 4, 0);
10695   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10696     BB = EmitAtomicBinary(MI, BB, 8, 0);
10697   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10698            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10699            (Subtarget.hasPartwordAtomics() &&
10700             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10701            (Subtarget.hasPartwordAtomics() &&
10702             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10703     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10704 
10705     auto LoadMnemonic = PPC::LDARX;
10706     auto StoreMnemonic = PPC::STDCX;
10707     switch (MI.getOpcode()) {
10708     default:
10709       llvm_unreachable("Compare and swap of unknown size");
10710     case PPC::ATOMIC_CMP_SWAP_I8:
10711       LoadMnemonic = PPC::LBARX;
10712       StoreMnemonic = PPC::STBCX;
10713       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10714       break;
10715     case PPC::ATOMIC_CMP_SWAP_I16:
10716       LoadMnemonic = PPC::LHARX;
10717       StoreMnemonic = PPC::STHCX;
10718       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10719       break;
10720     case PPC::ATOMIC_CMP_SWAP_I32:
10721       LoadMnemonic = PPC::LWARX;
10722       StoreMnemonic = PPC::STWCX;
10723       break;
10724     case PPC::ATOMIC_CMP_SWAP_I64:
10725       LoadMnemonic = PPC::LDARX;
10726       StoreMnemonic = PPC::STDCX;
10727       break;
10728     }
10729     unsigned dest = MI.getOperand(0).getReg();
10730     unsigned ptrA = MI.getOperand(1).getReg();
10731     unsigned ptrB = MI.getOperand(2).getReg();
10732     unsigned oldval = MI.getOperand(3).getReg();
10733     unsigned newval = MI.getOperand(4).getReg();
10734     DebugLoc dl = MI.getDebugLoc();
10735 
10736     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10737     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10738     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10739     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10740     F->insert(It, loop1MBB);
10741     F->insert(It, loop2MBB);
10742     F->insert(It, midMBB);
10743     F->insert(It, exitMBB);
10744     exitMBB->splice(exitMBB->begin(), BB,
10745                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10746     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10747 
10748     //  thisMBB:
10749     //   ...
10750     //   fallthrough --> loopMBB
10751     BB->addSuccessor(loop1MBB);
10752 
10753     // loop1MBB:
10754     //   l[bhwd]arx dest, ptr
10755     //   cmp[wd] dest, oldval
10756     //   bne- midMBB
10757     // loop2MBB:
10758     //   st[bhwd]cx. newval, ptr
10759     //   bne- loopMBB
10760     //   b exitBB
10761     // midMBB:
10762     //   st[bhwd]cx. dest, ptr
10763     // exitBB:
10764     BB = loop1MBB;
10765     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
10766     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10767         .addReg(oldval)
10768         .addReg(dest);
10769     BuildMI(BB, dl, TII->get(PPC::BCC))
10770         .addImm(PPC::PRED_NE)
10771         .addReg(PPC::CR0)
10772         .addMBB(midMBB);
10773     BB->addSuccessor(loop2MBB);
10774     BB->addSuccessor(midMBB);
10775 
10776     BB = loop2MBB;
10777     BuildMI(BB, dl, TII->get(StoreMnemonic))
10778         .addReg(newval)
10779         .addReg(ptrA)
10780         .addReg(ptrB);
10781     BuildMI(BB, dl, TII->get(PPC::BCC))
10782         .addImm(PPC::PRED_NE)
10783         .addReg(PPC::CR0)
10784         .addMBB(loop1MBB);
10785     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10786     BB->addSuccessor(loop1MBB);
10787     BB->addSuccessor(exitMBB);
10788 
10789     BB = midMBB;
10790     BuildMI(BB, dl, TII->get(StoreMnemonic))
10791         .addReg(dest)
10792         .addReg(ptrA)
10793         .addReg(ptrB);
10794     BB->addSuccessor(exitMBB);
10795 
10796     //  exitMBB:
10797     //   ...
10798     BB = exitMBB;
10799   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10800              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10801     // We must use 64-bit registers for addresses when targeting 64-bit,
10802     // since we're actually doing arithmetic on them.  Other registers
10803     // can be 32-bit.
10804     bool is64bit = Subtarget.isPPC64();
10805     bool isLittleEndian = Subtarget.isLittleEndian();
10806     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10807 
10808     unsigned dest = MI.getOperand(0).getReg();
10809     unsigned ptrA = MI.getOperand(1).getReg();
10810     unsigned ptrB = MI.getOperand(2).getReg();
10811     unsigned oldval = MI.getOperand(3).getReg();
10812     unsigned newval = MI.getOperand(4).getReg();
10813     DebugLoc dl = MI.getDebugLoc();
10814 
10815     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10816     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10817     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10818     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10819     F->insert(It, loop1MBB);
10820     F->insert(It, loop2MBB);
10821     F->insert(It, midMBB);
10822     F->insert(It, exitMBB);
10823     exitMBB->splice(exitMBB->begin(), BB,
10824                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10825     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10826 
10827     MachineRegisterInfo &RegInfo = F->getRegInfo();
10828     const TargetRegisterClass *RC =
10829         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10830     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10831 
10832     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10833     unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10834     unsigned ShiftReg =
10835         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10836     unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
10837     unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
10838     unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
10839     unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
10840     unsigned MaskReg = RegInfo.createVirtualRegister(GPRC);
10841     unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10842     unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10843     unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10844     unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10845     unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10846     unsigned Ptr1Reg;
10847     unsigned TmpReg = RegInfo.createVirtualRegister(GPRC);
10848     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10849     //  thisMBB:
10850     //   ...
10851     //   fallthrough --> loopMBB
10852     BB->addSuccessor(loop1MBB);
10853 
10854     // The 4-byte load must be aligned, while a char or short may be
10855     // anywhere in the word.  Hence all this nasty bookkeeping code.
10856     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10857     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10858     //   xori shift, shift1, 24 [16]
10859     //   rlwinm ptr, ptr1, 0, 0, 29
10860     //   slw newval2, newval, shift
10861     //   slw oldval2, oldval,shift
10862     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10863     //   slw mask, mask2, shift
10864     //   and newval3, newval2, mask
10865     //   and oldval3, oldval2, mask
10866     // loop1MBB:
10867     //   lwarx tmpDest, ptr
10868     //   and tmp, tmpDest, mask
10869     //   cmpw tmp, oldval3
10870     //   bne- midMBB
10871     // loop2MBB:
10872     //   andc tmp2, tmpDest, mask
10873     //   or tmp4, tmp2, newval3
10874     //   stwcx. tmp4, ptr
10875     //   bne- loop1MBB
10876     //   b exitBB
10877     // midMBB:
10878     //   stwcx. tmpDest, ptr
10879     // exitBB:
10880     //   srw dest, tmpDest, shift
10881     if (ptrA != ZeroReg) {
10882       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10883       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10884           .addReg(ptrA)
10885           .addReg(ptrB);
10886     } else {
10887       Ptr1Reg = ptrB;
10888     }
10889 
10890     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10891     // mode.
10892     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10893         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10894         .addImm(3)
10895         .addImm(27)
10896         .addImm(is8bit ? 28 : 27);
10897     if (!isLittleEndian)
10898       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10899           .addReg(Shift1Reg)
10900           .addImm(is8bit ? 24 : 16);
10901     if (is64bit)
10902       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10903           .addReg(Ptr1Reg)
10904           .addImm(0)
10905           .addImm(61);
10906     else
10907       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10908           .addReg(Ptr1Reg)
10909           .addImm(0)
10910           .addImm(0)
10911           .addImm(29);
10912     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10913         .addReg(newval)
10914         .addReg(ShiftReg);
10915     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10916         .addReg(oldval)
10917         .addReg(ShiftReg);
10918     if (is8bit)
10919       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10920     else {
10921       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10922       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10923           .addReg(Mask3Reg)
10924           .addImm(65535);
10925     }
10926     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10927         .addReg(Mask2Reg)
10928         .addReg(ShiftReg);
10929     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10930         .addReg(NewVal2Reg)
10931         .addReg(MaskReg);
10932     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10933         .addReg(OldVal2Reg)
10934         .addReg(MaskReg);
10935 
10936     BB = loop1MBB;
10937     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10938         .addReg(ZeroReg)
10939         .addReg(PtrReg);
10940     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
10941         .addReg(TmpDestReg)
10942         .addReg(MaskReg);
10943     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10944         .addReg(TmpReg)
10945         .addReg(OldVal3Reg);
10946     BuildMI(BB, dl, TII->get(PPC::BCC))
10947         .addImm(PPC::PRED_NE)
10948         .addReg(PPC::CR0)
10949         .addMBB(midMBB);
10950     BB->addSuccessor(loop2MBB);
10951     BB->addSuccessor(midMBB);
10952 
10953     BB = loop2MBB;
10954     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10955         .addReg(TmpDestReg)
10956         .addReg(MaskReg);
10957     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
10958         .addReg(Tmp2Reg)
10959         .addReg(NewVal3Reg);
10960     BuildMI(BB, dl, TII->get(PPC::STWCX))
10961         .addReg(Tmp4Reg)
10962         .addReg(ZeroReg)
10963         .addReg(PtrReg);
10964     BuildMI(BB, dl, TII->get(PPC::BCC))
10965         .addImm(PPC::PRED_NE)
10966         .addReg(PPC::CR0)
10967         .addMBB(loop1MBB);
10968     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10969     BB->addSuccessor(loop1MBB);
10970     BB->addSuccessor(exitMBB);
10971 
10972     BB = midMBB;
10973     BuildMI(BB, dl, TII->get(PPC::STWCX))
10974         .addReg(TmpDestReg)
10975         .addReg(ZeroReg)
10976         .addReg(PtrReg);
10977     BB->addSuccessor(exitMBB);
10978 
10979     //  exitMBB:
10980     //   ...
10981     BB = exitMBB;
10982     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10983         .addReg(TmpReg)
10984         .addReg(ShiftReg);
10985   } else if (MI.getOpcode() == PPC::FADDrtz) {
10986     // This pseudo performs an FADD with rounding mode temporarily forced
10987     // to round-to-zero.  We emit this via custom inserter since the FPSCR
10988     // is not modeled at the SelectionDAG level.
10989     unsigned Dest = MI.getOperand(0).getReg();
10990     unsigned Src1 = MI.getOperand(1).getReg();
10991     unsigned Src2 = MI.getOperand(2).getReg();
10992     DebugLoc dl = MI.getDebugLoc();
10993 
10994     MachineRegisterInfo &RegInfo = F->getRegInfo();
10995     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10996 
10997     // Save FPSCR value.
10998     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10999 
11000     // Set rounding mode to round-to-zero.
11001     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11002     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11003 
11004     // Perform addition.
11005     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11006 
11007     // Restore FPSCR value.
11008     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11009   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11010              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11011              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11012              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11013     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11014                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11015                           ? PPC::ANDIo8
11016                           : PPC::ANDIo;
11017     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11018                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11019 
11020     MachineRegisterInfo &RegInfo = F->getRegInfo();
11021     unsigned Dest = RegInfo.createVirtualRegister(
11022         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11023 
11024     DebugLoc dl = MI.getDebugLoc();
11025     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11026         .addReg(MI.getOperand(1).getReg())
11027         .addImm(1);
11028     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11029             MI.getOperand(0).getReg())
11030         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11031   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11032     DebugLoc Dl = MI.getDebugLoc();
11033     MachineRegisterInfo &RegInfo = F->getRegInfo();
11034     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11035     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11036     return BB;
11037   } else if (MI.getOpcode() == PPC::SETRNDi) {
11038     DebugLoc dl = MI.getDebugLoc();
11039     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11040 
11041     // Save FPSCR value.
11042     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11043 
11044     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11045     // the following settings:
11046     //   00 Round to nearest
11047     //   01 Round to 0
11048     //   10 Round to +inf
11049     //   11 Round to -inf
11050 
11051     // When the operand is immediate, using the two least significant bits of
11052     // the immediate to set the bits 62:63 of FPSCR.
11053     unsigned Mode = MI.getOperand(1).getImm();
11054     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11055       .addImm(31);
11056 
11057     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11058       .addImm(30);
11059   } else if (MI.getOpcode() == PPC::SETRND) {
11060     DebugLoc dl = MI.getDebugLoc();
11061 
11062     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11063     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11064     // If the target doesn't have DirectMove, we should use stack to do the
11065     // conversion, because the target doesn't have the instructions like mtvsrd
11066     // or mfvsrd to do this conversion directly.
11067     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11068       if (Subtarget.hasDirectMove()) {
11069         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11070           .addReg(SrcReg);
11071       } else {
11072         // Use stack to do the register copy.
11073         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11074         MachineRegisterInfo &RegInfo = F->getRegInfo();
11075         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11076         if (RC == &PPC::F8RCRegClass) {
11077           // Copy register from F8RCRegClass to G8RCRegclass.
11078           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11079                  "Unsupported RegClass.");
11080 
11081           StoreOp = PPC::STFD;
11082           LoadOp = PPC::LD;
11083         } else {
11084           // Copy register from G8RCRegClass to F8RCRegclass.
11085           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11086                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11087                  "Unsupported RegClass.");
11088         }
11089 
11090         MachineFrameInfo &MFI = F->getFrameInfo();
11091         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11092 
11093         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11094           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11095           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11096           MFI.getObjectAlignment(FrameIdx));
11097 
11098         // Store the SrcReg into the stack.
11099         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11100           .addReg(SrcReg)
11101           .addImm(0)
11102           .addFrameIndex(FrameIdx)
11103           .addMemOperand(MMOStore);
11104 
11105         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11106           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11107           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11108           MFI.getObjectAlignment(FrameIdx));
11109 
11110         // Load from the stack where SrcReg is stored, and save to DestReg,
11111         // so we have done the RegClass conversion from RegClass::SrcReg to
11112         // RegClass::DestReg.
11113         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11114           .addImm(0)
11115           .addFrameIndex(FrameIdx)
11116           .addMemOperand(MMOLoad);
11117       }
11118     };
11119 
11120     unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11121 
11122     // Save FPSCR value.
11123     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11124 
11125     // When the operand is gprc register, use two least significant bits of the
11126     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11127     //
11128     // copy OldFPSCRTmpReg, OldFPSCRReg
11129     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11130     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11131     // copy NewFPSCRReg, NewFPSCRTmpReg
11132     // mtfsf 255, NewFPSCRReg
11133     MachineOperand SrcOp = MI.getOperand(1);
11134     MachineRegisterInfo &RegInfo = F->getRegInfo();
11135     unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11136 
11137     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11138 
11139     unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11140     unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11141 
11142     // The first operand of INSERT_SUBREG should be a register which has
11143     // subregisters, we only care about its RegClass, so we should use an
11144     // IMPLICIT_DEF register.
11145     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11146     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11147       .addReg(ImDefReg)
11148       .add(SrcOp)
11149       .addImm(1);
11150 
11151     unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11152     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11153       .addReg(OldFPSCRTmpReg)
11154       .addReg(ExtSrcReg)
11155       .addImm(0)
11156       .addImm(62);
11157 
11158     unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11159     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11160 
11161     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11162     // bits of FPSCR.
11163     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11164       .addImm(255)
11165       .addReg(NewFPSCRReg)
11166       .addImm(0)
11167       .addImm(0);
11168   } else {
11169     llvm_unreachable("Unexpected instr type to insert");
11170   }
11171 
11172   MI.eraseFromParent(); // The pseudo instruction is gone now.
11173   return BB;
11174 }
11175 
11176 //===----------------------------------------------------------------------===//
11177 // Target Optimization Hooks
11178 //===----------------------------------------------------------------------===//
11179 
11180 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11181   // For the estimates, convergence is quadratic, so we essentially double the
11182   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11183   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11184   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11185   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11186   if (VT.getScalarType() == MVT::f64)
11187     RefinementSteps++;
11188   return RefinementSteps;
11189 }
11190 
11191 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11192                                            int Enabled, int &RefinementSteps,
11193                                            bool &UseOneConstNR,
11194                                            bool Reciprocal) const {
11195   EVT VT = Operand.getValueType();
11196   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11197       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11198       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11199       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11200       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11201       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11202     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11203       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11204 
11205     // The Newton-Raphson computation with a single constant does not provide
11206     // enough accuracy on some CPUs.
11207     UseOneConstNR = !Subtarget.needsTwoConstNR();
11208     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11209   }
11210   return SDValue();
11211 }
11212 
11213 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11214                                             int Enabled,
11215                                             int &RefinementSteps) const {
11216   EVT VT = Operand.getValueType();
11217   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11218       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11219       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11220       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11221       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11222       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11223     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11224       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11225     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11226   }
11227   return SDValue();
11228 }
11229 
11230 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11231   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11232   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11233   // enabled for division), this functionality is redundant with the default
11234   // combiner logic (once the division -> reciprocal/multiply transformation
11235   // has taken place). As a result, this matters more for older cores than for
11236   // newer ones.
11237 
11238   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11239   // reciprocal if there are two or more FDIVs (for embedded cores with only
11240   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11241   switch (Subtarget.getDarwinDirective()) {
11242   default:
11243     return 3;
11244   case PPC::DIR_440:
11245   case PPC::DIR_A2:
11246   case PPC::DIR_E500:
11247   case PPC::DIR_E500mc:
11248   case PPC::DIR_E5500:
11249     return 2;
11250   }
11251 }
11252 
11253 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11254 // collapsed, and so we need to look through chains of them.
11255 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11256                                      int64_t& Offset, SelectionDAG &DAG) {
11257   if (DAG.isBaseWithConstantOffset(Loc)) {
11258     Base = Loc.getOperand(0);
11259     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11260 
11261     // The base might itself be a base plus an offset, and if so, accumulate
11262     // that as well.
11263     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11264   }
11265 }
11266 
11267 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11268                             unsigned Bytes, int Dist,
11269                             SelectionDAG &DAG) {
11270   if (VT.getSizeInBits() / 8 != Bytes)
11271     return false;
11272 
11273   SDValue BaseLoc = Base->getBasePtr();
11274   if (Loc.getOpcode() == ISD::FrameIndex) {
11275     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11276       return false;
11277     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11278     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11279     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11280     int FS  = MFI.getObjectSize(FI);
11281     int BFS = MFI.getObjectSize(BFI);
11282     if (FS != BFS || FS != (int)Bytes) return false;
11283     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11284   }
11285 
11286   SDValue Base1 = Loc, Base2 = BaseLoc;
11287   int64_t Offset1 = 0, Offset2 = 0;
11288   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11289   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11290   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11291     return true;
11292 
11293   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11294   const GlobalValue *GV1 = nullptr;
11295   const GlobalValue *GV2 = nullptr;
11296   Offset1 = 0;
11297   Offset2 = 0;
11298   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11299   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11300   if (isGA1 && isGA2 && GV1 == GV2)
11301     return Offset1 == (Offset2 + Dist*Bytes);
11302   return false;
11303 }
11304 
11305 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11306 // not enforce equality of the chain operands.
11307 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11308                             unsigned Bytes, int Dist,
11309                             SelectionDAG &DAG) {
11310   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11311     EVT VT = LS->getMemoryVT();
11312     SDValue Loc = LS->getBasePtr();
11313     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11314   }
11315 
11316   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11317     EVT VT;
11318     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11319     default: return false;
11320     case Intrinsic::ppc_qpx_qvlfd:
11321     case Intrinsic::ppc_qpx_qvlfda:
11322       VT = MVT::v4f64;
11323       break;
11324     case Intrinsic::ppc_qpx_qvlfs:
11325     case Intrinsic::ppc_qpx_qvlfsa:
11326       VT = MVT::v4f32;
11327       break;
11328     case Intrinsic::ppc_qpx_qvlfcd:
11329     case Intrinsic::ppc_qpx_qvlfcda:
11330       VT = MVT::v2f64;
11331       break;
11332     case Intrinsic::ppc_qpx_qvlfcs:
11333     case Intrinsic::ppc_qpx_qvlfcsa:
11334       VT = MVT::v2f32;
11335       break;
11336     case Intrinsic::ppc_qpx_qvlfiwa:
11337     case Intrinsic::ppc_qpx_qvlfiwz:
11338     case Intrinsic::ppc_altivec_lvx:
11339     case Intrinsic::ppc_altivec_lvxl:
11340     case Intrinsic::ppc_vsx_lxvw4x:
11341     case Intrinsic::ppc_vsx_lxvw4x_be:
11342       VT = MVT::v4i32;
11343       break;
11344     case Intrinsic::ppc_vsx_lxvd2x:
11345     case Intrinsic::ppc_vsx_lxvd2x_be:
11346       VT = MVT::v2f64;
11347       break;
11348     case Intrinsic::ppc_altivec_lvebx:
11349       VT = MVT::i8;
11350       break;
11351     case Intrinsic::ppc_altivec_lvehx:
11352       VT = MVT::i16;
11353       break;
11354     case Intrinsic::ppc_altivec_lvewx:
11355       VT = MVT::i32;
11356       break;
11357     }
11358 
11359     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11360   }
11361 
11362   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11363     EVT VT;
11364     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11365     default: return false;
11366     case Intrinsic::ppc_qpx_qvstfd:
11367     case Intrinsic::ppc_qpx_qvstfda:
11368       VT = MVT::v4f64;
11369       break;
11370     case Intrinsic::ppc_qpx_qvstfs:
11371     case Intrinsic::ppc_qpx_qvstfsa:
11372       VT = MVT::v4f32;
11373       break;
11374     case Intrinsic::ppc_qpx_qvstfcd:
11375     case Intrinsic::ppc_qpx_qvstfcda:
11376       VT = MVT::v2f64;
11377       break;
11378     case Intrinsic::ppc_qpx_qvstfcs:
11379     case Intrinsic::ppc_qpx_qvstfcsa:
11380       VT = MVT::v2f32;
11381       break;
11382     case Intrinsic::ppc_qpx_qvstfiw:
11383     case Intrinsic::ppc_qpx_qvstfiwa:
11384     case Intrinsic::ppc_altivec_stvx:
11385     case Intrinsic::ppc_altivec_stvxl:
11386     case Intrinsic::ppc_vsx_stxvw4x:
11387       VT = MVT::v4i32;
11388       break;
11389     case Intrinsic::ppc_vsx_stxvd2x:
11390       VT = MVT::v2f64;
11391       break;
11392     case Intrinsic::ppc_vsx_stxvw4x_be:
11393       VT = MVT::v4i32;
11394       break;
11395     case Intrinsic::ppc_vsx_stxvd2x_be:
11396       VT = MVT::v2f64;
11397       break;
11398     case Intrinsic::ppc_altivec_stvebx:
11399       VT = MVT::i8;
11400       break;
11401     case Intrinsic::ppc_altivec_stvehx:
11402       VT = MVT::i16;
11403       break;
11404     case Intrinsic::ppc_altivec_stvewx:
11405       VT = MVT::i32;
11406       break;
11407     }
11408 
11409     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11410   }
11411 
11412   return false;
11413 }
11414 
11415 // Return true is there is a nearyby consecutive load to the one provided
11416 // (regardless of alignment). We search up and down the chain, looking though
11417 // token factors and other loads (but nothing else). As a result, a true result
11418 // indicates that it is safe to create a new consecutive load adjacent to the
11419 // load provided.
11420 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11421   SDValue Chain = LD->getChain();
11422   EVT VT = LD->getMemoryVT();
11423 
11424   SmallSet<SDNode *, 16> LoadRoots;
11425   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11426   SmallSet<SDNode *, 16> Visited;
11427 
11428   // First, search up the chain, branching to follow all token-factor operands.
11429   // If we find a consecutive load, then we're done, otherwise, record all
11430   // nodes just above the top-level loads and token factors.
11431   while (!Queue.empty()) {
11432     SDNode *ChainNext = Queue.pop_back_val();
11433     if (!Visited.insert(ChainNext).second)
11434       continue;
11435 
11436     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11437       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11438         return true;
11439 
11440       if (!Visited.count(ChainLD->getChain().getNode()))
11441         Queue.push_back(ChainLD->getChain().getNode());
11442     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11443       for (const SDUse &O : ChainNext->ops())
11444         if (!Visited.count(O.getNode()))
11445           Queue.push_back(O.getNode());
11446     } else
11447       LoadRoots.insert(ChainNext);
11448   }
11449 
11450   // Second, search down the chain, starting from the top-level nodes recorded
11451   // in the first phase. These top-level nodes are the nodes just above all
11452   // loads and token factors. Starting with their uses, recursively look though
11453   // all loads (just the chain uses) and token factors to find a consecutive
11454   // load.
11455   Visited.clear();
11456   Queue.clear();
11457 
11458   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11459        IE = LoadRoots.end(); I != IE; ++I) {
11460     Queue.push_back(*I);
11461 
11462     while (!Queue.empty()) {
11463       SDNode *LoadRoot = Queue.pop_back_val();
11464       if (!Visited.insert(LoadRoot).second)
11465         continue;
11466 
11467       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11468         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11469           return true;
11470 
11471       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11472            UE = LoadRoot->use_end(); UI != UE; ++UI)
11473         if (((isa<MemSDNode>(*UI) &&
11474             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11475             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11476           Queue.push_back(*UI);
11477     }
11478   }
11479 
11480   return false;
11481 }
11482 
11483 /// This function is called when we have proved that a SETCC node can be replaced
11484 /// by subtraction (and other supporting instructions) so that the result of
11485 /// comparison is kept in a GPR instead of CR. This function is purely for
11486 /// codegen purposes and has some flags to guide the codegen process.
11487 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11488                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11489   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11490 
11491   // Zero extend the operands to the largest legal integer. Originally, they
11492   // must be of a strictly smaller size.
11493   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11494                          DAG.getConstant(Size, DL, MVT::i32));
11495   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11496                          DAG.getConstant(Size, DL, MVT::i32));
11497 
11498   // Swap if needed. Depends on the condition code.
11499   if (Swap)
11500     std::swap(Op0, Op1);
11501 
11502   // Subtract extended integers.
11503   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11504 
11505   // Move the sign bit to the least significant position and zero out the rest.
11506   // Now the least significant bit carries the result of original comparison.
11507   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11508                              DAG.getConstant(Size - 1, DL, MVT::i32));
11509   auto Final = Shifted;
11510 
11511   // Complement the result if needed. Based on the condition code.
11512   if (Complement)
11513     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11514                         DAG.getConstant(1, DL, MVT::i64));
11515 
11516   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11517 }
11518 
11519 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11520                                                   DAGCombinerInfo &DCI) const {
11521   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11522 
11523   SelectionDAG &DAG = DCI.DAG;
11524   SDLoc DL(N);
11525 
11526   // Size of integers being compared has a critical role in the following
11527   // analysis, so we prefer to do this when all types are legal.
11528   if (!DCI.isAfterLegalizeDAG())
11529     return SDValue();
11530 
11531   // If all users of SETCC extend its value to a legal integer type
11532   // then we replace SETCC with a subtraction
11533   for (SDNode::use_iterator UI = N->use_begin(),
11534        UE = N->use_end(); UI != UE; ++UI) {
11535     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11536       return SDValue();
11537   }
11538 
11539   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11540   auto OpSize = N->getOperand(0).getValueSizeInBits();
11541 
11542   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11543 
11544   if (OpSize < Size) {
11545     switch (CC) {
11546     default: break;
11547     case ISD::SETULT:
11548       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11549     case ISD::SETULE:
11550       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11551     case ISD::SETUGT:
11552       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11553     case ISD::SETUGE:
11554       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11555     }
11556   }
11557 
11558   return SDValue();
11559 }
11560 
11561 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11562                                                   DAGCombinerInfo &DCI) const {
11563   SelectionDAG &DAG = DCI.DAG;
11564   SDLoc dl(N);
11565 
11566   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11567   // If we're tracking CR bits, we need to be careful that we don't have:
11568   //   trunc(binary-ops(zext(x), zext(y)))
11569   // or
11570   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11571   // such that we're unnecessarily moving things into GPRs when it would be
11572   // better to keep them in CR bits.
11573 
11574   // Note that trunc here can be an actual i1 trunc, or can be the effective
11575   // truncation that comes from a setcc or select_cc.
11576   if (N->getOpcode() == ISD::TRUNCATE &&
11577       N->getValueType(0) != MVT::i1)
11578     return SDValue();
11579 
11580   if (N->getOperand(0).getValueType() != MVT::i32 &&
11581       N->getOperand(0).getValueType() != MVT::i64)
11582     return SDValue();
11583 
11584   if (N->getOpcode() == ISD::SETCC ||
11585       N->getOpcode() == ISD::SELECT_CC) {
11586     // If we're looking at a comparison, then we need to make sure that the
11587     // high bits (all except for the first) don't matter the result.
11588     ISD::CondCode CC =
11589       cast<CondCodeSDNode>(N->getOperand(
11590         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11591     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11592 
11593     if (ISD::isSignedIntSetCC(CC)) {
11594       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11595           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11596         return SDValue();
11597     } else if (ISD::isUnsignedIntSetCC(CC)) {
11598       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11599                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11600           !DAG.MaskedValueIsZero(N->getOperand(1),
11601                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11602         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11603                                              : SDValue());
11604     } else {
11605       // This is neither a signed nor an unsigned comparison, just make sure
11606       // that the high bits are equal.
11607       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
11608       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
11609 
11610       // We don't really care about what is known about the first bit (if
11611       // anything), so clear it in all masks prior to comparing them.
11612       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11613       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11614 
11615       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11616         return SDValue();
11617     }
11618   }
11619 
11620   // We now know that the higher-order bits are irrelevant, we just need to
11621   // make sure that all of the intermediate operations are bit operations, and
11622   // all inputs are extensions.
11623   if (N->getOperand(0).getOpcode() != ISD::AND &&
11624       N->getOperand(0).getOpcode() != ISD::OR  &&
11625       N->getOperand(0).getOpcode() != ISD::XOR &&
11626       N->getOperand(0).getOpcode() != ISD::SELECT &&
11627       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11628       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11629       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11630       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11631       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11632     return SDValue();
11633 
11634   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11635       N->getOperand(1).getOpcode() != ISD::AND &&
11636       N->getOperand(1).getOpcode() != ISD::OR  &&
11637       N->getOperand(1).getOpcode() != ISD::XOR &&
11638       N->getOperand(1).getOpcode() != ISD::SELECT &&
11639       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11640       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11641       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11642       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11643       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11644     return SDValue();
11645 
11646   SmallVector<SDValue, 4> Inputs;
11647   SmallVector<SDValue, 8> BinOps, PromOps;
11648   SmallPtrSet<SDNode *, 16> Visited;
11649 
11650   for (unsigned i = 0; i < 2; ++i) {
11651     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11652           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11653           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11654           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11655         isa<ConstantSDNode>(N->getOperand(i)))
11656       Inputs.push_back(N->getOperand(i));
11657     else
11658       BinOps.push_back(N->getOperand(i));
11659 
11660     if (N->getOpcode() == ISD::TRUNCATE)
11661       break;
11662   }
11663 
11664   // Visit all inputs, collect all binary operations (and, or, xor and
11665   // select) that are all fed by extensions.
11666   while (!BinOps.empty()) {
11667     SDValue BinOp = BinOps.back();
11668     BinOps.pop_back();
11669 
11670     if (!Visited.insert(BinOp.getNode()).second)
11671       continue;
11672 
11673     PromOps.push_back(BinOp);
11674 
11675     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11676       // The condition of the select is not promoted.
11677       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11678         continue;
11679       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11680         continue;
11681 
11682       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11683             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11684             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11685            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11686           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11687         Inputs.push_back(BinOp.getOperand(i));
11688       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11689                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11690                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11691                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11692                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11693                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11694                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11695                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11696                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11697         BinOps.push_back(BinOp.getOperand(i));
11698       } else {
11699         // We have an input that is not an extension or another binary
11700         // operation; we'll abort this transformation.
11701         return SDValue();
11702       }
11703     }
11704   }
11705 
11706   // Make sure that this is a self-contained cluster of operations (which
11707   // is not quite the same thing as saying that everything has only one
11708   // use).
11709   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11710     if (isa<ConstantSDNode>(Inputs[i]))
11711       continue;
11712 
11713     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11714                               UE = Inputs[i].getNode()->use_end();
11715          UI != UE; ++UI) {
11716       SDNode *User = *UI;
11717       if (User != N && !Visited.count(User))
11718         return SDValue();
11719 
11720       // Make sure that we're not going to promote the non-output-value
11721       // operand(s) or SELECT or SELECT_CC.
11722       // FIXME: Although we could sometimes handle this, and it does occur in
11723       // practice that one of the condition inputs to the select is also one of
11724       // the outputs, we currently can't deal with this.
11725       if (User->getOpcode() == ISD::SELECT) {
11726         if (User->getOperand(0) == Inputs[i])
11727           return SDValue();
11728       } else if (User->getOpcode() == ISD::SELECT_CC) {
11729         if (User->getOperand(0) == Inputs[i] ||
11730             User->getOperand(1) == Inputs[i])
11731           return SDValue();
11732       }
11733     }
11734   }
11735 
11736   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11737     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11738                               UE = PromOps[i].getNode()->use_end();
11739          UI != UE; ++UI) {
11740       SDNode *User = *UI;
11741       if (User != N && !Visited.count(User))
11742         return SDValue();
11743 
11744       // Make sure that we're not going to promote the non-output-value
11745       // operand(s) or SELECT or SELECT_CC.
11746       // FIXME: Although we could sometimes handle this, and it does occur in
11747       // practice that one of the condition inputs to the select is also one of
11748       // the outputs, we currently can't deal with this.
11749       if (User->getOpcode() == ISD::SELECT) {
11750         if (User->getOperand(0) == PromOps[i])
11751           return SDValue();
11752       } else if (User->getOpcode() == ISD::SELECT_CC) {
11753         if (User->getOperand(0) == PromOps[i] ||
11754             User->getOperand(1) == PromOps[i])
11755           return SDValue();
11756       }
11757     }
11758   }
11759 
11760   // Replace all inputs with the extension operand.
11761   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11762     // Constants may have users outside the cluster of to-be-promoted nodes,
11763     // and so we need to replace those as we do the promotions.
11764     if (isa<ConstantSDNode>(Inputs[i]))
11765       continue;
11766     else
11767       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11768   }
11769 
11770   std::list<HandleSDNode> PromOpHandles;
11771   for (auto &PromOp : PromOps)
11772     PromOpHandles.emplace_back(PromOp);
11773 
11774   // Replace all operations (these are all the same, but have a different
11775   // (i1) return type). DAG.getNode will validate that the types of
11776   // a binary operator match, so go through the list in reverse so that
11777   // we've likely promoted both operands first. Any intermediate truncations or
11778   // extensions disappear.
11779   while (!PromOpHandles.empty()) {
11780     SDValue PromOp = PromOpHandles.back().getValue();
11781     PromOpHandles.pop_back();
11782 
11783     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11784         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11785         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11786         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11787       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11788           PromOp.getOperand(0).getValueType() != MVT::i1) {
11789         // The operand is not yet ready (see comment below).
11790         PromOpHandles.emplace_front(PromOp);
11791         continue;
11792       }
11793 
11794       SDValue RepValue = PromOp.getOperand(0);
11795       if (isa<ConstantSDNode>(RepValue))
11796         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11797 
11798       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11799       continue;
11800     }
11801 
11802     unsigned C;
11803     switch (PromOp.getOpcode()) {
11804     default:             C = 0; break;
11805     case ISD::SELECT:    C = 1; break;
11806     case ISD::SELECT_CC: C = 2; break;
11807     }
11808 
11809     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11810          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11811         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11812          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11813       // The to-be-promoted operands of this node have not yet been
11814       // promoted (this should be rare because we're going through the
11815       // list backward, but if one of the operands has several users in
11816       // this cluster of to-be-promoted nodes, it is possible).
11817       PromOpHandles.emplace_front(PromOp);
11818       continue;
11819     }
11820 
11821     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11822                                 PromOp.getNode()->op_end());
11823 
11824     // If there are any constant inputs, make sure they're replaced now.
11825     for (unsigned i = 0; i < 2; ++i)
11826       if (isa<ConstantSDNode>(Ops[C+i]))
11827         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11828 
11829     DAG.ReplaceAllUsesOfValueWith(PromOp,
11830       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11831   }
11832 
11833   // Now we're left with the initial truncation itself.
11834   if (N->getOpcode() == ISD::TRUNCATE)
11835     return N->getOperand(0);
11836 
11837   // Otherwise, this is a comparison. The operands to be compared have just
11838   // changed type (to i1), but everything else is the same.
11839   return SDValue(N, 0);
11840 }
11841 
11842 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11843                                                   DAGCombinerInfo &DCI) const {
11844   SelectionDAG &DAG = DCI.DAG;
11845   SDLoc dl(N);
11846 
11847   // If we're tracking CR bits, we need to be careful that we don't have:
11848   //   zext(binary-ops(trunc(x), trunc(y)))
11849   // or
11850   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11851   // such that we're unnecessarily moving things into CR bits that can more
11852   // efficiently stay in GPRs. Note that if we're not certain that the high
11853   // bits are set as required by the final extension, we still may need to do
11854   // some masking to get the proper behavior.
11855 
11856   // This same functionality is important on PPC64 when dealing with
11857   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11858   // the return values of functions. Because it is so similar, it is handled
11859   // here as well.
11860 
11861   if (N->getValueType(0) != MVT::i32 &&
11862       N->getValueType(0) != MVT::i64)
11863     return SDValue();
11864 
11865   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11866         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11867     return SDValue();
11868 
11869   if (N->getOperand(0).getOpcode() != ISD::AND &&
11870       N->getOperand(0).getOpcode() != ISD::OR  &&
11871       N->getOperand(0).getOpcode() != ISD::XOR &&
11872       N->getOperand(0).getOpcode() != ISD::SELECT &&
11873       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11874     return SDValue();
11875 
11876   SmallVector<SDValue, 4> Inputs;
11877   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11878   SmallPtrSet<SDNode *, 16> Visited;
11879 
11880   // Visit all inputs, collect all binary operations (and, or, xor and
11881   // select) that are all fed by truncations.
11882   while (!BinOps.empty()) {
11883     SDValue BinOp = BinOps.back();
11884     BinOps.pop_back();
11885 
11886     if (!Visited.insert(BinOp.getNode()).second)
11887       continue;
11888 
11889     PromOps.push_back(BinOp);
11890 
11891     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11892       // The condition of the select is not promoted.
11893       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11894         continue;
11895       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11896         continue;
11897 
11898       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11899           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11900         Inputs.push_back(BinOp.getOperand(i));
11901       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11902                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11903                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11904                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11905                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11906         BinOps.push_back(BinOp.getOperand(i));
11907       } else {
11908         // We have an input that is not a truncation or another binary
11909         // operation; we'll abort this transformation.
11910         return SDValue();
11911       }
11912     }
11913   }
11914 
11915   // The operands of a select that must be truncated when the select is
11916   // promoted because the operand is actually part of the to-be-promoted set.
11917   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11918 
11919   // Make sure that this is a self-contained cluster of operations (which
11920   // is not quite the same thing as saying that everything has only one
11921   // use).
11922   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11923     if (isa<ConstantSDNode>(Inputs[i]))
11924       continue;
11925 
11926     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11927                               UE = Inputs[i].getNode()->use_end();
11928          UI != UE; ++UI) {
11929       SDNode *User = *UI;
11930       if (User != N && !Visited.count(User))
11931         return SDValue();
11932 
11933       // If we're going to promote the non-output-value operand(s) or SELECT or
11934       // SELECT_CC, record them for truncation.
11935       if (User->getOpcode() == ISD::SELECT) {
11936         if (User->getOperand(0) == Inputs[i])
11937           SelectTruncOp[0].insert(std::make_pair(User,
11938                                     User->getOperand(0).getValueType()));
11939       } else if (User->getOpcode() == ISD::SELECT_CC) {
11940         if (User->getOperand(0) == Inputs[i])
11941           SelectTruncOp[0].insert(std::make_pair(User,
11942                                     User->getOperand(0).getValueType()));
11943         if (User->getOperand(1) == Inputs[i])
11944           SelectTruncOp[1].insert(std::make_pair(User,
11945                                     User->getOperand(1).getValueType()));
11946       }
11947     }
11948   }
11949 
11950   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11951     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11952                               UE = PromOps[i].getNode()->use_end();
11953          UI != UE; ++UI) {
11954       SDNode *User = *UI;
11955       if (User != N && !Visited.count(User))
11956         return SDValue();
11957 
11958       // If we're going to promote the non-output-value operand(s) or SELECT or
11959       // SELECT_CC, record them for truncation.
11960       if (User->getOpcode() == ISD::SELECT) {
11961         if (User->getOperand(0) == PromOps[i])
11962           SelectTruncOp[0].insert(std::make_pair(User,
11963                                     User->getOperand(0).getValueType()));
11964       } else if (User->getOpcode() == ISD::SELECT_CC) {
11965         if (User->getOperand(0) == PromOps[i])
11966           SelectTruncOp[0].insert(std::make_pair(User,
11967                                     User->getOperand(0).getValueType()));
11968         if (User->getOperand(1) == PromOps[i])
11969           SelectTruncOp[1].insert(std::make_pair(User,
11970                                     User->getOperand(1).getValueType()));
11971       }
11972     }
11973   }
11974 
11975   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11976   bool ReallyNeedsExt = false;
11977   if (N->getOpcode() != ISD::ANY_EXTEND) {
11978     // If all of the inputs are not already sign/zero extended, then
11979     // we'll still need to do that at the end.
11980     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11981       if (isa<ConstantSDNode>(Inputs[i]))
11982         continue;
11983 
11984       unsigned OpBits =
11985         Inputs[i].getOperand(0).getValueSizeInBits();
11986       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11987 
11988       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11989            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11990                                   APInt::getHighBitsSet(OpBits,
11991                                                         OpBits-PromBits))) ||
11992           (N->getOpcode() == ISD::SIGN_EXTEND &&
11993            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11994              (OpBits-(PromBits-1)))) {
11995         ReallyNeedsExt = true;
11996         break;
11997       }
11998     }
11999   }
12000 
12001   // Replace all inputs, either with the truncation operand, or a
12002   // truncation or extension to the final output type.
12003   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12004     // Constant inputs need to be replaced with the to-be-promoted nodes that
12005     // use them because they might have users outside of the cluster of
12006     // promoted nodes.
12007     if (isa<ConstantSDNode>(Inputs[i]))
12008       continue;
12009 
12010     SDValue InSrc = Inputs[i].getOperand(0);
12011     if (Inputs[i].getValueType() == N->getValueType(0))
12012       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12013     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12014       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12015         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12016     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12017       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12018         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12019     else
12020       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12021         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12022   }
12023 
12024   std::list<HandleSDNode> PromOpHandles;
12025   for (auto &PromOp : PromOps)
12026     PromOpHandles.emplace_back(PromOp);
12027 
12028   // Replace all operations (these are all the same, but have a different
12029   // (promoted) return type). DAG.getNode will validate that the types of
12030   // a binary operator match, so go through the list in reverse so that
12031   // we've likely promoted both operands first.
12032   while (!PromOpHandles.empty()) {
12033     SDValue PromOp = PromOpHandles.back().getValue();
12034     PromOpHandles.pop_back();
12035 
12036     unsigned C;
12037     switch (PromOp.getOpcode()) {
12038     default:             C = 0; break;
12039     case ISD::SELECT:    C = 1; break;
12040     case ISD::SELECT_CC: C = 2; break;
12041     }
12042 
12043     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12044          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12045         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12046          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12047       // The to-be-promoted operands of this node have not yet been
12048       // promoted (this should be rare because we're going through the
12049       // list backward, but if one of the operands has several users in
12050       // this cluster of to-be-promoted nodes, it is possible).
12051       PromOpHandles.emplace_front(PromOp);
12052       continue;
12053     }
12054 
12055     // For SELECT and SELECT_CC nodes, we do a similar check for any
12056     // to-be-promoted comparison inputs.
12057     if (PromOp.getOpcode() == ISD::SELECT ||
12058         PromOp.getOpcode() == ISD::SELECT_CC) {
12059       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12060            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12061           (SelectTruncOp[1].count(PromOp.getNode()) &&
12062            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12063         PromOpHandles.emplace_front(PromOp);
12064         continue;
12065       }
12066     }
12067 
12068     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12069                                 PromOp.getNode()->op_end());
12070 
12071     // If this node has constant inputs, then they'll need to be promoted here.
12072     for (unsigned i = 0; i < 2; ++i) {
12073       if (!isa<ConstantSDNode>(Ops[C+i]))
12074         continue;
12075       if (Ops[C+i].getValueType() == N->getValueType(0))
12076         continue;
12077 
12078       if (N->getOpcode() == ISD::SIGN_EXTEND)
12079         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12080       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12081         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12082       else
12083         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12084     }
12085 
12086     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12087     // truncate them again to the original value type.
12088     if (PromOp.getOpcode() == ISD::SELECT ||
12089         PromOp.getOpcode() == ISD::SELECT_CC) {
12090       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12091       if (SI0 != SelectTruncOp[0].end())
12092         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12093       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12094       if (SI1 != SelectTruncOp[1].end())
12095         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12096     }
12097 
12098     DAG.ReplaceAllUsesOfValueWith(PromOp,
12099       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12100   }
12101 
12102   // Now we're left with the initial extension itself.
12103   if (!ReallyNeedsExt)
12104     return N->getOperand(0);
12105 
12106   // To zero extend, just mask off everything except for the first bit (in the
12107   // i1 case).
12108   if (N->getOpcode() == ISD::ZERO_EXTEND)
12109     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12110                        DAG.getConstant(APInt::getLowBitsSet(
12111                                          N->getValueSizeInBits(0), PromBits),
12112                                        dl, N->getValueType(0)));
12113 
12114   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12115          "Invalid extension type");
12116   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12117   SDValue ShiftCst =
12118       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12119   return DAG.getNode(
12120       ISD::SRA, dl, N->getValueType(0),
12121       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12122       ShiftCst);
12123 }
12124 
12125 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12126                                         DAGCombinerInfo &DCI) const {
12127   assert(N->getOpcode() == ISD::SETCC &&
12128          "Should be called with a SETCC node");
12129 
12130   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12131   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12132     SDValue LHS = N->getOperand(0);
12133     SDValue RHS = N->getOperand(1);
12134 
12135     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12136     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12137         LHS.hasOneUse())
12138       std::swap(LHS, RHS);
12139 
12140     // x == 0-y --> x+y == 0
12141     // x != 0-y --> x+y != 0
12142     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12143         RHS.hasOneUse()) {
12144       SDLoc DL(N);
12145       SelectionDAG &DAG = DCI.DAG;
12146       EVT VT = N->getValueType(0);
12147       EVT OpVT = LHS.getValueType();
12148       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12149       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12150     }
12151   }
12152 
12153   return DAGCombineTruncBoolExt(N, DCI);
12154 }
12155 
12156 // Is this an extending load from an f32 to an f64?
12157 static bool isFPExtLoad(SDValue Op) {
12158   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12159     return LD->getExtensionType() == ISD::EXTLOAD &&
12160       Op.getValueType() == MVT::f64;
12161   return false;
12162 }
12163 
12164 /// Reduces the number of fp-to-int conversion when building a vector.
12165 ///
12166 /// If this vector is built out of floating to integer conversions,
12167 /// transform it to a vector built out of floating point values followed by a
12168 /// single floating to integer conversion of the vector.
12169 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12170 /// becomes (fptosi (build_vector ($A, $B, ...)))
12171 SDValue PPCTargetLowering::
12172 combineElementTruncationToVectorTruncation(SDNode *N,
12173                                            DAGCombinerInfo &DCI) const {
12174   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12175          "Should be called with a BUILD_VECTOR node");
12176 
12177   SelectionDAG &DAG = DCI.DAG;
12178   SDLoc dl(N);
12179 
12180   SDValue FirstInput = N->getOperand(0);
12181   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12182          "The input operand must be an fp-to-int conversion.");
12183 
12184   // This combine happens after legalization so the fp_to_[su]i nodes are
12185   // already converted to PPCSISD nodes.
12186   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12187   if (FirstConversion == PPCISD::FCTIDZ ||
12188       FirstConversion == PPCISD::FCTIDUZ ||
12189       FirstConversion == PPCISD::FCTIWZ ||
12190       FirstConversion == PPCISD::FCTIWUZ) {
12191     bool IsSplat = true;
12192     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12193       FirstConversion == PPCISD::FCTIWUZ;
12194     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12195     SmallVector<SDValue, 4> Ops;
12196     EVT TargetVT = N->getValueType(0);
12197     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12198       SDValue NextOp = N->getOperand(i);
12199       if (NextOp.getOpcode() != PPCISD::MFVSR)
12200         return SDValue();
12201       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12202       if (NextConversion != FirstConversion)
12203         return SDValue();
12204       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12205       // This is not valid if the input was originally double precision. It is
12206       // also not profitable to do unless this is an extending load in which
12207       // case doing this combine will allow us to combine consecutive loads.
12208       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12209         return SDValue();
12210       if (N->getOperand(i) != FirstInput)
12211         IsSplat = false;
12212     }
12213 
12214     // If this is a splat, we leave it as-is since there will be only a single
12215     // fp-to-int conversion followed by a splat of the integer. This is better
12216     // for 32-bit and smaller ints and neutral for 64-bit ints.
12217     if (IsSplat)
12218       return SDValue();
12219 
12220     // Now that we know we have the right type of node, get its operands
12221     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12222       SDValue In = N->getOperand(i).getOperand(0);
12223       if (Is32Bit) {
12224         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12225         // here, we know that all inputs are extending loads so this is safe).
12226         if (In.isUndef())
12227           Ops.push_back(DAG.getUNDEF(SrcVT));
12228         else {
12229           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12230                                       MVT::f32, In.getOperand(0),
12231                                       DAG.getIntPtrConstant(1, dl));
12232           Ops.push_back(Trunc);
12233         }
12234       } else
12235         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12236     }
12237 
12238     unsigned Opcode;
12239     if (FirstConversion == PPCISD::FCTIDZ ||
12240         FirstConversion == PPCISD::FCTIWZ)
12241       Opcode = ISD::FP_TO_SINT;
12242     else
12243       Opcode = ISD::FP_TO_UINT;
12244 
12245     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12246     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12247     return DAG.getNode(Opcode, dl, TargetVT, BV);
12248   }
12249   return SDValue();
12250 }
12251 
12252 /// Reduce the number of loads when building a vector.
12253 ///
12254 /// Building a vector out of multiple loads can be converted to a load
12255 /// of the vector type if the loads are consecutive. If the loads are
12256 /// consecutive but in descending order, a shuffle is added at the end
12257 /// to reorder the vector.
12258 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12259   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12260          "Should be called with a BUILD_VECTOR node");
12261 
12262   SDLoc dl(N);
12263 
12264   // Return early for non byte-sized type, as they can't be consecutive.
12265   if (!N->getValueType(0).getVectorElementType().isByteSized())
12266     return SDValue();
12267 
12268   bool InputsAreConsecutiveLoads = true;
12269   bool InputsAreReverseConsecutive = true;
12270   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12271   SDValue FirstInput = N->getOperand(0);
12272   bool IsRoundOfExtLoad = false;
12273 
12274   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12275       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12276     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12277     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12278   }
12279   // Not a build vector of (possibly fp_rounded) loads.
12280   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12281       N->getNumOperands() == 1)
12282     return SDValue();
12283 
12284   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12285     // If any inputs are fp_round(extload), they all must be.
12286     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12287       return SDValue();
12288 
12289     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12290       N->getOperand(i);
12291     if (NextInput.getOpcode() != ISD::LOAD)
12292       return SDValue();
12293 
12294     SDValue PreviousInput =
12295       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12296     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12297     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12298 
12299     // If any inputs are fp_round(extload), they all must be.
12300     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12301       return SDValue();
12302 
12303     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12304       InputsAreConsecutiveLoads = false;
12305     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12306       InputsAreReverseConsecutive = false;
12307 
12308     // Exit early if the loads are neither consecutive nor reverse consecutive.
12309     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12310       return SDValue();
12311   }
12312 
12313   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12314          "The loads cannot be both consecutive and reverse consecutive.");
12315 
12316   SDValue FirstLoadOp =
12317     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12318   SDValue LastLoadOp =
12319     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12320                        N->getOperand(N->getNumOperands()-1);
12321 
12322   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12323   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12324   if (InputsAreConsecutiveLoads) {
12325     assert(LD1 && "Input needs to be a LoadSDNode.");
12326     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12327                        LD1->getBasePtr(), LD1->getPointerInfo(),
12328                        LD1->getAlignment());
12329   }
12330   if (InputsAreReverseConsecutive) {
12331     assert(LDL && "Input needs to be a LoadSDNode.");
12332     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12333                                LDL->getBasePtr(), LDL->getPointerInfo(),
12334                                LDL->getAlignment());
12335     SmallVector<int, 16> Ops;
12336     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12337       Ops.push_back(i);
12338 
12339     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12340                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12341   }
12342   return SDValue();
12343 }
12344 
12345 // This function adds the required vector_shuffle needed to get
12346 // the elements of the vector extract in the correct position
12347 // as specified by the CorrectElems encoding.
12348 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12349                                       SDValue Input, uint64_t Elems,
12350                                       uint64_t CorrectElems) {
12351   SDLoc dl(N);
12352 
12353   unsigned NumElems = Input.getValueType().getVectorNumElements();
12354   SmallVector<int, 16> ShuffleMask(NumElems, -1);
12355 
12356   // Knowing the element indices being extracted from the original
12357   // vector and the order in which they're being inserted, just put
12358   // them at element indices required for the instruction.
12359   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12360     if (DAG.getDataLayout().isLittleEndian())
12361       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12362     else
12363       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12364     CorrectElems = CorrectElems >> 8;
12365     Elems = Elems >> 8;
12366   }
12367 
12368   SDValue Shuffle =
12369       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12370                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12371 
12372   EVT Ty = N->getValueType(0);
12373   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12374   return BV;
12375 }
12376 
12377 // Look for build vector patterns where input operands come from sign
12378 // extended vector_extract elements of specific indices. If the correct indices
12379 // aren't used, add a vector shuffle to fix up the indices and create a new
12380 // PPCISD:SExtVElems node which selects the vector sign extend instructions
12381 // during instruction selection.
12382 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
12383   // This array encodes the indices that the vector sign extend instructions
12384   // extract from when extending from one type to another for both BE and LE.
12385   // The right nibble of each byte corresponds to the LE incides.
12386   // and the left nibble of each byte corresponds to the BE incides.
12387   // For example: 0x3074B8FC  byte->word
12388   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
12389   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
12390   // For example: 0x000070F8  byte->double word
12391   // For LE: the allowed indices are: 0x0,0x8
12392   // For BE: the allowed indices are: 0x7,0xF
12393   uint64_t TargetElems[] = {
12394       0x3074B8FC, // b->w
12395       0x000070F8, // b->d
12396       0x10325476, // h->w
12397       0x00003074, // h->d
12398       0x00001032, // w->d
12399   };
12400 
12401   uint64_t Elems = 0;
12402   int Index;
12403   SDValue Input;
12404 
12405   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
12406     if (!Op)
12407       return false;
12408     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
12409         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
12410       return false;
12411 
12412     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
12413     // of the right width.
12414     SDValue Extract = Op.getOperand(0);
12415     if (Extract.getOpcode() == ISD::ANY_EXTEND)
12416       Extract = Extract.getOperand(0);
12417     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12418       return false;
12419 
12420     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12421     if (!ExtOp)
12422       return false;
12423 
12424     Index = ExtOp->getZExtValue();
12425     if (Input && Input != Extract.getOperand(0))
12426       return false;
12427 
12428     if (!Input)
12429       Input = Extract.getOperand(0);
12430 
12431     Elems = Elems << 8;
12432     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12433     Elems |= Index;
12434 
12435     return true;
12436   };
12437 
12438   // If the build vector operands aren't sign extended vector extracts,
12439   // of the same input vector, then return.
12440   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12441     if (!isSExtOfVecExtract(N->getOperand(i))) {
12442       return SDValue();
12443     }
12444   }
12445 
12446   // If the vector extract indicies are not correct, add the appropriate
12447   // vector_shuffle.
12448   int TgtElemArrayIdx;
12449   int InputSize = Input.getValueType().getScalarSizeInBits();
12450   int OutputSize = N->getValueType(0).getScalarSizeInBits();
12451   if (InputSize + OutputSize == 40)
12452     TgtElemArrayIdx = 0;
12453   else if (InputSize + OutputSize == 72)
12454     TgtElemArrayIdx = 1;
12455   else if (InputSize + OutputSize == 48)
12456     TgtElemArrayIdx = 2;
12457   else if (InputSize + OutputSize == 80)
12458     TgtElemArrayIdx = 3;
12459   else if (InputSize + OutputSize == 96)
12460     TgtElemArrayIdx = 4;
12461   else
12462     return SDValue();
12463 
12464   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12465   CorrectElems = DAG.getDataLayout().isLittleEndian()
12466                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12467                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12468   if (Elems != CorrectElems) {
12469     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12470   }
12471 
12472   // Regular lowering will catch cases where a shuffle is not needed.
12473   return SDValue();
12474 }
12475 
12476 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12477                                                  DAGCombinerInfo &DCI) const {
12478   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12479          "Should be called with a BUILD_VECTOR node");
12480 
12481   SelectionDAG &DAG = DCI.DAG;
12482   SDLoc dl(N);
12483 
12484   if (!Subtarget.hasVSX())
12485     return SDValue();
12486 
12487   // The target independent DAG combiner will leave a build_vector of
12488   // float-to-int conversions intact. We can generate MUCH better code for
12489   // a float-to-int conversion of a vector of floats.
12490   SDValue FirstInput = N->getOperand(0);
12491   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12492     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12493     if (Reduced)
12494       return Reduced;
12495   }
12496 
12497   // If we're building a vector out of consecutive loads, just load that
12498   // vector type.
12499   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12500   if (Reduced)
12501     return Reduced;
12502 
12503   // If we're building a vector out of extended elements from another vector
12504   // we have P9 vector integer extend instructions. The code assumes legal
12505   // input types (i.e. it can't handle things like v4i16) so do not run before
12506   // legalization.
12507   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
12508     Reduced = combineBVOfVecSExt(N, DAG);
12509     if (Reduced)
12510       return Reduced;
12511   }
12512 
12513 
12514   if (N->getValueType(0) != MVT::v2f64)
12515     return SDValue();
12516 
12517   // Looking for:
12518   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12519   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12520       FirstInput.getOpcode() != ISD::UINT_TO_FP)
12521     return SDValue();
12522   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12523       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12524     return SDValue();
12525   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12526     return SDValue();
12527 
12528   SDValue Ext1 = FirstInput.getOperand(0);
12529   SDValue Ext2 = N->getOperand(1).getOperand(0);
12530   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12531      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12532     return SDValue();
12533 
12534   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12535   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12536   if (!Ext1Op || !Ext2Op)
12537     return SDValue();
12538   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
12539       Ext1.getOperand(0) != Ext2.getOperand(0))
12540     return SDValue();
12541 
12542   int FirstElem = Ext1Op->getZExtValue();
12543   int SecondElem = Ext2Op->getZExtValue();
12544   int SubvecIdx;
12545   if (FirstElem == 0 && SecondElem == 1)
12546     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12547   else if (FirstElem == 2 && SecondElem == 3)
12548     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12549   else
12550     return SDValue();
12551 
12552   SDValue SrcVec = Ext1.getOperand(0);
12553   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12554     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12555   return DAG.getNode(NodeType, dl, MVT::v2f64,
12556                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12557 }
12558 
12559 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12560                                               DAGCombinerInfo &DCI) const {
12561   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12562           N->getOpcode() == ISD::UINT_TO_FP) &&
12563          "Need an int -> FP conversion node here");
12564 
12565   if (useSoftFloat() || !Subtarget.has64BitSupport())
12566     return SDValue();
12567 
12568   SelectionDAG &DAG = DCI.DAG;
12569   SDLoc dl(N);
12570   SDValue Op(N, 0);
12571 
12572   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12573   // from the hardware.
12574   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12575     return SDValue();
12576   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12577       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12578     return SDValue();
12579 
12580   SDValue FirstOperand(Op.getOperand(0));
12581   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12582     (FirstOperand.getValueType() == MVT::i8 ||
12583      FirstOperand.getValueType() == MVT::i16);
12584   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12585     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12586     bool DstDouble = Op.getValueType() == MVT::f64;
12587     unsigned ConvOp = Signed ?
12588       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12589       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12590     SDValue WidthConst =
12591       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12592                             dl, false);
12593     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12594     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12595     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12596                                          DAG.getVTList(MVT::f64, MVT::Other),
12597                                          Ops, MVT::i8, LDN->getMemOperand());
12598 
12599     // For signed conversion, we need to sign-extend the value in the VSR
12600     if (Signed) {
12601       SDValue ExtOps[] = { Ld, WidthConst };
12602       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12603       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12604     } else
12605       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12606   }
12607 
12608 
12609   // For i32 intermediate values, unfortunately, the conversion functions
12610   // leave the upper 32 bits of the value are undefined. Within the set of
12611   // scalar instructions, we have no method for zero- or sign-extending the
12612   // value. Thus, we cannot handle i32 intermediate values here.
12613   if (Op.getOperand(0).getValueType() == MVT::i32)
12614     return SDValue();
12615 
12616   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12617          "UINT_TO_FP is supported only with FPCVT");
12618 
12619   // If we have FCFIDS, then use it when converting to single-precision.
12620   // Otherwise, convert to double-precision and then round.
12621   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12622                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12623                                                             : PPCISD::FCFIDS)
12624                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12625                                                             : PPCISD::FCFID);
12626   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12627                   ? MVT::f32
12628                   : MVT::f64;
12629 
12630   // If we're converting from a float, to an int, and back to a float again,
12631   // then we don't need the store/load pair at all.
12632   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12633        Subtarget.hasFPCVT()) ||
12634       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12635     SDValue Src = Op.getOperand(0).getOperand(0);
12636     if (Src.getValueType() == MVT::f32) {
12637       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12638       DCI.AddToWorklist(Src.getNode());
12639     } else if (Src.getValueType() != MVT::f64) {
12640       // Make sure that we don't pick up a ppc_fp128 source value.
12641       return SDValue();
12642     }
12643 
12644     unsigned FCTOp =
12645       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12646                                                         PPCISD::FCTIDUZ;
12647 
12648     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12649     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12650 
12651     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12652       FP = DAG.getNode(ISD::FP_ROUND, dl,
12653                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12654       DCI.AddToWorklist(FP.getNode());
12655     }
12656 
12657     return FP;
12658   }
12659 
12660   return SDValue();
12661 }
12662 
12663 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12664 // builtins) into loads with swaps.
12665 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12666                                               DAGCombinerInfo &DCI) const {
12667   SelectionDAG &DAG = DCI.DAG;
12668   SDLoc dl(N);
12669   SDValue Chain;
12670   SDValue Base;
12671   MachineMemOperand *MMO;
12672 
12673   switch (N->getOpcode()) {
12674   default:
12675     llvm_unreachable("Unexpected opcode for little endian VSX load");
12676   case ISD::LOAD: {
12677     LoadSDNode *LD = cast<LoadSDNode>(N);
12678     Chain = LD->getChain();
12679     Base = LD->getBasePtr();
12680     MMO = LD->getMemOperand();
12681     // If the MMO suggests this isn't a load of a full vector, leave
12682     // things alone.  For a built-in, we have to make the change for
12683     // correctness, so if there is a size problem that will be a bug.
12684     if (MMO->getSize() < 16)
12685       return SDValue();
12686     break;
12687   }
12688   case ISD::INTRINSIC_W_CHAIN: {
12689     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12690     Chain = Intrin->getChain();
12691     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12692     // us what we want. Get operand 2 instead.
12693     Base = Intrin->getOperand(2);
12694     MMO = Intrin->getMemOperand();
12695     break;
12696   }
12697   }
12698 
12699   MVT VecTy = N->getValueType(0).getSimpleVT();
12700 
12701   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12702   // aligned and the type is a vector with elements up to 4 bytes
12703   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12704       && VecTy.getScalarSizeInBits() <= 32 ) {
12705     return SDValue();
12706   }
12707 
12708   SDValue LoadOps[] = { Chain, Base };
12709   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12710                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12711                                          LoadOps, MVT::v2f64, MMO);
12712 
12713   DCI.AddToWorklist(Load.getNode());
12714   Chain = Load.getValue(1);
12715   SDValue Swap = DAG.getNode(
12716       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12717   DCI.AddToWorklist(Swap.getNode());
12718 
12719   // Add a bitcast if the resulting load type doesn't match v2f64.
12720   if (VecTy != MVT::v2f64) {
12721     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12722     DCI.AddToWorklist(N.getNode());
12723     // Package {bitcast value, swap's chain} to match Load's shape.
12724     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12725                        N, Swap.getValue(1));
12726   }
12727 
12728   return Swap;
12729 }
12730 
12731 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12732 // builtins) into stores with swaps.
12733 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12734                                                DAGCombinerInfo &DCI) const {
12735   SelectionDAG &DAG = DCI.DAG;
12736   SDLoc dl(N);
12737   SDValue Chain;
12738   SDValue Base;
12739   unsigned SrcOpnd;
12740   MachineMemOperand *MMO;
12741 
12742   switch (N->getOpcode()) {
12743   default:
12744     llvm_unreachable("Unexpected opcode for little endian VSX store");
12745   case ISD::STORE: {
12746     StoreSDNode *ST = cast<StoreSDNode>(N);
12747     Chain = ST->getChain();
12748     Base = ST->getBasePtr();
12749     MMO = ST->getMemOperand();
12750     SrcOpnd = 1;
12751     // If the MMO suggests this isn't a store of a full vector, leave
12752     // things alone.  For a built-in, we have to make the change for
12753     // correctness, so if there is a size problem that will be a bug.
12754     if (MMO->getSize() < 16)
12755       return SDValue();
12756     break;
12757   }
12758   case ISD::INTRINSIC_VOID: {
12759     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12760     Chain = Intrin->getChain();
12761     // Intrin->getBasePtr() oddly does not get what we want.
12762     Base = Intrin->getOperand(3);
12763     MMO = Intrin->getMemOperand();
12764     SrcOpnd = 2;
12765     break;
12766   }
12767   }
12768 
12769   SDValue Src = N->getOperand(SrcOpnd);
12770   MVT VecTy = Src.getValueType().getSimpleVT();
12771 
12772   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12773   // aligned and the type is a vector with elements up to 4 bytes
12774   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12775       && VecTy.getScalarSizeInBits() <= 32 ) {
12776     return SDValue();
12777   }
12778 
12779   // All stores are done as v2f64 and possible bit cast.
12780   if (VecTy != MVT::v2f64) {
12781     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12782     DCI.AddToWorklist(Src.getNode());
12783   }
12784 
12785   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12786                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12787   DCI.AddToWorklist(Swap.getNode());
12788   Chain = Swap.getValue(1);
12789   SDValue StoreOps[] = { Chain, Swap, Base };
12790   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12791                                           DAG.getVTList(MVT::Other),
12792                                           StoreOps, VecTy, MMO);
12793   DCI.AddToWorklist(Store.getNode());
12794   return Store;
12795 }
12796 
12797 // Handle DAG combine for STORE (FP_TO_INT F).
12798 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
12799                                                DAGCombinerInfo &DCI) const {
12800 
12801   SelectionDAG &DAG = DCI.DAG;
12802   SDLoc dl(N);
12803   unsigned Opcode = N->getOperand(1).getOpcode();
12804 
12805   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
12806          && "Not a FP_TO_INT Instruction!");
12807 
12808   SDValue Val = N->getOperand(1).getOperand(0);
12809   EVT Op1VT = N->getOperand(1).getValueType();
12810   EVT ResVT = Val.getValueType();
12811 
12812   // Floating point types smaller than 32 bits are not legal on Power.
12813   if (ResVT.getScalarSizeInBits() < 32)
12814     return SDValue();
12815 
12816   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
12817   bool ValidTypeForStoreFltAsInt =
12818         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
12819          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
12820 
12821   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
12822       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
12823     return SDValue();
12824 
12825   // Extend f32 values to f64
12826   if (ResVT.getScalarSizeInBits() == 32) {
12827     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12828     DCI.AddToWorklist(Val.getNode());
12829   }
12830 
12831   // Set signed or unsigned conversion opcode.
12832   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
12833                           PPCISD::FP_TO_SINT_IN_VSR :
12834                           PPCISD::FP_TO_UINT_IN_VSR;
12835 
12836   Val = DAG.getNode(ConvOpcode,
12837                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
12838   DCI.AddToWorklist(Val.getNode());
12839 
12840   // Set number of bytes being converted.
12841   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
12842   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
12843                     DAG.getIntPtrConstant(ByteSize, dl, false),
12844                     DAG.getValueType(Op1VT) };
12845 
12846   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
12847           DAG.getVTList(MVT::Other), Ops,
12848           cast<StoreSDNode>(N)->getMemoryVT(),
12849           cast<StoreSDNode>(N)->getMemOperand());
12850 
12851   DCI.AddToWorklist(Val.getNode());
12852   return Val;
12853 }
12854 
12855 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12856                                              DAGCombinerInfo &DCI) const {
12857   SelectionDAG &DAG = DCI.DAG;
12858   SDLoc dl(N);
12859   switch (N->getOpcode()) {
12860   default: break;
12861   case ISD::ADD:
12862     return combineADD(N, DCI);
12863   case ISD::SHL:
12864     return combineSHL(N, DCI);
12865   case ISD::SRA:
12866     return combineSRA(N, DCI);
12867   case ISD::SRL:
12868     return combineSRL(N, DCI);
12869   case ISD::MUL:
12870     return combineMUL(N, DCI);
12871   case PPCISD::SHL:
12872     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12873         return N->getOperand(0);
12874     break;
12875   case PPCISD::SRL:
12876     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12877         return N->getOperand(0);
12878     break;
12879   case PPCISD::SRA:
12880     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12881       if (C->isNullValue() ||   //  0 >>s V -> 0.
12882           C->isAllOnesValue())    // -1 >>s V -> -1.
12883         return N->getOperand(0);
12884     }
12885     break;
12886   case ISD::SIGN_EXTEND:
12887   case ISD::ZERO_EXTEND:
12888   case ISD::ANY_EXTEND:
12889     return DAGCombineExtBoolTrunc(N, DCI);
12890   case ISD::TRUNCATE:
12891     return combineTRUNCATE(N, DCI);
12892   case ISD::SETCC:
12893     if (SDValue CSCC = combineSetCC(N, DCI))
12894       return CSCC;
12895     LLVM_FALLTHROUGH;
12896   case ISD::SELECT_CC:
12897     return DAGCombineTruncBoolExt(N, DCI);
12898   case ISD::SINT_TO_FP:
12899   case ISD::UINT_TO_FP:
12900     return combineFPToIntToFP(N, DCI);
12901   case ISD::STORE: {
12902 
12903     EVT Op1VT = N->getOperand(1).getValueType();
12904     unsigned Opcode = N->getOperand(1).getOpcode();
12905 
12906     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
12907       SDValue Val= combineStoreFPToInt(N, DCI);
12908       if (Val)
12909         return Val;
12910     }
12911 
12912     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12913     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
12914         N->getOperand(1).getNode()->hasOneUse() &&
12915         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
12916          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
12917 
12918       // STBRX can only handle simple types and it makes no sense to store less
12919       // two bytes in byte-reversed order.
12920       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12921       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
12922         break;
12923 
12924       SDValue BSwapOp = N->getOperand(1).getOperand(0);
12925       // Do an any-extend to 32-bits if this is a half-word input.
12926       if (BSwapOp.getValueType() == MVT::i16)
12927         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12928 
12929       // If the type of BSWAP operand is wider than stored memory width
12930       // it need to be shifted to the right side before STBRX.
12931       if (Op1VT.bitsGT(mVT)) {
12932         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12933         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12934                               DAG.getConstant(Shift, dl, MVT::i32));
12935         // Need to truncate if this is a bswap of i64 stored as i32/i16.
12936         if (Op1VT == MVT::i64)
12937           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12938       }
12939 
12940       SDValue Ops[] = {
12941         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12942       };
12943       return
12944         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12945                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12946                                 cast<StoreSDNode>(N)->getMemOperand());
12947     }
12948 
12949     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
12950     // So it can increase the chance of CSE constant construction.
12951     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
12952         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
12953       // Need to sign-extended to 64-bits to handle negative values.
12954       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
12955       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
12956                                     MemVT.getSizeInBits());
12957       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
12958 
12959       // DAG.getTruncStore() can't be used here because it doesn't accept
12960       // the general (base + offset) addressing mode.
12961       // So we use UpdateNodeOperands and setTruncatingStore instead.
12962       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
12963                              N->getOperand(3));
12964       cast<StoreSDNode>(N)->setTruncatingStore(true);
12965       return SDValue(N, 0);
12966     }
12967 
12968     // For little endian, VSX stores require generating xxswapd/lxvd2x.
12969     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12970     if (Op1VT.isSimple()) {
12971       MVT StoreVT = Op1VT.getSimpleVT();
12972       if (Subtarget.needsSwapsForVSXMemOps() &&
12973           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12974            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12975         return expandVSXStoreForLE(N, DCI);
12976     }
12977     break;
12978   }
12979   case ISD::LOAD: {
12980     LoadSDNode *LD = cast<LoadSDNode>(N);
12981     EVT VT = LD->getValueType(0);
12982 
12983     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12984     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12985     if (VT.isSimple()) {
12986       MVT LoadVT = VT.getSimpleVT();
12987       if (Subtarget.needsSwapsForVSXMemOps() &&
12988           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12989            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12990         return expandVSXLoadForLE(N, DCI);
12991     }
12992 
12993     // We sometimes end up with a 64-bit integer load, from which we extract
12994     // two single-precision floating-point numbers. This happens with
12995     // std::complex<float>, and other similar structures, because of the way we
12996     // canonicalize structure copies. However, if we lack direct moves,
12997     // then the final bitcasts from the extracted integer values to the
12998     // floating-point numbers turn into store/load pairs. Even with direct moves,
12999     // just loading the two floating-point numbers is likely better.
13000     auto ReplaceTwoFloatLoad = [&]() {
13001       if (VT != MVT::i64)
13002         return false;
13003 
13004       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13005           LD->isVolatile())
13006         return false;
13007 
13008       //  We're looking for a sequence like this:
13009       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13010       //      t16: i64 = srl t13, Constant:i32<32>
13011       //    t17: i32 = truncate t16
13012       //  t18: f32 = bitcast t17
13013       //    t19: i32 = truncate t13
13014       //  t20: f32 = bitcast t19
13015 
13016       if (!LD->hasNUsesOfValue(2, 0))
13017         return false;
13018 
13019       auto UI = LD->use_begin();
13020       while (UI.getUse().getResNo() != 0) ++UI;
13021       SDNode *Trunc = *UI++;
13022       while (UI.getUse().getResNo() != 0) ++UI;
13023       SDNode *RightShift = *UI;
13024       if (Trunc->getOpcode() != ISD::TRUNCATE)
13025         std::swap(Trunc, RightShift);
13026 
13027       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13028           Trunc->getValueType(0) != MVT::i32 ||
13029           !Trunc->hasOneUse())
13030         return false;
13031       if (RightShift->getOpcode() != ISD::SRL ||
13032           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13033           RightShift->getConstantOperandVal(1) != 32 ||
13034           !RightShift->hasOneUse())
13035         return false;
13036 
13037       SDNode *Trunc2 = *RightShift->use_begin();
13038       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13039           Trunc2->getValueType(0) != MVT::i32 ||
13040           !Trunc2->hasOneUse())
13041         return false;
13042 
13043       SDNode *Bitcast = *Trunc->use_begin();
13044       SDNode *Bitcast2 = *Trunc2->use_begin();
13045 
13046       if (Bitcast->getOpcode() != ISD::BITCAST ||
13047           Bitcast->getValueType(0) != MVT::f32)
13048         return false;
13049       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13050           Bitcast2->getValueType(0) != MVT::f32)
13051         return false;
13052 
13053       if (Subtarget.isLittleEndian())
13054         std::swap(Bitcast, Bitcast2);
13055 
13056       // Bitcast has the second float (in memory-layout order) and Bitcast2
13057       // has the first one.
13058 
13059       SDValue BasePtr = LD->getBasePtr();
13060       if (LD->isIndexed()) {
13061         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13062                "Non-pre-inc AM on PPC?");
13063         BasePtr =
13064           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13065                       LD->getOffset());
13066       }
13067 
13068       auto MMOFlags =
13069           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13070       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13071                                       LD->getPointerInfo(), LD->getAlignment(),
13072                                       MMOFlags, LD->getAAInfo());
13073       SDValue AddPtr =
13074         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13075                     BasePtr, DAG.getIntPtrConstant(4, dl));
13076       SDValue FloatLoad2 = DAG.getLoad(
13077           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13078           LD->getPointerInfo().getWithOffset(4),
13079           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13080 
13081       if (LD->isIndexed()) {
13082         // Note that DAGCombine should re-form any pre-increment load(s) from
13083         // what is produced here if that makes sense.
13084         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13085       }
13086 
13087       DCI.CombineTo(Bitcast2, FloatLoad);
13088       DCI.CombineTo(Bitcast, FloatLoad2);
13089 
13090       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13091                                     SDValue(FloatLoad2.getNode(), 1));
13092       return true;
13093     };
13094 
13095     if (ReplaceTwoFloatLoad())
13096       return SDValue(N, 0);
13097 
13098     EVT MemVT = LD->getMemoryVT();
13099     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13100     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13101     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13102     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13103     if (LD->isUnindexed() && VT.isVector() &&
13104         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13105           // P8 and later hardware should just use LOAD.
13106           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13107                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13108          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13109           LD->getAlignment() >= ScalarABIAlignment)) &&
13110         LD->getAlignment() < ABIAlignment) {
13111       // This is a type-legal unaligned Altivec or QPX load.
13112       SDValue Chain = LD->getChain();
13113       SDValue Ptr = LD->getBasePtr();
13114       bool isLittleEndian = Subtarget.isLittleEndian();
13115 
13116       // This implements the loading of unaligned vectors as described in
13117       // the venerable Apple Velocity Engine overview. Specifically:
13118       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13119       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13120       //
13121       // The general idea is to expand a sequence of one or more unaligned
13122       // loads into an alignment-based permutation-control instruction (lvsl
13123       // or lvsr), a series of regular vector loads (which always truncate
13124       // their input address to an aligned address), and a series of
13125       // permutations.  The results of these permutations are the requested
13126       // loaded values.  The trick is that the last "extra" load is not taken
13127       // from the address you might suspect (sizeof(vector) bytes after the
13128       // last requested load), but rather sizeof(vector) - 1 bytes after the
13129       // last requested vector. The point of this is to avoid a page fault if
13130       // the base address happened to be aligned. This works because if the
13131       // base address is aligned, then adding less than a full vector length
13132       // will cause the last vector in the sequence to be (re)loaded.
13133       // Otherwise, the next vector will be fetched as you might suspect was
13134       // necessary.
13135 
13136       // We might be able to reuse the permutation generation from
13137       // a different base address offset from this one by an aligned amount.
13138       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13139       // optimization later.
13140       Intrinsic::ID Intr, IntrLD, IntrPerm;
13141       MVT PermCntlTy, PermTy, LDTy;
13142       if (Subtarget.hasAltivec()) {
13143         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13144                                  Intrinsic::ppc_altivec_lvsl;
13145         IntrLD = Intrinsic::ppc_altivec_lvx;
13146         IntrPerm = Intrinsic::ppc_altivec_vperm;
13147         PermCntlTy = MVT::v16i8;
13148         PermTy = MVT::v4i32;
13149         LDTy = MVT::v4i32;
13150       } else {
13151         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13152                                        Intrinsic::ppc_qpx_qvlpcls;
13153         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13154                                        Intrinsic::ppc_qpx_qvlfs;
13155         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13156         PermCntlTy = MVT::v4f64;
13157         PermTy = MVT::v4f64;
13158         LDTy = MemVT.getSimpleVT();
13159       }
13160 
13161       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13162 
13163       // Create the new MMO for the new base load. It is like the original MMO,
13164       // but represents an area in memory almost twice the vector size centered
13165       // on the original address. If the address is unaligned, we might start
13166       // reading up to (sizeof(vector)-1) bytes below the address of the
13167       // original unaligned load.
13168       MachineFunction &MF = DAG.getMachineFunction();
13169       MachineMemOperand *BaseMMO =
13170         MF.getMachineMemOperand(LD->getMemOperand(),
13171                                 -(long)MemVT.getStoreSize()+1,
13172                                 2*MemVT.getStoreSize()-1);
13173 
13174       // Create the new base load.
13175       SDValue LDXIntID =
13176           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13177       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13178       SDValue BaseLoad =
13179         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13180                                 DAG.getVTList(PermTy, MVT::Other),
13181                                 BaseLoadOps, LDTy, BaseMMO);
13182 
13183       // Note that the value of IncOffset (which is provided to the next
13184       // load's pointer info offset value, and thus used to calculate the
13185       // alignment), and the value of IncValue (which is actually used to
13186       // increment the pointer value) are different! This is because we
13187       // require the next load to appear to be aligned, even though it
13188       // is actually offset from the base pointer by a lesser amount.
13189       int IncOffset = VT.getSizeInBits() / 8;
13190       int IncValue = IncOffset;
13191 
13192       // Walk (both up and down) the chain looking for another load at the real
13193       // (aligned) offset (the alignment of the other load does not matter in
13194       // this case). If found, then do not use the offset reduction trick, as
13195       // that will prevent the loads from being later combined (as they would
13196       // otherwise be duplicates).
13197       if (!findConsecutiveLoad(LD, DAG))
13198         --IncValue;
13199 
13200       SDValue Increment =
13201           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13202       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13203 
13204       MachineMemOperand *ExtraMMO =
13205         MF.getMachineMemOperand(LD->getMemOperand(),
13206                                 1, 2*MemVT.getStoreSize()-1);
13207       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13208       SDValue ExtraLoad =
13209         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13210                                 DAG.getVTList(PermTy, MVT::Other),
13211                                 ExtraLoadOps, LDTy, ExtraMMO);
13212 
13213       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13214         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13215 
13216       // Because vperm has a big-endian bias, we must reverse the order
13217       // of the input vectors and complement the permute control vector
13218       // when generating little endian code.  We have already handled the
13219       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13220       // and ExtraLoad here.
13221       SDValue Perm;
13222       if (isLittleEndian)
13223         Perm = BuildIntrinsicOp(IntrPerm,
13224                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13225       else
13226         Perm = BuildIntrinsicOp(IntrPerm,
13227                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13228 
13229       if (VT != PermTy)
13230         Perm = Subtarget.hasAltivec() ?
13231                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13232                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13233                                DAG.getTargetConstant(1, dl, MVT::i64));
13234                                // second argument is 1 because this rounding
13235                                // is always exact.
13236 
13237       // The output of the permutation is our loaded result, the TokenFactor is
13238       // our new chain.
13239       DCI.CombineTo(N, Perm, TF);
13240       return SDValue(N, 0);
13241     }
13242     }
13243     break;
13244     case ISD::INTRINSIC_WO_CHAIN: {
13245       bool isLittleEndian = Subtarget.isLittleEndian();
13246       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13247       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13248                                            : Intrinsic::ppc_altivec_lvsl);
13249       if ((IID == Intr ||
13250            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13251            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13252         N->getOperand(1)->getOpcode() == ISD::ADD) {
13253         SDValue Add = N->getOperand(1);
13254 
13255         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13256                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13257 
13258         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13259                                   APInt::getAllOnesValue(Bits /* alignment */)
13260                                       .zext(Add.getScalarValueSizeInBits()))) {
13261           SDNode *BasePtr = Add->getOperand(0).getNode();
13262           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13263                                     UE = BasePtr->use_end();
13264                UI != UE; ++UI) {
13265             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13266                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13267               // We've found another LVSL/LVSR, and this address is an aligned
13268               // multiple of that one. The results will be the same, so use the
13269               // one we've just found instead.
13270 
13271               return SDValue(*UI, 0);
13272             }
13273           }
13274         }
13275 
13276         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13277           SDNode *BasePtr = Add->getOperand(0).getNode();
13278           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13279                UE = BasePtr->use_end(); UI != UE; ++UI) {
13280             if (UI->getOpcode() == ISD::ADD &&
13281                 isa<ConstantSDNode>(UI->getOperand(1)) &&
13282                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13283                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13284                 (1ULL << Bits) == 0) {
13285               SDNode *OtherAdd = *UI;
13286               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13287                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
13288                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13289                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13290                   return SDValue(*VI, 0);
13291                 }
13292               }
13293             }
13294           }
13295         }
13296       }
13297 
13298       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13299       // Expose the vabsduw/h/b opportunity for down stream
13300       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13301           (IID == Intrinsic::ppc_altivec_vmaxsw ||
13302            IID == Intrinsic::ppc_altivec_vmaxsh ||
13303            IID == Intrinsic::ppc_altivec_vmaxsb)) {
13304         SDValue V1 = N->getOperand(1);
13305         SDValue V2 = N->getOperand(2);
13306         if ((V1.getSimpleValueType() == MVT::v4i32 ||
13307              V1.getSimpleValueType() == MVT::v8i16 ||
13308              V1.getSimpleValueType() == MVT::v16i8) &&
13309             V1.getSimpleValueType() == V2.getSimpleValueType()) {
13310           // (0-a, a)
13311           if (V1.getOpcode() == ISD::SUB &&
13312               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
13313               V1.getOperand(1) == V2) {
13314             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
13315           }
13316           // (a, 0-a)
13317           if (V2.getOpcode() == ISD::SUB &&
13318               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
13319               V2.getOperand(1) == V1) {
13320             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13321           }
13322           // (x-y, y-x)
13323           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
13324               V1.getOperand(0) == V2.getOperand(1) &&
13325               V1.getOperand(1) == V2.getOperand(0)) {
13326             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13327           }
13328         }
13329       }
13330     }
13331 
13332     break;
13333   case ISD::INTRINSIC_W_CHAIN:
13334     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13335     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13336     if (Subtarget.needsSwapsForVSXMemOps()) {
13337       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13338       default:
13339         break;
13340       case Intrinsic::ppc_vsx_lxvw4x:
13341       case Intrinsic::ppc_vsx_lxvd2x:
13342         return expandVSXLoadForLE(N, DCI);
13343       }
13344     }
13345     break;
13346   case ISD::INTRINSIC_VOID:
13347     // For little endian, VSX stores require generating xxswapd/stxvd2x.
13348     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13349     if (Subtarget.needsSwapsForVSXMemOps()) {
13350       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13351       default:
13352         break;
13353       case Intrinsic::ppc_vsx_stxvw4x:
13354       case Intrinsic::ppc_vsx_stxvd2x:
13355         return expandVSXStoreForLE(N, DCI);
13356       }
13357     }
13358     break;
13359   case ISD::BSWAP:
13360     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
13361     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
13362         N->getOperand(0).hasOneUse() &&
13363         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
13364          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
13365           N->getValueType(0) == MVT::i64))) {
13366       SDValue Load = N->getOperand(0);
13367       LoadSDNode *LD = cast<LoadSDNode>(Load);
13368       // Create the byte-swapping load.
13369       SDValue Ops[] = {
13370         LD->getChain(),    // Chain
13371         LD->getBasePtr(),  // Ptr
13372         DAG.getValueType(N->getValueType(0)) // VT
13373       };
13374       SDValue BSLoad =
13375         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
13376                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
13377                                               MVT::i64 : MVT::i32, MVT::Other),
13378                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
13379 
13380       // If this is an i16 load, insert the truncate.
13381       SDValue ResVal = BSLoad;
13382       if (N->getValueType(0) == MVT::i16)
13383         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
13384 
13385       // First, combine the bswap away.  This makes the value produced by the
13386       // load dead.
13387       DCI.CombineTo(N, ResVal);
13388 
13389       // Next, combine the load away, we give it a bogus result value but a real
13390       // chain result.  The result value is dead because the bswap is dead.
13391       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
13392 
13393       // Return N so it doesn't get rechecked!
13394       return SDValue(N, 0);
13395     }
13396     break;
13397   case PPCISD::VCMP:
13398     // If a VCMPo node already exists with exactly the same operands as this
13399     // node, use its result instead of this node (VCMPo computes both a CR6 and
13400     // a normal output).
13401     //
13402     if (!N->getOperand(0).hasOneUse() &&
13403         !N->getOperand(1).hasOneUse() &&
13404         !N->getOperand(2).hasOneUse()) {
13405 
13406       // Scan all of the users of the LHS, looking for VCMPo's that match.
13407       SDNode *VCMPoNode = nullptr;
13408 
13409       SDNode *LHSN = N->getOperand(0).getNode();
13410       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
13411            UI != E; ++UI)
13412         if (UI->getOpcode() == PPCISD::VCMPo &&
13413             UI->getOperand(1) == N->getOperand(1) &&
13414             UI->getOperand(2) == N->getOperand(2) &&
13415             UI->getOperand(0) == N->getOperand(0)) {
13416           VCMPoNode = *UI;
13417           break;
13418         }
13419 
13420       // If there is no VCMPo node, or if the flag value has a single use, don't
13421       // transform this.
13422       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
13423         break;
13424 
13425       // Look at the (necessarily single) use of the flag value.  If it has a
13426       // chain, this transformation is more complex.  Note that multiple things
13427       // could use the value result, which we should ignore.
13428       SDNode *FlagUser = nullptr;
13429       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
13430            FlagUser == nullptr; ++UI) {
13431         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
13432         SDNode *User = *UI;
13433         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
13434           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
13435             FlagUser = User;
13436             break;
13437           }
13438         }
13439       }
13440 
13441       // If the user is a MFOCRF instruction, we know this is safe.
13442       // Otherwise we give up for right now.
13443       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
13444         return SDValue(VCMPoNode, 0);
13445     }
13446     break;
13447   case ISD::BRCOND: {
13448     SDValue Cond = N->getOperand(1);
13449     SDValue Target = N->getOperand(2);
13450 
13451     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13452         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
13453           Intrinsic::ppc_is_decremented_ctr_nonzero) {
13454 
13455       // We now need to make the intrinsic dead (it cannot be instruction
13456       // selected).
13457       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
13458       assert(Cond.getNode()->hasOneUse() &&
13459              "Counter decrement has more than one use");
13460 
13461       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
13462                          N->getOperand(0), Target);
13463     }
13464   }
13465   break;
13466   case ISD::BR_CC: {
13467     // If this is a branch on an altivec predicate comparison, lower this so
13468     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
13469     // lowering is done pre-legalize, because the legalizer lowers the predicate
13470     // compare down to code that is difficult to reassemble.
13471     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13472     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13473 
13474     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13475     // value. If so, pass-through the AND to get to the intrinsic.
13476     if (LHS.getOpcode() == ISD::AND &&
13477         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13478         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13479           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13480         isa<ConstantSDNode>(LHS.getOperand(1)) &&
13481         !isNullConstant(LHS.getOperand(1)))
13482       LHS = LHS.getOperand(0);
13483 
13484     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13485         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13486           Intrinsic::ppc_is_decremented_ctr_nonzero &&
13487         isa<ConstantSDNode>(RHS)) {
13488       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13489              "Counter decrement comparison is not EQ or NE");
13490 
13491       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13492       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13493                     (CC == ISD::SETNE && !Val);
13494 
13495       // We now need to make the intrinsic dead (it cannot be instruction
13496       // selected).
13497       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13498       assert(LHS.getNode()->hasOneUse() &&
13499              "Counter decrement has more than one use");
13500 
13501       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13502                          N->getOperand(0), N->getOperand(4));
13503     }
13504 
13505     int CompareOpc;
13506     bool isDot;
13507 
13508     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13509         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13510         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13511       assert(isDot && "Can't compare against a vector result!");
13512 
13513       // If this is a comparison against something other than 0/1, then we know
13514       // that the condition is never/always true.
13515       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13516       if (Val != 0 && Val != 1) {
13517         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
13518           return N->getOperand(0);
13519         // Always !=, turn it into an unconditional branch.
13520         return DAG.getNode(ISD::BR, dl, MVT::Other,
13521                            N->getOperand(0), N->getOperand(4));
13522       }
13523 
13524       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13525 
13526       // Create the PPCISD altivec 'dot' comparison node.
13527       SDValue Ops[] = {
13528         LHS.getOperand(2),  // LHS of compare
13529         LHS.getOperand(3),  // RHS of compare
13530         DAG.getConstant(CompareOpc, dl, MVT::i32)
13531       };
13532       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
13533       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
13534 
13535       // Unpack the result based on how the target uses it.
13536       PPC::Predicate CompOpc;
13537       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
13538       default:  // Can't happen, don't crash on invalid number though.
13539       case 0:   // Branch on the value of the EQ bit of CR6.
13540         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
13541         break;
13542       case 1:   // Branch on the inverted value of the EQ bit of CR6.
13543         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
13544         break;
13545       case 2:   // Branch on the value of the LT bit of CR6.
13546         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
13547         break;
13548       case 3:   // Branch on the inverted value of the LT bit of CR6.
13549         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
13550         break;
13551       }
13552 
13553       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
13554                          DAG.getConstant(CompOpc, dl, MVT::i32),
13555                          DAG.getRegister(PPC::CR6, MVT::i32),
13556                          N->getOperand(4), CompNode.getValue(1));
13557     }
13558     break;
13559   }
13560   case ISD::BUILD_VECTOR:
13561     return DAGCombineBuildVector(N, DCI);
13562   case ISD::ABS:
13563     return combineABS(N, DCI);
13564   case ISD::VSELECT:
13565     return combineVSelect(N, DCI);
13566   }
13567 
13568   return SDValue();
13569 }
13570 
13571 SDValue
13572 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13573                                  SelectionDAG &DAG,
13574                                  SmallVectorImpl<SDNode *> &Created) const {
13575   // fold (sdiv X, pow2)
13576   EVT VT = N->getValueType(0);
13577   if (VT == MVT::i64 && !Subtarget.isPPC64())
13578     return SDValue();
13579   if ((VT != MVT::i32 && VT != MVT::i64) ||
13580       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
13581     return SDValue();
13582 
13583   SDLoc DL(N);
13584   SDValue N0 = N->getOperand(0);
13585 
13586   bool IsNegPow2 = (-Divisor).isPowerOf2();
13587   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
13588   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
13589 
13590   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
13591   Created.push_back(Op.getNode());
13592 
13593   if (IsNegPow2) {
13594     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13595     Created.push_back(Op.getNode());
13596   }
13597 
13598   return Op;
13599 }
13600 
13601 //===----------------------------------------------------------------------===//
13602 // Inline Assembly Support
13603 //===----------------------------------------------------------------------===//
13604 
13605 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13606                                                       KnownBits &Known,
13607                                                       const APInt &DemandedElts,
13608                                                       const SelectionDAG &DAG,
13609                                                       unsigned Depth) const {
13610   Known.resetAll();
13611   switch (Op.getOpcode()) {
13612   default: break;
13613   case PPCISD::LBRX: {
13614     // lhbrx is known to have the top bits cleared out.
13615     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13616       Known.Zero = 0xFFFF0000;
13617     break;
13618   }
13619   case ISD::INTRINSIC_WO_CHAIN: {
13620     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13621     default: break;
13622     case Intrinsic::ppc_altivec_vcmpbfp_p:
13623     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13624     case Intrinsic::ppc_altivec_vcmpequb_p:
13625     case Intrinsic::ppc_altivec_vcmpequh_p:
13626     case Intrinsic::ppc_altivec_vcmpequw_p:
13627     case Intrinsic::ppc_altivec_vcmpequd_p:
13628     case Intrinsic::ppc_altivec_vcmpgefp_p:
13629     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13630     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13631     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13632     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13633     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13634     case Intrinsic::ppc_altivec_vcmpgtub_p:
13635     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13636     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13637     case Intrinsic::ppc_altivec_vcmpgtud_p:
13638       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13639       break;
13640     }
13641   }
13642   }
13643 }
13644 
13645 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13646   switch (Subtarget.getDarwinDirective()) {
13647   default: break;
13648   case PPC::DIR_970:
13649   case PPC::DIR_PWR4:
13650   case PPC::DIR_PWR5:
13651   case PPC::DIR_PWR5X:
13652   case PPC::DIR_PWR6:
13653   case PPC::DIR_PWR6X:
13654   case PPC::DIR_PWR7:
13655   case PPC::DIR_PWR8:
13656   case PPC::DIR_PWR9: {
13657     if (!ML)
13658       break;
13659 
13660     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13661 
13662     // For small loops (between 5 and 8 instructions), align to a 32-byte
13663     // boundary so that the entire loop fits in one instruction-cache line.
13664     uint64_t LoopSize = 0;
13665     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13666       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13667         LoopSize += TII->getInstSizeInBytes(*J);
13668         if (LoopSize > 32)
13669           break;
13670       }
13671 
13672     if (LoopSize > 16 && LoopSize <= 32)
13673       return 5;
13674 
13675     break;
13676   }
13677   }
13678 
13679   return TargetLowering::getPrefLoopAlignment(ML);
13680 }
13681 
13682 /// getConstraintType - Given a constraint, return the type of
13683 /// constraint it is for this target.
13684 PPCTargetLowering::ConstraintType
13685 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13686   if (Constraint.size() == 1) {
13687     switch (Constraint[0]) {
13688     default: break;
13689     case 'b':
13690     case 'r':
13691     case 'f':
13692     case 'd':
13693     case 'v':
13694     case 'y':
13695       return C_RegisterClass;
13696     case 'Z':
13697       // FIXME: While Z does indicate a memory constraint, it specifically
13698       // indicates an r+r address (used in conjunction with the 'y' modifier
13699       // in the replacement string). Currently, we're forcing the base
13700       // register to be r0 in the asm printer (which is interpreted as zero)
13701       // and forming the complete address in the second register. This is
13702       // suboptimal.
13703       return C_Memory;
13704     }
13705   } else if (Constraint == "wc") { // individual CR bits.
13706     return C_RegisterClass;
13707   } else if (Constraint == "wa" || Constraint == "wd" ||
13708              Constraint == "wf" || Constraint == "ws" ||
13709              Constraint == "wi") {
13710     return C_RegisterClass; // VSX registers.
13711   }
13712   return TargetLowering::getConstraintType(Constraint);
13713 }
13714 
13715 /// Examine constraint type and operand type and determine a weight value.
13716 /// This object must already have been set up with the operand type
13717 /// and the current alternative constraint selected.
13718 TargetLowering::ConstraintWeight
13719 PPCTargetLowering::getSingleConstraintMatchWeight(
13720     AsmOperandInfo &info, const char *constraint) const {
13721   ConstraintWeight weight = CW_Invalid;
13722   Value *CallOperandVal = info.CallOperandVal;
13723     // If we don't have a value, we can't do a match,
13724     // but allow it at the lowest weight.
13725   if (!CallOperandVal)
13726     return CW_Default;
13727   Type *type = CallOperandVal->getType();
13728 
13729   // Look at the constraint type.
13730   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13731     return CW_Register; // an individual CR bit.
13732   else if ((StringRef(constraint) == "wa" ||
13733             StringRef(constraint) == "wd" ||
13734             StringRef(constraint) == "wf") &&
13735            type->isVectorTy())
13736     return CW_Register;
13737   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13738     return CW_Register;
13739   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
13740     return CW_Register; // just hold 64-bit integers data.
13741 
13742   switch (*constraint) {
13743   default:
13744     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13745     break;
13746   case 'b':
13747     if (type->isIntegerTy())
13748       weight = CW_Register;
13749     break;
13750   case 'f':
13751     if (type->isFloatTy())
13752       weight = CW_Register;
13753     break;
13754   case 'd':
13755     if (type->isDoubleTy())
13756       weight = CW_Register;
13757     break;
13758   case 'v':
13759     if (type->isVectorTy())
13760       weight = CW_Register;
13761     break;
13762   case 'y':
13763     weight = CW_Register;
13764     break;
13765   case 'Z':
13766     weight = CW_Memory;
13767     break;
13768   }
13769   return weight;
13770 }
13771 
13772 std::pair<unsigned, const TargetRegisterClass *>
13773 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13774                                                 StringRef Constraint,
13775                                                 MVT VT) const {
13776   if (Constraint.size() == 1) {
13777     // GCC RS6000 Constraint Letters
13778     switch (Constraint[0]) {
13779     case 'b':   // R1-R31
13780       if (VT == MVT::i64 && Subtarget.isPPC64())
13781         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13782       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13783     case 'r':   // R0-R31
13784       if (VT == MVT::i64 && Subtarget.isPPC64())
13785         return std::make_pair(0U, &PPC::G8RCRegClass);
13786       return std::make_pair(0U, &PPC::GPRCRegClass);
13787     // 'd' and 'f' constraints are both defined to be "the floating point
13788     // registers", where one is for 32-bit and the other for 64-bit. We don't
13789     // really care overly much here so just give them all the same reg classes.
13790     case 'd':
13791     case 'f':
13792       if (Subtarget.hasSPE()) {
13793         if (VT == MVT::f32 || VT == MVT::i32)
13794           return std::make_pair(0U, &PPC::SPE4RCRegClass);
13795         if (VT == MVT::f64 || VT == MVT::i64)
13796           return std::make_pair(0U, &PPC::SPERCRegClass);
13797       } else {
13798         if (VT == MVT::f32 || VT == MVT::i32)
13799           return std::make_pair(0U, &PPC::F4RCRegClass);
13800         if (VT == MVT::f64 || VT == MVT::i64)
13801           return std::make_pair(0U, &PPC::F8RCRegClass);
13802         if (VT == MVT::v4f64 && Subtarget.hasQPX())
13803           return std::make_pair(0U, &PPC::QFRCRegClass);
13804         if (VT == MVT::v4f32 && Subtarget.hasQPX())
13805           return std::make_pair(0U, &PPC::QSRCRegClass);
13806       }
13807       break;
13808     case 'v':
13809       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13810         return std::make_pair(0U, &PPC::QFRCRegClass);
13811       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13812         return std::make_pair(0U, &PPC::QSRCRegClass);
13813       if (Subtarget.hasAltivec())
13814         return std::make_pair(0U, &PPC::VRRCRegClass);
13815       break;
13816     case 'y':   // crrc
13817       return std::make_pair(0U, &PPC::CRRCRegClass);
13818     }
13819   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13820     // An individual CR bit.
13821     return std::make_pair(0U, &PPC::CRBITRCRegClass);
13822   } else if ((Constraint == "wa" || Constraint == "wd" ||
13823              Constraint == "wf" || Constraint == "wi") &&
13824              Subtarget.hasVSX()) {
13825     return std::make_pair(0U, &PPC::VSRCRegClass);
13826   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13827     if (VT == MVT::f32 && Subtarget.hasP8Vector())
13828       return std::make_pair(0U, &PPC::VSSRCRegClass);
13829     else
13830       return std::make_pair(0U, &PPC::VSFRCRegClass);
13831   }
13832 
13833   std::pair<unsigned, const TargetRegisterClass *> R =
13834       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13835 
13836   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13837   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13838   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13839   // register.
13840   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13841   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13842   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13843       PPC::GPRCRegClass.contains(R.first))
13844     return std::make_pair(TRI->getMatchingSuperReg(R.first,
13845                             PPC::sub_32, &PPC::G8RCRegClass),
13846                           &PPC::G8RCRegClass);
13847 
13848   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13849   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13850     R.first = PPC::CR0;
13851     R.second = &PPC::CRRCRegClass;
13852   }
13853 
13854   return R;
13855 }
13856 
13857 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13858 /// vector.  If it is invalid, don't add anything to Ops.
13859 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13860                                                      std::string &Constraint,
13861                                                      std::vector<SDValue>&Ops,
13862                                                      SelectionDAG &DAG) const {
13863   SDValue Result;
13864 
13865   // Only support length 1 constraints.
13866   if (Constraint.length() > 1) return;
13867 
13868   char Letter = Constraint[0];
13869   switch (Letter) {
13870   default: break;
13871   case 'I':
13872   case 'J':
13873   case 'K':
13874   case 'L':
13875   case 'M':
13876   case 'N':
13877   case 'O':
13878   case 'P': {
13879     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13880     if (!CST) return; // Must be an immediate to match.
13881     SDLoc dl(Op);
13882     int64_t Value = CST->getSExtValue();
13883     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13884                          // numbers are printed as such.
13885     switch (Letter) {
13886     default: llvm_unreachable("Unknown constraint letter!");
13887     case 'I':  // "I" is a signed 16-bit constant.
13888       if (isInt<16>(Value))
13889         Result = DAG.getTargetConstant(Value, dl, TCVT);
13890       break;
13891     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
13892       if (isShiftedUInt<16, 16>(Value))
13893         Result = DAG.getTargetConstant(Value, dl, TCVT);
13894       break;
13895     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
13896       if (isShiftedInt<16, 16>(Value))
13897         Result = DAG.getTargetConstant(Value, dl, TCVT);
13898       break;
13899     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
13900       if (isUInt<16>(Value))
13901         Result = DAG.getTargetConstant(Value, dl, TCVT);
13902       break;
13903     case 'M':  // "M" is a constant that is greater than 31.
13904       if (Value > 31)
13905         Result = DAG.getTargetConstant(Value, dl, TCVT);
13906       break;
13907     case 'N':  // "N" is a positive constant that is an exact power of two.
13908       if (Value > 0 && isPowerOf2_64(Value))
13909         Result = DAG.getTargetConstant(Value, dl, TCVT);
13910       break;
13911     case 'O':  // "O" is the constant zero.
13912       if (Value == 0)
13913         Result = DAG.getTargetConstant(Value, dl, TCVT);
13914       break;
13915     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
13916       if (isInt<16>(-Value))
13917         Result = DAG.getTargetConstant(Value, dl, TCVT);
13918       break;
13919     }
13920     break;
13921   }
13922   }
13923 
13924   if (Result.getNode()) {
13925     Ops.push_back(Result);
13926     return;
13927   }
13928 
13929   // Handle standard constraint letters.
13930   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13931 }
13932 
13933 // isLegalAddressingMode - Return true if the addressing mode represented
13934 // by AM is legal for this target, for a load/store of the specified type.
13935 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13936                                               const AddrMode &AM, Type *Ty,
13937                                               unsigned AS, Instruction *I) const {
13938   // PPC does not allow r+i addressing modes for vectors!
13939   if (Ty->isVectorTy() && AM.BaseOffs != 0)
13940     return false;
13941 
13942   // PPC allows a sign-extended 16-bit immediate field.
13943   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13944     return false;
13945 
13946   // No global is ever allowed as a base.
13947   if (AM.BaseGV)
13948     return false;
13949 
13950   // PPC only support r+r,
13951   switch (AM.Scale) {
13952   case 0:  // "r+i" or just "i", depending on HasBaseReg.
13953     break;
13954   case 1:
13955     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
13956       return false;
13957     // Otherwise we have r+r or r+i.
13958     break;
13959   case 2:
13960     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
13961       return false;
13962     // Allow 2*r as r+r.
13963     break;
13964   default:
13965     // No other scales are supported.
13966     return false;
13967   }
13968 
13969   return true;
13970 }
13971 
13972 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13973                                            SelectionDAG &DAG) const {
13974   MachineFunction &MF = DAG.getMachineFunction();
13975   MachineFrameInfo &MFI = MF.getFrameInfo();
13976   MFI.setReturnAddressIsTaken(true);
13977 
13978   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13979     return SDValue();
13980 
13981   SDLoc dl(Op);
13982   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13983 
13984   // Make sure the function does not optimize away the store of the RA to
13985   // the stack.
13986   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13987   FuncInfo->setLRStoreRequired();
13988   bool isPPC64 = Subtarget.isPPC64();
13989   auto PtrVT = getPointerTy(MF.getDataLayout());
13990 
13991   if (Depth > 0) {
13992     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13993     SDValue Offset =
13994         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13995                         isPPC64 ? MVT::i64 : MVT::i32);
13996     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13997                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13998                        MachinePointerInfo());
13999   }
14000 
14001   // Just load the return address off the stack.
14002   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14003   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14004                      MachinePointerInfo());
14005 }
14006 
14007 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14008                                           SelectionDAG &DAG) const {
14009   SDLoc dl(Op);
14010   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14011 
14012   MachineFunction &MF = DAG.getMachineFunction();
14013   MachineFrameInfo &MFI = MF.getFrameInfo();
14014   MFI.setFrameAddressIsTaken(true);
14015 
14016   EVT PtrVT = getPointerTy(MF.getDataLayout());
14017   bool isPPC64 = PtrVT == MVT::i64;
14018 
14019   // Naked functions never have a frame pointer, and so we use r1. For all
14020   // other functions, this decision must be delayed until during PEI.
14021   unsigned FrameReg;
14022   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14023     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14024   else
14025     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14026 
14027   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14028                                          PtrVT);
14029   while (Depth--)
14030     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14031                             FrameAddr, MachinePointerInfo());
14032   return FrameAddr;
14033 }
14034 
14035 // FIXME? Maybe this could be a TableGen attribute on some registers and
14036 // this table could be generated automatically from RegInfo.
14037 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14038                                               SelectionDAG &DAG) const {
14039   bool isPPC64 = Subtarget.isPPC64();
14040   bool isDarwinABI = Subtarget.isDarwinABI();
14041 
14042   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14043       (!isPPC64 && VT != MVT::i32))
14044     report_fatal_error("Invalid register global variable type");
14045 
14046   bool is64Bit = isPPC64 && VT == MVT::i64;
14047   unsigned Reg = StringSwitch<unsigned>(RegName)
14048                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14049                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
14050                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
14051                                   (is64Bit ? PPC::X13 : PPC::R13))
14052                    .Default(0);
14053 
14054   if (Reg)
14055     return Reg;
14056   report_fatal_error("Invalid register name global variable");
14057 }
14058 
14059 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14060   // 32-bit SVR4 ABI access everything as got-indirect.
14061   if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
14062     return true;
14063 
14064   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14065   // If it is small or large code model, module locals are accessed
14066   // indirectly by loading their address from .toc/.got. The difference
14067   // is that for large code model we have ADDISTocHa + LDtocL and for
14068   // small code model we simply have LDtoc.
14069   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14070     return true;
14071 
14072   // JumpTable and BlockAddress are accessed as got-indirect.
14073   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14074     return true;
14075 
14076   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
14077     const GlobalValue *GV = G->getGlobal();
14078     unsigned char GVFlags = Subtarget.classifyGlobalReference(GV);
14079     // The NLP flag indicates that a global access has to use an
14080     // extra indirection.
14081     if (GVFlags & PPCII::MO_NLP_FLAG)
14082       return true;
14083   }
14084 
14085   return false;
14086 }
14087 
14088 bool
14089 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14090   // The PowerPC target isn't yet aware of offsets.
14091   return false;
14092 }
14093 
14094 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14095                                            const CallInst &I,
14096                                            MachineFunction &MF,
14097                                            unsigned Intrinsic) const {
14098   switch (Intrinsic) {
14099   case Intrinsic::ppc_qpx_qvlfd:
14100   case Intrinsic::ppc_qpx_qvlfs:
14101   case Intrinsic::ppc_qpx_qvlfcd:
14102   case Intrinsic::ppc_qpx_qvlfcs:
14103   case Intrinsic::ppc_qpx_qvlfiwa:
14104   case Intrinsic::ppc_qpx_qvlfiwz:
14105   case Intrinsic::ppc_altivec_lvx:
14106   case Intrinsic::ppc_altivec_lvxl:
14107   case Intrinsic::ppc_altivec_lvebx:
14108   case Intrinsic::ppc_altivec_lvehx:
14109   case Intrinsic::ppc_altivec_lvewx:
14110   case Intrinsic::ppc_vsx_lxvd2x:
14111   case Intrinsic::ppc_vsx_lxvw4x: {
14112     EVT VT;
14113     switch (Intrinsic) {
14114     case Intrinsic::ppc_altivec_lvebx:
14115       VT = MVT::i8;
14116       break;
14117     case Intrinsic::ppc_altivec_lvehx:
14118       VT = MVT::i16;
14119       break;
14120     case Intrinsic::ppc_altivec_lvewx:
14121       VT = MVT::i32;
14122       break;
14123     case Intrinsic::ppc_vsx_lxvd2x:
14124       VT = MVT::v2f64;
14125       break;
14126     case Intrinsic::ppc_qpx_qvlfd:
14127       VT = MVT::v4f64;
14128       break;
14129     case Intrinsic::ppc_qpx_qvlfs:
14130       VT = MVT::v4f32;
14131       break;
14132     case Intrinsic::ppc_qpx_qvlfcd:
14133       VT = MVT::v2f64;
14134       break;
14135     case Intrinsic::ppc_qpx_qvlfcs:
14136       VT = MVT::v2f32;
14137       break;
14138     default:
14139       VT = MVT::v4i32;
14140       break;
14141     }
14142 
14143     Info.opc = ISD::INTRINSIC_W_CHAIN;
14144     Info.memVT = VT;
14145     Info.ptrVal = I.getArgOperand(0);
14146     Info.offset = -VT.getStoreSize()+1;
14147     Info.size = 2*VT.getStoreSize()-1;
14148     Info.align = 1;
14149     Info.flags = MachineMemOperand::MOLoad;
14150     return true;
14151   }
14152   case Intrinsic::ppc_qpx_qvlfda:
14153   case Intrinsic::ppc_qpx_qvlfsa:
14154   case Intrinsic::ppc_qpx_qvlfcda:
14155   case Intrinsic::ppc_qpx_qvlfcsa:
14156   case Intrinsic::ppc_qpx_qvlfiwaa:
14157   case Intrinsic::ppc_qpx_qvlfiwza: {
14158     EVT VT;
14159     switch (Intrinsic) {
14160     case Intrinsic::ppc_qpx_qvlfda:
14161       VT = MVT::v4f64;
14162       break;
14163     case Intrinsic::ppc_qpx_qvlfsa:
14164       VT = MVT::v4f32;
14165       break;
14166     case Intrinsic::ppc_qpx_qvlfcda:
14167       VT = MVT::v2f64;
14168       break;
14169     case Intrinsic::ppc_qpx_qvlfcsa:
14170       VT = MVT::v2f32;
14171       break;
14172     default:
14173       VT = MVT::v4i32;
14174       break;
14175     }
14176 
14177     Info.opc = ISD::INTRINSIC_W_CHAIN;
14178     Info.memVT = VT;
14179     Info.ptrVal = I.getArgOperand(0);
14180     Info.offset = 0;
14181     Info.size = VT.getStoreSize();
14182     Info.align = 1;
14183     Info.flags = MachineMemOperand::MOLoad;
14184     return true;
14185   }
14186   case Intrinsic::ppc_qpx_qvstfd:
14187   case Intrinsic::ppc_qpx_qvstfs:
14188   case Intrinsic::ppc_qpx_qvstfcd:
14189   case Intrinsic::ppc_qpx_qvstfcs:
14190   case Intrinsic::ppc_qpx_qvstfiw:
14191   case Intrinsic::ppc_altivec_stvx:
14192   case Intrinsic::ppc_altivec_stvxl:
14193   case Intrinsic::ppc_altivec_stvebx:
14194   case Intrinsic::ppc_altivec_stvehx:
14195   case Intrinsic::ppc_altivec_stvewx:
14196   case Intrinsic::ppc_vsx_stxvd2x:
14197   case Intrinsic::ppc_vsx_stxvw4x: {
14198     EVT VT;
14199     switch (Intrinsic) {
14200     case Intrinsic::ppc_altivec_stvebx:
14201       VT = MVT::i8;
14202       break;
14203     case Intrinsic::ppc_altivec_stvehx:
14204       VT = MVT::i16;
14205       break;
14206     case Intrinsic::ppc_altivec_stvewx:
14207       VT = MVT::i32;
14208       break;
14209     case Intrinsic::ppc_vsx_stxvd2x:
14210       VT = MVT::v2f64;
14211       break;
14212     case Intrinsic::ppc_qpx_qvstfd:
14213       VT = MVT::v4f64;
14214       break;
14215     case Intrinsic::ppc_qpx_qvstfs:
14216       VT = MVT::v4f32;
14217       break;
14218     case Intrinsic::ppc_qpx_qvstfcd:
14219       VT = MVT::v2f64;
14220       break;
14221     case Intrinsic::ppc_qpx_qvstfcs:
14222       VT = MVT::v2f32;
14223       break;
14224     default:
14225       VT = MVT::v4i32;
14226       break;
14227     }
14228 
14229     Info.opc = ISD::INTRINSIC_VOID;
14230     Info.memVT = VT;
14231     Info.ptrVal = I.getArgOperand(1);
14232     Info.offset = -VT.getStoreSize()+1;
14233     Info.size = 2*VT.getStoreSize()-1;
14234     Info.align = 1;
14235     Info.flags = MachineMemOperand::MOStore;
14236     return true;
14237   }
14238   case Intrinsic::ppc_qpx_qvstfda:
14239   case Intrinsic::ppc_qpx_qvstfsa:
14240   case Intrinsic::ppc_qpx_qvstfcda:
14241   case Intrinsic::ppc_qpx_qvstfcsa:
14242   case Intrinsic::ppc_qpx_qvstfiwa: {
14243     EVT VT;
14244     switch (Intrinsic) {
14245     case Intrinsic::ppc_qpx_qvstfda:
14246       VT = MVT::v4f64;
14247       break;
14248     case Intrinsic::ppc_qpx_qvstfsa:
14249       VT = MVT::v4f32;
14250       break;
14251     case Intrinsic::ppc_qpx_qvstfcda:
14252       VT = MVT::v2f64;
14253       break;
14254     case Intrinsic::ppc_qpx_qvstfcsa:
14255       VT = MVT::v2f32;
14256       break;
14257     default:
14258       VT = MVT::v4i32;
14259       break;
14260     }
14261 
14262     Info.opc = ISD::INTRINSIC_VOID;
14263     Info.memVT = VT;
14264     Info.ptrVal = I.getArgOperand(1);
14265     Info.offset = 0;
14266     Info.size = VT.getStoreSize();
14267     Info.align = 1;
14268     Info.flags = MachineMemOperand::MOStore;
14269     return true;
14270   }
14271   default:
14272     break;
14273   }
14274 
14275   return false;
14276 }
14277 
14278 /// getOptimalMemOpType - Returns the target specific optimal type for load
14279 /// and store operations as a result of memset, memcpy, and memmove
14280 /// lowering. If DstAlign is zero that means it's safe to destination
14281 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14282 /// means there isn't a need to check it against alignment requirement,
14283 /// probably because the source does not need to be loaded. If 'IsMemset' is
14284 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14285 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14286 /// source is constant so it does not need to be loaded.
14287 /// It returns EVT::Other if the type should be determined using generic
14288 /// target-independent logic.
14289 EVT PPCTargetLowering::getOptimalMemOpType(
14290     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14291     bool ZeroMemset, bool MemcpyStrSrc,
14292     const AttributeList &FuncAttributes) const {
14293   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
14294     // When expanding a memset, require at least two QPX instructions to cover
14295     // the cost of loading the value to be stored from the constant pool.
14296     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
14297        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
14298         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14299       return MVT::v4f64;
14300     }
14301 
14302     // We should use Altivec/VSX loads and stores when available. For unaligned
14303     // addresses, unaligned VSX loads are only fast starting with the P8.
14304     if (Subtarget.hasAltivec() && Size >= 16 &&
14305         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
14306          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
14307       return MVT::v4i32;
14308   }
14309 
14310   if (Subtarget.isPPC64()) {
14311     return MVT::i64;
14312   }
14313 
14314   return MVT::i32;
14315 }
14316 
14317 /// Returns true if it is beneficial to convert a load of a constant
14318 /// to just the constant itself.
14319 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14320                                                           Type *Ty) const {
14321   assert(Ty->isIntegerTy());
14322 
14323   unsigned BitSize = Ty->getPrimitiveSizeInBits();
14324   return !(BitSize == 0 || BitSize > 64);
14325 }
14326 
14327 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14328   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14329     return false;
14330   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14331   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14332   return NumBits1 == 64 && NumBits2 == 32;
14333 }
14334 
14335 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14336   if (!VT1.isInteger() || !VT2.isInteger())
14337     return false;
14338   unsigned NumBits1 = VT1.getSizeInBits();
14339   unsigned NumBits2 = VT2.getSizeInBits();
14340   return NumBits1 == 64 && NumBits2 == 32;
14341 }
14342 
14343 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14344   // Generally speaking, zexts are not free, but they are free when they can be
14345   // folded with other operations.
14346   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
14347     EVT MemVT = LD->getMemoryVT();
14348     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
14349          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
14350         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
14351          LD->getExtensionType() == ISD::ZEXTLOAD))
14352       return true;
14353   }
14354 
14355   // FIXME: Add other cases...
14356   //  - 32-bit shifts with a zext to i64
14357   //  - zext after ctlz, bswap, etc.
14358   //  - zext after and by a constant mask
14359 
14360   return TargetLowering::isZExtFree(Val, VT2);
14361 }
14362 
14363 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
14364   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
14365          "invalid fpext types");
14366   // Extending to float128 is not free.
14367   if (DestVT == MVT::f128)
14368     return false;
14369   return true;
14370 }
14371 
14372 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14373   return isInt<16>(Imm) || isUInt<16>(Imm);
14374 }
14375 
14376 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14377   return isInt<16>(Imm) || isUInt<16>(Imm);
14378 }
14379 
14380 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
14381                                                        unsigned,
14382                                                        unsigned,
14383                                                        bool *Fast) const {
14384   if (DisablePPCUnaligned)
14385     return false;
14386 
14387   // PowerPC supports unaligned memory access for simple non-vector types.
14388   // Although accessing unaligned addresses is not as efficient as accessing
14389   // aligned addresses, it is generally more efficient than manual expansion,
14390   // and generally only traps for software emulation when crossing page
14391   // boundaries.
14392 
14393   if (!VT.isSimple())
14394     return false;
14395 
14396   if (VT.getSimpleVT().isVector()) {
14397     if (Subtarget.hasVSX()) {
14398       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
14399           VT != MVT::v4f32 && VT != MVT::v4i32)
14400         return false;
14401     } else {
14402       return false;
14403     }
14404   }
14405 
14406   if (VT == MVT::ppcf128)
14407     return false;
14408 
14409   if (Fast)
14410     *Fast = true;
14411 
14412   return true;
14413 }
14414 
14415 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14416   VT = VT.getScalarType();
14417 
14418   if (!VT.isSimple())
14419     return false;
14420 
14421   switch (VT.getSimpleVT().SimpleTy) {
14422   case MVT::f32:
14423   case MVT::f64:
14424     return true;
14425   case MVT::f128:
14426     return (EnableQuadPrecision && Subtarget.hasP9Vector());
14427   default:
14428     break;
14429   }
14430 
14431   return false;
14432 }
14433 
14434 const MCPhysReg *
14435 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
14436   // LR is a callee-save register, but we must treat it as clobbered by any call
14437   // site. Hence we include LR in the scratch registers, which are in turn added
14438   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
14439   // to CTR, which is used by any indirect call.
14440   static const MCPhysReg ScratchRegs[] = {
14441     PPC::X12, PPC::LR8, PPC::CTR8, 0
14442   };
14443 
14444   return ScratchRegs;
14445 }
14446 
14447 unsigned PPCTargetLowering::getExceptionPointerRegister(
14448     const Constant *PersonalityFn) const {
14449   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
14450 }
14451 
14452 unsigned PPCTargetLowering::getExceptionSelectorRegister(
14453     const Constant *PersonalityFn) const {
14454   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
14455 }
14456 
14457 bool
14458 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
14459                      EVT VT , unsigned DefinedValues) const {
14460   if (VT == MVT::v2i64)
14461     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
14462 
14463   if (Subtarget.hasVSX() || Subtarget.hasQPX())
14464     return true;
14465 
14466   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
14467 }
14468 
14469 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
14470   if (DisableILPPref || Subtarget.enableMachineScheduler())
14471     return TargetLowering::getSchedulingPreference(N);
14472 
14473   return Sched::ILP;
14474 }
14475 
14476 // Create a fast isel object.
14477 FastISel *
14478 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
14479                                   const TargetLibraryInfo *LibInfo) const {
14480   return PPC::createFastISel(FuncInfo, LibInfo);
14481 }
14482 
14483 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14484   if (Subtarget.isDarwinABI()) return;
14485   if (!Subtarget.isPPC64()) return;
14486 
14487   // Update IsSplitCSR in PPCFunctionInfo
14488   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
14489   PFI->setIsSplitCSR(true);
14490 }
14491 
14492 void PPCTargetLowering::insertCopiesSplitCSR(
14493   MachineBasicBlock *Entry,
14494   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14495   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
14496   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14497   if (!IStart)
14498     return;
14499 
14500   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14501   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14502   MachineBasicBlock::iterator MBBI = Entry->begin();
14503   for (const MCPhysReg *I = IStart; *I; ++I) {
14504     const TargetRegisterClass *RC = nullptr;
14505     if (PPC::G8RCRegClass.contains(*I))
14506       RC = &PPC::G8RCRegClass;
14507     else if (PPC::F8RCRegClass.contains(*I))
14508       RC = &PPC::F8RCRegClass;
14509     else if (PPC::CRRCRegClass.contains(*I))
14510       RC = &PPC::CRRCRegClass;
14511     else if (PPC::VRRCRegClass.contains(*I))
14512       RC = &PPC::VRRCRegClass;
14513     else
14514       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14515 
14516     unsigned NewVR = MRI->createVirtualRegister(RC);
14517     // Create copy from CSR to a virtual register.
14518     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14519     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14520     // nounwind. If we want to generalize this later, we may need to emit
14521     // CFI pseudo-instructions.
14522     assert(Entry->getParent()->getFunction().hasFnAttribute(
14523              Attribute::NoUnwind) &&
14524            "Function should be nounwind in insertCopiesSplitCSR!");
14525     Entry->addLiveIn(*I);
14526     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14527       .addReg(*I);
14528 
14529     // Insert the copy-back instructions right before the terminator.
14530     for (auto *Exit : Exits)
14531       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14532               TII->get(TargetOpcode::COPY), *I)
14533         .addReg(NewVR);
14534   }
14535 }
14536 
14537 // Override to enable LOAD_STACK_GUARD lowering on Linux.
14538 bool PPCTargetLowering::useLoadStackGuardNode() const {
14539   if (!Subtarget.isTargetLinux())
14540     return TargetLowering::useLoadStackGuardNode();
14541   return true;
14542 }
14543 
14544 // Override to disable global variable loading on Linux.
14545 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
14546   if (!Subtarget.isTargetLinux())
14547     return TargetLowering::insertSSPDeclarations(M);
14548 }
14549 
14550 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
14551                                      bool ForCodeSize) const {
14552   if (!VT.isSimple() || !Subtarget.hasVSX())
14553     return false;
14554 
14555   switch(VT.getSimpleVT().SimpleTy) {
14556   default:
14557     // For FP types that are currently not supported by PPC backend, return
14558     // false. Examples: f16, f80.
14559     return false;
14560   case MVT::f32:
14561   case MVT::f64:
14562   case MVT::ppcf128:
14563     return Imm.isPosZero();
14564   }
14565 }
14566 
14567 // For vector shift operation op, fold
14568 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
14569 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
14570                                   SelectionDAG &DAG) {
14571   SDValue N0 = N->getOperand(0);
14572   SDValue N1 = N->getOperand(1);
14573   EVT VT = N0.getValueType();
14574   unsigned OpSizeInBits = VT.getScalarSizeInBits();
14575   unsigned Opcode = N->getOpcode();
14576   unsigned TargetOpcode;
14577 
14578   switch (Opcode) {
14579   default:
14580     llvm_unreachable("Unexpected shift operation");
14581   case ISD::SHL:
14582     TargetOpcode = PPCISD::SHL;
14583     break;
14584   case ISD::SRL:
14585     TargetOpcode = PPCISD::SRL;
14586     break;
14587   case ISD::SRA:
14588     TargetOpcode = PPCISD::SRA;
14589     break;
14590   }
14591 
14592   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
14593       N1->getOpcode() == ISD::AND)
14594     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
14595       if (Mask->getZExtValue() == OpSizeInBits - 1)
14596         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
14597 
14598   return SDValue();
14599 }
14600 
14601 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
14602   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14603     return Value;
14604 
14605   SDValue N0 = N->getOperand(0);
14606   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
14607   if (!Subtarget.isISA3_0() ||
14608       N0.getOpcode() != ISD::SIGN_EXTEND ||
14609       N0.getOperand(0).getValueType() != MVT::i32 ||
14610       CN1 == nullptr || N->getValueType(0) != MVT::i64)
14611     return SDValue();
14612 
14613   // We can't save an operation here if the value is already extended, and
14614   // the existing shift is easier to combine.
14615   SDValue ExtsSrc = N0.getOperand(0);
14616   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
14617       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
14618     return SDValue();
14619 
14620   SDLoc DL(N0);
14621   SDValue ShiftBy = SDValue(CN1, 0);
14622   // We want the shift amount to be i32 on the extswli, but the shift could
14623   // have an i64.
14624   if (ShiftBy.getValueType() == MVT::i64)
14625     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
14626 
14627   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
14628                          ShiftBy);
14629 }
14630 
14631 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
14632   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14633     return Value;
14634 
14635   return SDValue();
14636 }
14637 
14638 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
14639   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14640     return Value;
14641 
14642   return SDValue();
14643 }
14644 
14645 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
14646 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
14647 // When C is zero, the equation (addi Z, -C) can be simplified to Z
14648 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
14649 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
14650                                  const PPCSubtarget &Subtarget) {
14651   if (!Subtarget.isPPC64())
14652     return SDValue();
14653 
14654   SDValue LHS = N->getOperand(0);
14655   SDValue RHS = N->getOperand(1);
14656 
14657   auto isZextOfCompareWithConstant = [](SDValue Op) {
14658     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
14659         Op.getValueType() != MVT::i64)
14660       return false;
14661 
14662     SDValue Cmp = Op.getOperand(0);
14663     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
14664         Cmp.getOperand(0).getValueType() != MVT::i64)
14665       return false;
14666 
14667     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
14668       int64_t NegConstant = 0 - Constant->getSExtValue();
14669       // Due to the limitations of the addi instruction,
14670       // -C is required to be [-32768, 32767].
14671       return isInt<16>(NegConstant);
14672     }
14673 
14674     return false;
14675   };
14676 
14677   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
14678   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
14679 
14680   // If there is a pattern, canonicalize a zext operand to the RHS.
14681   if (LHSHasPattern && !RHSHasPattern)
14682     std::swap(LHS, RHS);
14683   else if (!LHSHasPattern && !RHSHasPattern)
14684     return SDValue();
14685 
14686   SDLoc DL(N);
14687   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
14688   SDValue Cmp = RHS.getOperand(0);
14689   SDValue Z = Cmp.getOperand(0);
14690   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
14691 
14692   assert(Constant && "Constant Should not be a null pointer.");
14693   int64_t NegConstant = 0 - Constant->getSExtValue();
14694 
14695   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
14696   default: break;
14697   case ISD::SETNE: {
14698     //                                 when C == 0
14699     //                             --> addze X, (addic Z, -1).carry
14700     //                            /
14701     // add X, (zext(setne Z, C))--
14702     //                            \    when -32768 <= -C <= 32767 && C != 0
14703     //                             --> addze X, (addic (addi Z, -C), -1).carry
14704     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14705                               DAG.getConstant(NegConstant, DL, MVT::i64));
14706     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14707     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14708                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
14709     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14710                        SDValue(Addc.getNode(), 1));
14711     }
14712   case ISD::SETEQ: {
14713     //                                 when C == 0
14714     //                             --> addze X, (subfic Z, 0).carry
14715     //                            /
14716     // add X, (zext(sete  Z, C))--
14717     //                            \    when -32768 <= -C <= 32767 && C != 0
14718     //                             --> addze X, (subfic (addi Z, -C), 0).carry
14719     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14720                               DAG.getConstant(NegConstant, DL, MVT::i64));
14721     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14722     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14723                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
14724     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14725                        SDValue(Subc.getNode(), 1));
14726     }
14727   }
14728 
14729   return SDValue();
14730 }
14731 
14732 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
14733   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
14734     return Value;
14735 
14736   return SDValue();
14737 }
14738 
14739 // Detect TRUNCATE operations on bitcasts of float128 values.
14740 // What we are looking for here is the situtation where we extract a subset
14741 // of bits from a 128 bit float.
14742 // This can be of two forms:
14743 // 1) BITCAST of f128 feeding TRUNCATE
14744 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
14745 // The reason this is required is because we do not have a legal i128 type
14746 // and so we want to prevent having to store the f128 and then reload part
14747 // of it.
14748 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
14749                                            DAGCombinerInfo &DCI) const {
14750   // If we are using CRBits then try that first.
14751   if (Subtarget.useCRBits()) {
14752     // Check if CRBits did anything and return that if it did.
14753     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
14754       return CRTruncValue;
14755   }
14756 
14757   SDLoc dl(N);
14758   SDValue Op0 = N->getOperand(0);
14759 
14760   // Looking for a truncate of i128 to i64.
14761   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
14762     return SDValue();
14763 
14764   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
14765 
14766   // SRL feeding TRUNCATE.
14767   if (Op0.getOpcode() == ISD::SRL) {
14768     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
14769     // The right shift has to be by 64 bits.
14770     if (!ConstNode || ConstNode->getZExtValue() != 64)
14771       return SDValue();
14772 
14773     // Switch the element number to extract.
14774     EltToExtract = EltToExtract ? 0 : 1;
14775     // Update Op0 past the SRL.
14776     Op0 = Op0.getOperand(0);
14777   }
14778 
14779   // BITCAST feeding a TRUNCATE possibly via SRL.
14780   if (Op0.getOpcode() == ISD::BITCAST &&
14781       Op0.getValueType() == MVT::i128 &&
14782       Op0.getOperand(0).getValueType() == MVT::f128) {
14783     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
14784     return DCI.DAG.getNode(
14785         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
14786         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
14787   }
14788   return SDValue();
14789 }
14790 
14791 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
14792   SelectionDAG &DAG = DCI.DAG;
14793 
14794   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
14795   if (!ConstOpOrElement)
14796     return SDValue();
14797 
14798   // An imul is usually smaller than the alternative sequence for legal type.
14799   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
14800       isOperationLegal(ISD::MUL, N->getValueType(0)))
14801     return SDValue();
14802 
14803   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
14804     switch (this->Subtarget.getDarwinDirective()) {
14805     default:
14806       // TODO: enhance the condition for subtarget before pwr8
14807       return false;
14808     case PPC::DIR_PWR8:
14809       //  type        mul     add    shl
14810       // scalar        4       1      1
14811       // vector        7       2      2
14812       return true;
14813     case PPC::DIR_PWR9:
14814       //  type        mul     add    shl
14815       // scalar        5       2      2
14816       // vector        7       2      2
14817 
14818       // The cycle RATIO of related operations are showed as a table above.
14819       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
14820       // scalar and vector type. For 2 instrs patterns, add/sub + shl
14821       // are 4, it is always profitable; but for 3 instrs patterns
14822       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
14823       // So we should only do it for vector type.
14824       return IsAddOne && IsNeg ? VT.isVector() : true;
14825     }
14826   };
14827 
14828   EVT VT = N->getValueType(0);
14829   SDLoc DL(N);
14830 
14831   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
14832   bool IsNeg = MulAmt.isNegative();
14833   APInt MulAmtAbs = MulAmt.abs();
14834 
14835   if ((MulAmtAbs - 1).isPowerOf2()) {
14836     // (mul x, 2^N + 1) => (add (shl x, N), x)
14837     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
14838 
14839     if (!IsProfitable(IsNeg, true, VT))
14840       return SDValue();
14841 
14842     SDValue Op0 = N->getOperand(0);
14843     SDValue Op1 =
14844         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14845                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
14846     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
14847 
14848     if (!IsNeg)
14849       return Res;
14850 
14851     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
14852   } else if ((MulAmtAbs + 1).isPowerOf2()) {
14853     // (mul x, 2^N - 1) => (sub (shl x, N), x)
14854     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14855 
14856     if (!IsProfitable(IsNeg, false, VT))
14857       return SDValue();
14858 
14859     SDValue Op0 = N->getOperand(0);
14860     SDValue Op1 =
14861         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14862                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
14863 
14864     if (!IsNeg)
14865       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
14866     else
14867       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
14868 
14869   } else {
14870     return SDValue();
14871   }
14872 }
14873 
14874 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14875   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
14876   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
14877     return false;
14878 
14879   // If not a tail call then no need to proceed.
14880   if (!CI->isTailCall())
14881     return false;
14882 
14883   // If tail calls are disabled for the caller then we are done.
14884   const Function *Caller = CI->getParent()->getParent();
14885   auto Attr = Caller->getFnAttribute("disable-tail-calls");
14886   if (Attr.getValueAsString() == "true")
14887     return false;
14888 
14889   // If sibling calls have been disabled and tail-calls aren't guaranteed
14890   // there is no reason to duplicate.
14891   auto &TM = getTargetMachine();
14892   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
14893     return false;
14894 
14895   // Can't tail call a function called indirectly, or if it has variadic args.
14896   const Function *Callee = CI->getCalledFunction();
14897   if (!Callee || Callee->isVarArg())
14898     return false;
14899 
14900   // Make sure the callee and caller calling conventions are eligible for tco.
14901   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
14902                                            CI->getCallingConv()))
14903       return false;
14904 
14905   // If the function is local then we have a good chance at tail-calling it
14906   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
14907 }
14908 
14909 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
14910   if (!Subtarget.hasVSX())
14911     return false;
14912   if (Subtarget.hasP9Vector() && VT == MVT::f128)
14913     return true;
14914   return VT == MVT::f32 || VT == MVT::f64 ||
14915     VT == MVT::v4f32 || VT == MVT::v2f64;
14916 }
14917 
14918 bool PPCTargetLowering::
14919 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
14920   const Value *Mask = AndI.getOperand(1);
14921   // If the mask is suitable for andi. or andis. we should sink the and.
14922   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
14923     // Can't handle constants wider than 64-bits.
14924     if (CI->getBitWidth() > 64)
14925       return false;
14926     int64_t ConstVal = CI->getZExtValue();
14927     return isUInt<16>(ConstVal) ||
14928       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
14929   }
14930 
14931   // For non-constant masks, we can always use the record-form and.
14932   return true;
14933 }
14934 
14935 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
14936 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
14937 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
14938 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
14939 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
14940 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
14941   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
14942   assert(Subtarget.hasP9Altivec() &&
14943          "Only combine this when P9 altivec supported!");
14944   EVT VT = N->getValueType(0);
14945   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
14946     return SDValue();
14947 
14948   SelectionDAG &DAG = DCI.DAG;
14949   SDLoc dl(N);
14950   if (N->getOperand(0).getOpcode() == ISD::SUB) {
14951     // Even for signed integers, if it's known to be positive (as signed
14952     // integer) due to zero-extended inputs.
14953     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
14954     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
14955     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
14956          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
14957         (SubOpcd1 == ISD::ZERO_EXTEND ||
14958          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
14959       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
14960                          N->getOperand(0)->getOperand(0),
14961                          N->getOperand(0)->getOperand(1),
14962                          DAG.getTargetConstant(0, dl, MVT::i32));
14963     }
14964 
14965     // For type v4i32, it can be optimized with xvnegsp + vabsduw
14966     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
14967         N->getOperand(0).hasOneUse()) {
14968       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
14969                          N->getOperand(0)->getOperand(0),
14970                          N->getOperand(0)->getOperand(1),
14971                          DAG.getTargetConstant(1, dl, MVT::i32));
14972     }
14973   }
14974 
14975   return SDValue();
14976 }
14977 
14978 // For type v4i32/v8ii16/v16i8, transform
14979 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
14980 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
14981 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
14982 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
14983 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
14984                                           DAGCombinerInfo &DCI) const {
14985   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
14986   assert(Subtarget.hasP9Altivec() &&
14987          "Only combine this when P9 altivec supported!");
14988 
14989   SelectionDAG &DAG = DCI.DAG;
14990   SDLoc dl(N);
14991   SDValue Cond = N->getOperand(0);
14992   SDValue TrueOpnd = N->getOperand(1);
14993   SDValue FalseOpnd = N->getOperand(2);
14994   EVT VT = N->getOperand(1).getValueType();
14995 
14996   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
14997       FalseOpnd.getOpcode() != ISD::SUB)
14998     return SDValue();
14999 
15000   // ABSD only available for type v4i32/v8i16/v16i8
15001   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15002     return SDValue();
15003 
15004   // At least to save one more dependent computation
15005   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15006     return SDValue();
15007 
15008   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15009 
15010   // Can only handle unsigned comparison here
15011   switch (CC) {
15012   default:
15013     return SDValue();
15014   case ISD::SETUGT:
15015   case ISD::SETUGE:
15016     break;
15017   case ISD::SETULT:
15018   case ISD::SETULE:
15019     std::swap(TrueOpnd, FalseOpnd);
15020     break;
15021   }
15022 
15023   SDValue CmpOpnd1 = Cond.getOperand(0);
15024   SDValue CmpOpnd2 = Cond.getOperand(1);
15025 
15026   // SETCC CmpOpnd1 CmpOpnd2 cond
15027   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15028   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15029   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15030       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15031       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15032       FalseOpnd.getOperand(1) == CmpOpnd1) {
15033     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15034                        CmpOpnd1, CmpOpnd2,
15035                        DAG.getTargetConstant(0, dl, MVT::i32));
15036   }
15037 
15038   return SDValue();
15039 }
15040