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/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallSite.h"
59 #include "llvm/IR/CallingConv.h"
60 #include "llvm/IR/Constant.h"
61 #include "llvm/IR/Constants.h"
62 #include "llvm/IR/DataLayout.h"
63 #include "llvm/IR/DebugLoc.h"
64 #include "llvm/IR/DerivedTypes.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/GlobalValue.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/IntrinsicsPowerPC.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/Type.h"
73 #include "llvm/IR/Use.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/MC/MCContext.h"
76 #include "llvm/MC/MCExpr.h"
77 #include "llvm/MC/MCRegisterInfo.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
122 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
125 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
126 
127 STATISTIC(NumTailCalls, "Number of tail calls");
128 STATISTIC(NumSiblingCalls, "Number of sibling calls");
129 
130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
131 
132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
133 
134 // FIXME: Remove this once the bug has been fixed!
135 extern cl::opt<bool> ANDIGlueBug;
136 
137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
138                                      const PPCSubtarget &STI)
139     : TargetLowering(TM), Subtarget(STI) {
140   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
141   // arguments are at least 4/8 bytes aligned.
142   bool isPPC64 = Subtarget.isPPC64();
143   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
144 
145   // Set up the register classes.
146   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
147   if (!useSoftFloat()) {
148     if (hasSPE()) {
149       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
150       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
151     } else {
152       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
153       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
154     }
155   }
156 
157   // Match BITREVERSE to customized fast code sequence in the td file.
158   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
159   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
160 
161   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
162   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
163 
164   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
165   for (MVT VT : MVT::integer_valuetypes()) {
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
167     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
168   }
169 
170   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
171 
172   // PowerPC has pre-inc load and store's.
173   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
174   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
175   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
176   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
177   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
178   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
179   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
180   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
181   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
182   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
183   if (!Subtarget.hasSPE()) {
184     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
185     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
186     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
187     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
188   }
189 
190   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
191   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
192   for (MVT VT : ScalarIntVTs) {
193     setOperationAction(ISD::ADDC, VT, Legal);
194     setOperationAction(ISD::ADDE, VT, Legal);
195     setOperationAction(ISD::SUBC, VT, Legal);
196     setOperationAction(ISD::SUBE, VT, Legal);
197   }
198 
199   if (Subtarget.useCRBits()) {
200     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
201 
202     if (isPPC64 || Subtarget.hasFPCVT()) {
203       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
204       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
205                          isPPC64 ? MVT::i64 : MVT::i32);
206       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
207       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
208                         isPPC64 ? MVT::i64 : MVT::i32);
209     } else {
210       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
211       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
212     }
213 
214     // PowerPC does not support direct load/store of condition registers.
215     setOperationAction(ISD::LOAD, MVT::i1, Custom);
216     setOperationAction(ISD::STORE, MVT::i1, Custom);
217 
218     // FIXME: Remove this once the ANDI glue bug is fixed:
219     if (ANDIGlueBug)
220       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
221 
222     for (MVT VT : MVT::integer_valuetypes()) {
223       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
224       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
225       setTruncStoreAction(VT, MVT::i1, Expand);
226     }
227 
228     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
229   }
230 
231   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
232   // PPC (the libcall is not available).
233   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
234   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
235 
236   // We do not currently implement these libm ops for PowerPC.
237   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
238   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
239   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
240   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
241   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
242   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
243 
244   // PowerPC has no SREM/UREM instructions unless we are on P9
245   // On P9 we may use a hardware instruction to compute the remainder.
246   // The instructions are not legalized directly because in the cases where the
247   // result of both the remainder and the division is required it is more
248   // efficient to compute the remainder from the result of the division rather
249   // than use the remainder instruction.
250   if (Subtarget.isISA3_0()) {
251     setOperationAction(ISD::SREM, MVT::i32, Custom);
252     setOperationAction(ISD::UREM, MVT::i32, Custom);
253     setOperationAction(ISD::SREM, MVT::i64, Custom);
254     setOperationAction(ISD::UREM, MVT::i64, Custom);
255   } else {
256     setOperationAction(ISD::SREM, MVT::i32, Expand);
257     setOperationAction(ISD::UREM, MVT::i32, Expand);
258     setOperationAction(ISD::SREM, MVT::i64, Expand);
259     setOperationAction(ISD::UREM, MVT::i64, Expand);
260   }
261 
262   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
263   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
264   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
265   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
266   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
267   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
268   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
269   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
270   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
271 
272   // Handle constrained floating-point operations of scalar.
273   // TODO: Handle SPE specific operation.
274   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
275   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
276   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
277   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
278 
279   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
280   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
281   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
282   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
283 
284   // We don't support sin/cos/sqrt/fmod/pow
285   setOperationAction(ISD::FSIN , MVT::f64, Expand);
286   setOperationAction(ISD::FCOS , MVT::f64, Expand);
287   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
288   setOperationAction(ISD::FREM , MVT::f64, Expand);
289   setOperationAction(ISD::FPOW , MVT::f64, Expand);
290   setOperationAction(ISD::FSIN , MVT::f32, Expand);
291   setOperationAction(ISD::FCOS , MVT::f32, Expand);
292   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
293   setOperationAction(ISD::FREM , MVT::f32, Expand);
294   setOperationAction(ISD::FPOW , MVT::f32, Expand);
295   if (Subtarget.hasSPE()) {
296     setOperationAction(ISD::FMA  , MVT::f64, Expand);
297     setOperationAction(ISD::FMA  , MVT::f32, Expand);
298   } else {
299     setOperationAction(ISD::FMA  , MVT::f64, Legal);
300     setOperationAction(ISD::FMA  , MVT::f32, Legal);
301   }
302 
303   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
304 
305   // If we're enabling GP optimizations, use hardware square root
306   if (!Subtarget.hasFSQRT() &&
307       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
308         Subtarget.hasFRE()))
309     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
310 
311   if (!Subtarget.hasFSQRT() &&
312       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
313         Subtarget.hasFRES()))
314     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
315 
316   if (Subtarget.hasFCPSGN()) {
317     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
318     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
319   } else {
320     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
321     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
322   }
323 
324   if (Subtarget.hasFPRND()) {
325     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
326     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
327     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
328     setOperationAction(ISD::FROUND, MVT::f64, Legal);
329 
330     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
331     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
332     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
333     setOperationAction(ISD::FROUND, MVT::f32, Legal);
334   }
335 
336   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
337   // to speed up scalar BSWAP64.
338   // CTPOP or CTTZ were introduced in P8/P9 respectively
339   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
340   if (Subtarget.hasP9Vector())
341     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
342   else
343     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
344   if (Subtarget.isISA3_0()) {
345     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
346     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
347   } else {
348     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
349     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
350   }
351 
352   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
353     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
354     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
355   } else {
356     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
357     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
358   }
359 
360   // PowerPC does not have ROTR
361   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
362   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
363 
364   if (!Subtarget.useCRBits()) {
365     // PowerPC does not have Select
366     setOperationAction(ISD::SELECT, MVT::i32, Expand);
367     setOperationAction(ISD::SELECT, MVT::i64, Expand);
368     setOperationAction(ISD::SELECT, MVT::f32, Expand);
369     setOperationAction(ISD::SELECT, MVT::f64, Expand);
370   }
371 
372   // PowerPC wants to turn select_cc of FP into fsel when possible.
373   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
374   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
375 
376   // PowerPC wants to optimize integer setcc a bit
377   if (!Subtarget.useCRBits())
378     setOperationAction(ISD::SETCC, MVT::i32, Custom);
379 
380   // PowerPC does not have BRCOND which requires SetCC
381   if (!Subtarget.useCRBits())
382     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
383 
384   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
385 
386   if (Subtarget.hasSPE()) {
387     // SPE has built-in conversions
388     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
389     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
390     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
391   } else {
392     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
393     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
394 
395     // PowerPC does not have [U|S]INT_TO_FP
396     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
397     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
398   }
399 
400   if (Subtarget.hasDirectMove() && isPPC64) {
401     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
402     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
403     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
404     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
405     if (TM.Options.UnsafeFPMath) {
406       setOperationAction(ISD::LRINT, MVT::f64, Legal);
407       setOperationAction(ISD::LRINT, MVT::f32, Legal);
408       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
409       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
410       setOperationAction(ISD::LROUND, MVT::f64, Legal);
411       setOperationAction(ISD::LROUND, MVT::f32, Legal);
412       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
413       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
414     }
415   } else {
416     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
417     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
418     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
419     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
420   }
421 
422   // We cannot sextinreg(i1).  Expand to shifts.
423   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
424 
425   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
426   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
427   // support continuation, user-level threading, and etc.. As a result, no
428   // other SjLj exception interfaces are implemented and please don't build
429   // your own exception handling based on them.
430   // LLVM/Clang supports zero-cost DWARF exception handling.
431   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
432   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
433 
434   // We want to legalize GlobalAddress and ConstantPool nodes into the
435   // appropriate instructions to materialize the address.
436   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
438   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
439   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
440   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
441   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
442   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
443   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
444   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
445   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
446 
447   // TRAP is legal.
448   setOperationAction(ISD::TRAP, MVT::Other, Legal);
449 
450   // TRAMPOLINE is custom lowered.
451   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
452   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
453 
454   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
455   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
456 
457   if (Subtarget.is64BitELFABI()) {
458     // VAARG always uses double-word chunks, so promote anything smaller.
459     setOperationAction(ISD::VAARG, MVT::i1, Promote);
460     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
461     setOperationAction(ISD::VAARG, MVT::i8, Promote);
462     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
463     setOperationAction(ISD::VAARG, MVT::i16, Promote);
464     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
465     setOperationAction(ISD::VAARG, MVT::i32, Promote);
466     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
467     setOperationAction(ISD::VAARG, MVT::Other, Expand);
468   } else if (Subtarget.is32BitELFABI()) {
469     // VAARG is custom lowered with the 32-bit SVR4 ABI.
470     setOperationAction(ISD::VAARG, MVT::Other, Custom);
471     setOperationAction(ISD::VAARG, MVT::i64, Custom);
472   } else
473     setOperationAction(ISD::VAARG, MVT::Other, Expand);
474 
475   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
476   if (Subtarget.is32BitELFABI())
477     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
478   else
479     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
480 
481   // Use the default implementation.
482   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
483   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
484   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
485   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
486   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
487   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
488   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
489   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
490   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
491 
492   // We want to custom lower some of our intrinsics.
493   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
494 
495   // To handle counter-based loop conditions.
496   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
497 
498   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
499   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
500   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
501   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
502 
503   // Comparisons that require checking two conditions.
504   if (Subtarget.hasSPE()) {
505     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
506     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
507     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
508     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
509   }
510   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
511   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
512   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
513   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
514   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
515   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
516   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
517   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
518   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
519   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
520   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
521   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
522 
523   if (Subtarget.has64BitSupport()) {
524     // They also have instructions for converting between i64 and fp.
525     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
526     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
527     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
529     // This is just the low 32 bits of a (signed) fp->i64 conversion.
530     // We cannot do this with Promote because i64 is not a legal type.
531     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
532 
533     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
534       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
535   } else {
536     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
537     if (Subtarget.hasSPE())
538       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
539     else
540       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
541   }
542 
543   // With the instructions enabled under FPCVT, we can do everything.
544   if (Subtarget.hasFPCVT()) {
545     if (Subtarget.has64BitSupport()) {
546       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
547       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
548       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
549       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
550     }
551 
552     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
553     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
554     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
555     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
556   }
557 
558   if (Subtarget.use64BitRegs()) {
559     // 64-bit PowerPC implementations can support i64 types directly
560     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
561     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
562     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
563     // 64-bit PowerPC wants to expand i128 shifts itself.
564     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
565     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
566     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
567   } else {
568     // 32-bit PowerPC wants to expand i64 shifts itself.
569     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
570     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
571     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
572   }
573 
574   if (Subtarget.hasVSX()) {
575     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
576     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
577     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
578     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
579   }
580 
581   if (Subtarget.hasAltivec()) {
582     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
583       setOperationAction(ISD::SADDSAT, VT, Legal);
584       setOperationAction(ISD::SSUBSAT, VT, Legal);
585       setOperationAction(ISD::UADDSAT, VT, Legal);
586       setOperationAction(ISD::USUBSAT, VT, Legal);
587     }
588     // First set operation action for all vector types to expand. Then we
589     // will selectively turn on ones that can be effectively codegen'd.
590     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
591       // add/sub are legal for all supported vector VT's.
592       setOperationAction(ISD::ADD, VT, Legal);
593       setOperationAction(ISD::SUB, VT, Legal);
594 
595       // For v2i64, these are only valid with P8Vector. This is corrected after
596       // the loop.
597       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
598         setOperationAction(ISD::SMAX, VT, Legal);
599         setOperationAction(ISD::SMIN, VT, Legal);
600         setOperationAction(ISD::UMAX, VT, Legal);
601         setOperationAction(ISD::UMIN, VT, Legal);
602       }
603       else {
604         setOperationAction(ISD::SMAX, VT, Expand);
605         setOperationAction(ISD::SMIN, VT, Expand);
606         setOperationAction(ISD::UMAX, VT, Expand);
607         setOperationAction(ISD::UMIN, VT, Expand);
608       }
609 
610       if (Subtarget.hasVSX()) {
611         setOperationAction(ISD::FMAXNUM, VT, Legal);
612         setOperationAction(ISD::FMINNUM, VT, Legal);
613       }
614 
615       // Vector instructions introduced in P8
616       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
617         setOperationAction(ISD::CTPOP, VT, Legal);
618         setOperationAction(ISD::CTLZ, VT, Legal);
619       }
620       else {
621         setOperationAction(ISD::CTPOP, VT, Expand);
622         setOperationAction(ISD::CTLZ, VT, Expand);
623       }
624 
625       // Vector instructions introduced in P9
626       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
627         setOperationAction(ISD::CTTZ, VT, Legal);
628       else
629         setOperationAction(ISD::CTTZ, VT, Expand);
630 
631       // We promote all shuffles to v16i8.
632       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
633       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
634 
635       // We promote all non-typed operations to v4i32.
636       setOperationAction(ISD::AND   , VT, Promote);
637       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
638       setOperationAction(ISD::OR    , VT, Promote);
639       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
640       setOperationAction(ISD::XOR   , VT, Promote);
641       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
642       setOperationAction(ISD::LOAD  , VT, Promote);
643       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
644       setOperationAction(ISD::SELECT, VT, Promote);
645       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
646       setOperationAction(ISD::VSELECT, VT, Legal);
647       setOperationAction(ISD::SELECT_CC, VT, Promote);
648       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
649       setOperationAction(ISD::STORE, VT, Promote);
650       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
651 
652       // No other operations are legal.
653       setOperationAction(ISD::MUL , VT, Expand);
654       setOperationAction(ISD::SDIV, VT, Expand);
655       setOperationAction(ISD::SREM, VT, Expand);
656       setOperationAction(ISD::UDIV, VT, Expand);
657       setOperationAction(ISD::UREM, VT, Expand);
658       setOperationAction(ISD::FDIV, VT, Expand);
659       setOperationAction(ISD::FREM, VT, Expand);
660       setOperationAction(ISD::FNEG, VT, Expand);
661       setOperationAction(ISD::FSQRT, VT, Expand);
662       setOperationAction(ISD::FLOG, VT, Expand);
663       setOperationAction(ISD::FLOG10, VT, Expand);
664       setOperationAction(ISD::FLOG2, VT, Expand);
665       setOperationAction(ISD::FEXP, VT, Expand);
666       setOperationAction(ISD::FEXP2, VT, Expand);
667       setOperationAction(ISD::FSIN, VT, Expand);
668       setOperationAction(ISD::FCOS, VT, Expand);
669       setOperationAction(ISD::FABS, VT, Expand);
670       setOperationAction(ISD::FFLOOR, VT, Expand);
671       setOperationAction(ISD::FCEIL,  VT, Expand);
672       setOperationAction(ISD::FTRUNC, VT, Expand);
673       setOperationAction(ISD::FRINT,  VT, Expand);
674       setOperationAction(ISD::FNEARBYINT, VT, Expand);
675       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
676       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
677       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
678       setOperationAction(ISD::MULHU, VT, Expand);
679       setOperationAction(ISD::MULHS, VT, Expand);
680       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
681       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
682       setOperationAction(ISD::UDIVREM, VT, Expand);
683       setOperationAction(ISD::SDIVREM, VT, Expand);
684       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
685       setOperationAction(ISD::FPOW, VT, Expand);
686       setOperationAction(ISD::BSWAP, VT, Expand);
687       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
688       setOperationAction(ISD::ROTL, VT, Expand);
689       setOperationAction(ISD::ROTR, VT, Expand);
690 
691       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
692         setTruncStoreAction(VT, InnerVT, Expand);
693         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
694         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
695         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
696       }
697     }
698     if (!Subtarget.hasP8Vector()) {
699       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
700       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
701       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
702       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
703     }
704 
705     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
706       setOperationAction(ISD::ABS, VT, Custom);
707 
708     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
709     // with merges, splats, etc.
710     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
711 
712     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
713     // are cheap, so handle them before they get expanded to scalar.
714     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
715     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
716     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
717     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
718     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
719 
720     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
721     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
722     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
723     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
724     setOperationAction(ISD::SELECT, MVT::v4i32,
725                        Subtarget.useCRBits() ? Legal : Expand);
726     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
727     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
728     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
729     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
730     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
731     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
732     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
733     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
734     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
735 
736     // Without hasP8Altivec set, v2i64 SMAX isn't available.
737     // But ABS custom lowering requires SMAX support.
738     if (!Subtarget.hasP8Altivec())
739       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
740 
741     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
742     if (Subtarget.hasAltivec())
743       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
744         setOperationAction(ISD::ROTL, VT, Legal);
745     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
746     if (Subtarget.hasP8Altivec())
747       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
748 
749     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
750     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
751     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
752     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
753 
754     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
755     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
756 
757     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
758       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
759       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
760     }
761 
762     if (Subtarget.hasP8Altivec())
763       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
764     else
765       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
766 
767     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
768     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
769 
770     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
771     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
772 
773     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
774     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
775     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
776     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
777 
778     // Altivec does not contain unordered floating-point compare instructions
779     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
780     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
781     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
782     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
783 
784     if (Subtarget.hasVSX()) {
785       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
786       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
787       if (Subtarget.hasP8Vector()) {
788         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
789         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
790       }
791       if (Subtarget.hasDirectMove() && isPPC64) {
792         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
793         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
794         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
795         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
796         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
797         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
798         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
799         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
800       }
801       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
802 
803       // The nearbyint variants are not allowed to raise the inexact exception
804       // so we can only code-gen them with unsafe math.
805       if (TM.Options.UnsafeFPMath) {
806         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
807         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
808       }
809 
810       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
811       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
812       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
813       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
814       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
815       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
816       setOperationAction(ISD::FROUND, MVT::f64, Legal);
817       setOperationAction(ISD::FRINT, MVT::f64, Legal);
818 
819       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
820       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
821       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
822       setOperationAction(ISD::FROUND, MVT::f32, Legal);
823       setOperationAction(ISD::FRINT, MVT::f32, Legal);
824 
825       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
826       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
827 
828       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 
831       // Share the Altivec comparison restrictions.
832       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
833       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
834       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
835       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
836 
837       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
838       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
839 
840       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
841 
842       if (Subtarget.hasP8Vector())
843         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
844 
845       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
846 
847       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
848       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
849       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
850 
851       if (Subtarget.hasP8Altivec()) {
852         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
853         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
854         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
855 
856         // 128 bit shifts can be accomplished via 3 instructions for SHL and
857         // SRL, but not for SRA because of the instructions available:
858         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
859         // doing
860         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
861         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
862         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
863 
864         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
865       }
866       else {
867         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
868         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
869         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
870 
871         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
872 
873         // VSX v2i64 only supports non-arithmetic operations.
874         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
875         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
876       }
877 
878       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
879       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
880       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
881       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
882 
883       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
884 
885       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
886       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
887       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
888       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
889 
890       // Custom handling for partial vectors of integers converted to
891       // floating point. We already have optimal handling for v2i32 through
892       // the DAG combine, so those aren't necessary.
893       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
894       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
895       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
896       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
897       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
898       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
899       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
900       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
901 
902       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
903       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
904       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
905       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
906       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
907       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
908 
909       if (Subtarget.hasDirectMove())
910         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
911       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
912 
913       // Handle constrained floating-point operations of vector.
914       // The predictor is `hasVSX` because altivec instruction has
915       // no exception but VSX vector instruction has.
916       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
917       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
918       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
919       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
920 
921       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
922       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
923       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
924       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
925 
926       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
927     }
928 
929     if (Subtarget.hasP8Altivec()) {
930       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
931       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
932     }
933 
934     if (Subtarget.hasP9Vector()) {
935       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
936       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
937 
938       // 128 bit shifts can be accomplished via 3 instructions for SHL and
939       // SRL, but not for SRA because of the instructions available:
940       // VS{RL} and VS{RL}O.
941       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
942       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
943       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
944 
945       if (EnableQuadPrecision) {
946         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
947         setOperationAction(ISD::FADD, MVT::f128, Legal);
948         setOperationAction(ISD::FSUB, MVT::f128, Legal);
949         setOperationAction(ISD::FDIV, MVT::f128, Legal);
950         setOperationAction(ISD::FMUL, MVT::f128, Legal);
951         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
952         // No extending loads to f128 on PPC.
953         for (MVT FPT : MVT::fp_valuetypes())
954           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
955         setOperationAction(ISD::FMA, MVT::f128, Legal);
956         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
957         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
958         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
959         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
960         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
961         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
962 
963         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
964         setOperationAction(ISD::FRINT, MVT::f128, Legal);
965         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
966         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
967         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
968         setOperationAction(ISD::FROUND, MVT::f128, Legal);
969 
970         setOperationAction(ISD::SELECT, MVT::f128, Expand);
971         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
972         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
973         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
974         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
975         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
976         // No implementation for these ops for PowerPC.
977         setOperationAction(ISD::FSIN , MVT::f128, Expand);
978         setOperationAction(ISD::FCOS , MVT::f128, Expand);
979         setOperationAction(ISD::FPOW, MVT::f128, Expand);
980         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
981         setOperationAction(ISD::FREM, MVT::f128, Expand);
982 
983         // Handle constrained floating-point operations of fp128
984         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
985         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
986         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
987         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
988       }
989       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
990       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
991       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
992       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
993       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
994     }
995 
996     if (Subtarget.hasP9Altivec()) {
997       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
998       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
999 
1000       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1001       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1002       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1003       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1004       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1005       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1006       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1007     }
1008   }
1009 
1010   if (Subtarget.hasQPX()) {
1011     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1012     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1013     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1014     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1015 
1016     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1017     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1018 
1019     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1020     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1021 
1022     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1024 
1025     if (!Subtarget.useCRBits())
1026       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1027     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1028 
1029     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1030     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1031     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1032     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1033     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1034     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1035     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1036 
1037     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1038     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1039 
1040     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1041     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1042 
1043     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1044     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1045     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1046     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1047     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1048     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1049     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1050     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1051     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1052     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1053 
1054     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1055     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1056 
1057     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1058     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1059 
1060     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1061 
1062     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1063     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1064     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1065     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1066 
1067     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1068     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1069 
1070     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1071     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1072 
1073     if (!Subtarget.useCRBits())
1074       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1075     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1076 
1077     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1079     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1080     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1081     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1082     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1083     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1084 
1085     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1086     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1087 
1088     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1089     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1090     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1091     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1092     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1093     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1094     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1095     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1096     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1097     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1098 
1099     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1100     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1101 
1102     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1103     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1104 
1105     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1106 
1107     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1108     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1109     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1110 
1111     if (!Subtarget.useCRBits())
1112       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1113     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1114 
1115     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1116     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1117 
1118     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1119     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1120     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1121     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1122     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1123     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1124     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1125 
1126     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1127     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1128 
1129     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1130 
1131     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1132     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1133     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1134     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1135 
1136     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1137     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1138     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1139     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1140 
1141     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1142     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1143 
1144     // These need to set FE_INEXACT, and so cannot be vectorized here.
1145     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1146     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1147 
1148     if (TM.Options.UnsafeFPMath) {
1149       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1150       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1151 
1152       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1153       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1154     } else {
1155       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1156       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1157 
1158       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1159       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1160     }
1161 
1162     // TODO: Handle constrained floating-point operations of v4f64
1163   }
1164 
1165   if (Subtarget.has64BitSupport())
1166     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1167 
1168   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1169 
1170   if (!isPPC64) {
1171     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1172     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1173   }
1174 
1175   setBooleanContents(ZeroOrOneBooleanContent);
1176 
1177   if (Subtarget.hasAltivec()) {
1178     // Altivec instructions set fields to all zeros or all ones.
1179     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1180   }
1181 
1182   if (!isPPC64) {
1183     // These libcalls are not available in 32-bit.
1184     setLibcallName(RTLIB::SHL_I128, nullptr);
1185     setLibcallName(RTLIB::SRL_I128, nullptr);
1186     setLibcallName(RTLIB::SRA_I128, nullptr);
1187   }
1188 
1189   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1190 
1191   // We have target-specific dag combine patterns for the following nodes:
1192   setTargetDAGCombine(ISD::ADD);
1193   setTargetDAGCombine(ISD::SHL);
1194   setTargetDAGCombine(ISD::SRA);
1195   setTargetDAGCombine(ISD::SRL);
1196   setTargetDAGCombine(ISD::MUL);
1197   setTargetDAGCombine(ISD::SINT_TO_FP);
1198   setTargetDAGCombine(ISD::BUILD_VECTOR);
1199   if (Subtarget.hasFPCVT())
1200     setTargetDAGCombine(ISD::UINT_TO_FP);
1201   setTargetDAGCombine(ISD::LOAD);
1202   setTargetDAGCombine(ISD::STORE);
1203   setTargetDAGCombine(ISD::BR_CC);
1204   if (Subtarget.useCRBits())
1205     setTargetDAGCombine(ISD::BRCOND);
1206   setTargetDAGCombine(ISD::BSWAP);
1207   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1208   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1209   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1210 
1211   setTargetDAGCombine(ISD::SIGN_EXTEND);
1212   setTargetDAGCombine(ISD::ZERO_EXTEND);
1213   setTargetDAGCombine(ISD::ANY_EXTEND);
1214 
1215   setTargetDAGCombine(ISD::TRUNCATE);
1216   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1217 
1218 
1219   if (Subtarget.useCRBits()) {
1220     setTargetDAGCombine(ISD::TRUNCATE);
1221     setTargetDAGCombine(ISD::SETCC);
1222     setTargetDAGCombine(ISD::SELECT_CC);
1223   }
1224 
1225   // Use reciprocal estimates.
1226   if (TM.Options.UnsafeFPMath) {
1227     setTargetDAGCombine(ISD::FDIV);
1228     setTargetDAGCombine(ISD::FSQRT);
1229   }
1230 
1231   if (Subtarget.hasP9Altivec()) {
1232     setTargetDAGCombine(ISD::ABS);
1233     setTargetDAGCombine(ISD::VSELECT);
1234   }
1235 
1236   if (EnableQuadPrecision) {
1237     setLibcallName(RTLIB::LOG_F128, "logf128");
1238     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1239     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1240     setLibcallName(RTLIB::EXP_F128, "expf128");
1241     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1242     setLibcallName(RTLIB::SIN_F128, "sinf128");
1243     setLibcallName(RTLIB::COS_F128, "cosf128");
1244     setLibcallName(RTLIB::POW_F128, "powf128");
1245     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1246     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1247     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1248     setLibcallName(RTLIB::REM_F128, "fmodf128");
1249   }
1250 
1251   // With 32 condition bits, we don't need to sink (and duplicate) compares
1252   // aggressively in CodeGenPrep.
1253   if (Subtarget.useCRBits()) {
1254     setHasMultipleConditionRegisters();
1255     setJumpIsExpensive();
1256   }
1257 
1258   setMinFunctionAlignment(Align(4));
1259 
1260   switch (Subtarget.getCPUDirective()) {
1261   default: break;
1262   case PPC::DIR_970:
1263   case PPC::DIR_A2:
1264   case PPC::DIR_E500:
1265   case PPC::DIR_E500mc:
1266   case PPC::DIR_E5500:
1267   case PPC::DIR_PWR4:
1268   case PPC::DIR_PWR5:
1269   case PPC::DIR_PWR5X:
1270   case PPC::DIR_PWR6:
1271   case PPC::DIR_PWR6X:
1272   case PPC::DIR_PWR7:
1273   case PPC::DIR_PWR8:
1274   case PPC::DIR_PWR9:
1275   case PPC::DIR_PWR_FUTURE:
1276     setPrefLoopAlignment(Align(16));
1277     setPrefFunctionAlignment(Align(16));
1278     break;
1279   }
1280 
1281   if (Subtarget.enableMachineScheduler())
1282     setSchedulingPreference(Sched::Source);
1283   else
1284     setSchedulingPreference(Sched::Hybrid);
1285 
1286   computeRegisterProperties(STI.getRegisterInfo());
1287 
1288   // The Freescale cores do better with aggressive inlining of memcpy and
1289   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1290   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1291       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1292     MaxStoresPerMemset = 32;
1293     MaxStoresPerMemsetOptSize = 16;
1294     MaxStoresPerMemcpy = 32;
1295     MaxStoresPerMemcpyOptSize = 8;
1296     MaxStoresPerMemmove = 32;
1297     MaxStoresPerMemmoveOptSize = 8;
1298   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1299     // The A2 also benefits from (very) aggressive inlining of memcpy and
1300     // friends. The overhead of a the function call, even when warm, can be
1301     // over one hundred cycles.
1302     MaxStoresPerMemset = 128;
1303     MaxStoresPerMemcpy = 128;
1304     MaxStoresPerMemmove = 128;
1305     MaxLoadsPerMemcmp = 128;
1306   } else {
1307     MaxLoadsPerMemcmp = 8;
1308     MaxLoadsPerMemcmpOptSize = 4;
1309   }
1310 }
1311 
1312 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1313 /// the desired ByVal argument alignment.
1314 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1315                              unsigned MaxMaxAlign) {
1316   if (MaxAlign == MaxMaxAlign)
1317     return;
1318   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1319     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1320       MaxAlign = 32;
1321     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1322       MaxAlign = 16;
1323   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1324     unsigned EltAlign = 0;
1325     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1326     if (EltAlign > MaxAlign)
1327       MaxAlign = EltAlign;
1328   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1329     for (auto *EltTy : STy->elements()) {
1330       unsigned EltAlign = 0;
1331       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1332       if (EltAlign > MaxAlign)
1333         MaxAlign = EltAlign;
1334       if (MaxAlign == MaxMaxAlign)
1335         break;
1336     }
1337   }
1338 }
1339 
1340 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1341 /// function arguments in the caller parameter area.
1342 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1343                                                   const DataLayout &DL) const {
1344   // 16byte and wider vectors are passed on 16byte boundary.
1345   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1346   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1347   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1348     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1349   return Align;
1350 }
1351 
1352 bool PPCTargetLowering::useSoftFloat() const {
1353   return Subtarget.useSoftFloat();
1354 }
1355 
1356 bool PPCTargetLowering::hasSPE() const {
1357   return Subtarget.hasSPE();
1358 }
1359 
1360 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1361   return VT.isScalarInteger();
1362 }
1363 
1364 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1365   switch ((PPCISD::NodeType)Opcode) {
1366   case PPCISD::FIRST_NUMBER:    break;
1367   case PPCISD::FSEL:            return "PPCISD::FSEL";
1368   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1369   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1370   case PPCISD::FCFID:           return "PPCISD::FCFID";
1371   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1372   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1373   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1374   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1375   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1376   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1377   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1378   case PPCISD::FP_TO_UINT_IN_VSR:
1379                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1380   case PPCISD::FP_TO_SINT_IN_VSR:
1381                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1382   case PPCISD::FRE:             return "PPCISD::FRE";
1383   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1384   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1385   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1386   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1387   case PPCISD::VPERM:           return "PPCISD::VPERM";
1388   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1389   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1390   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1391   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1392   case PPCISD::CMPB:            return "PPCISD::CMPB";
1393   case PPCISD::Hi:              return "PPCISD::Hi";
1394   case PPCISD::Lo:              return "PPCISD::Lo";
1395   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1396   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1397   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1398   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1399   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1400   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1401   case PPCISD::SRL:             return "PPCISD::SRL";
1402   case PPCISD::SRA:             return "PPCISD::SRA";
1403   case PPCISD::SHL:             return "PPCISD::SHL";
1404   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1405   case PPCISD::CALL:            return "PPCISD::CALL";
1406   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1407   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1408   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1409   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1410   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1411   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1412   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1413   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1414   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1415   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1416   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1417   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1418   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1419   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1420   case PPCISD::ANDI_rec_1_EQ_BIT:
1421     return "PPCISD::ANDI_rec_1_EQ_BIT";
1422   case PPCISD::ANDI_rec_1_GT_BIT:
1423     return "PPCISD::ANDI_rec_1_GT_BIT";
1424   case PPCISD::VCMP:            return "PPCISD::VCMP";
1425   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1426   case PPCISD::LBRX:            return "PPCISD::LBRX";
1427   case PPCISD::STBRX:           return "PPCISD::STBRX";
1428   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1429   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1430   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1431   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1432   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1433   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1434   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1435   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1436   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1437   case PPCISD::ST_VSR_SCAL_INT:
1438                                 return "PPCISD::ST_VSR_SCAL_INT";
1439   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1440   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1441   case PPCISD::BDZ:             return "PPCISD::BDZ";
1442   case PPCISD::MFFS:            return "PPCISD::MFFS";
1443   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1444   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1445   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1446   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1447   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1448   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1449   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1450   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1451   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1452   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1453   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1454   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1455   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1456   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1457   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1458   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1459   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1460   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1461   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1462   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1463   case PPCISD::SC:              return "PPCISD::SC";
1464   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1465   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1466   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1467   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1468   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1469   case PPCISD::VABSD:           return "PPCISD::VABSD";
1470   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1471   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1472   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1473   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1474   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1475   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1476   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1477   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1478   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1479   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1480   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1481   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1482   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1483   }
1484   return nullptr;
1485 }
1486 
1487 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1488                                           EVT VT) const {
1489   if (!VT.isVector())
1490     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1491 
1492   if (Subtarget.hasQPX())
1493     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1494 
1495   return VT.changeVectorElementTypeToInteger();
1496 }
1497 
1498 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1499   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1500   return true;
1501 }
1502 
1503 //===----------------------------------------------------------------------===//
1504 // Node matching predicates, for use by the tblgen matching code.
1505 //===----------------------------------------------------------------------===//
1506 
1507 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1508 static bool isFloatingPointZero(SDValue Op) {
1509   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1510     return CFP->getValueAPF().isZero();
1511   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1512     // Maybe this has already been legalized into the constant pool?
1513     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1514       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1515         return CFP->getValueAPF().isZero();
1516   }
1517   return false;
1518 }
1519 
1520 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1521 /// true if Op is undef or if it matches the specified value.
1522 static bool isConstantOrUndef(int Op, int Val) {
1523   return Op < 0 || Op == Val;
1524 }
1525 
1526 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1527 /// VPKUHUM instruction.
1528 /// The ShuffleKind distinguishes between big-endian operations with
1529 /// two different inputs (0), either-endian operations with two identical
1530 /// inputs (1), and little-endian operations with two different inputs (2).
1531 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1532 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1533                                SelectionDAG &DAG) {
1534   bool IsLE = DAG.getDataLayout().isLittleEndian();
1535   if (ShuffleKind == 0) {
1536     if (IsLE)
1537       return false;
1538     for (unsigned i = 0; i != 16; ++i)
1539       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1540         return false;
1541   } else if (ShuffleKind == 2) {
1542     if (!IsLE)
1543       return false;
1544     for (unsigned i = 0; i != 16; ++i)
1545       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1546         return false;
1547   } else if (ShuffleKind == 1) {
1548     unsigned j = IsLE ? 0 : 1;
1549     for (unsigned i = 0; i != 8; ++i)
1550       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1551           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1552         return false;
1553   }
1554   return true;
1555 }
1556 
1557 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1558 /// VPKUWUM instruction.
1559 /// The ShuffleKind distinguishes between big-endian operations with
1560 /// two different inputs (0), either-endian operations with two identical
1561 /// inputs (1), and little-endian operations with two different inputs (2).
1562 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1563 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1564                                SelectionDAG &DAG) {
1565   bool IsLE = DAG.getDataLayout().isLittleEndian();
1566   if (ShuffleKind == 0) {
1567     if (IsLE)
1568       return false;
1569     for (unsigned i = 0; i != 16; i += 2)
1570       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1571           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1572         return false;
1573   } else if (ShuffleKind == 2) {
1574     if (!IsLE)
1575       return false;
1576     for (unsigned i = 0; i != 16; i += 2)
1577       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1578           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1579         return false;
1580   } else if (ShuffleKind == 1) {
1581     unsigned j = IsLE ? 0 : 2;
1582     for (unsigned i = 0; i != 8; i += 2)
1583       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1584           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1585           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1586           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1587         return false;
1588   }
1589   return true;
1590 }
1591 
1592 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1593 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1594 /// current subtarget.
1595 ///
1596 /// The ShuffleKind distinguishes between big-endian operations with
1597 /// two different inputs (0), either-endian operations with two identical
1598 /// inputs (1), and little-endian operations with two different inputs (2).
1599 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1600 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1601                                SelectionDAG &DAG) {
1602   const PPCSubtarget& Subtarget =
1603       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1604   if (!Subtarget.hasP8Vector())
1605     return false;
1606 
1607   bool IsLE = DAG.getDataLayout().isLittleEndian();
1608   if (ShuffleKind == 0) {
1609     if (IsLE)
1610       return false;
1611     for (unsigned i = 0; i != 16; i += 4)
1612       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1613           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1614           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1615           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1616         return false;
1617   } else if (ShuffleKind == 2) {
1618     if (!IsLE)
1619       return false;
1620     for (unsigned i = 0; i != 16; i += 4)
1621       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1622           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1623           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1624           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1625         return false;
1626   } else if (ShuffleKind == 1) {
1627     unsigned j = IsLE ? 0 : 4;
1628     for (unsigned i = 0; i != 8; i += 4)
1629       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1630           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1631           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1632           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1633           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1634           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1635           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1636           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1637         return false;
1638   }
1639   return true;
1640 }
1641 
1642 /// isVMerge - Common function, used to match vmrg* shuffles.
1643 ///
1644 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1645                      unsigned LHSStart, unsigned RHSStart) {
1646   if (N->getValueType(0) != MVT::v16i8)
1647     return false;
1648   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1649          "Unsupported merge size!");
1650 
1651   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1652     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1653       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1654                              LHSStart+j+i*UnitSize) ||
1655           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1656                              RHSStart+j+i*UnitSize))
1657         return false;
1658     }
1659   return true;
1660 }
1661 
1662 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1663 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1664 /// The ShuffleKind distinguishes between big-endian merges with two
1665 /// different inputs (0), either-endian merges with two identical inputs (1),
1666 /// and little-endian merges with two different inputs (2).  For the latter,
1667 /// the input operands are swapped (see PPCInstrAltivec.td).
1668 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1669                              unsigned ShuffleKind, SelectionDAG &DAG) {
1670   if (DAG.getDataLayout().isLittleEndian()) {
1671     if (ShuffleKind == 1) // unary
1672       return isVMerge(N, UnitSize, 0, 0);
1673     else if (ShuffleKind == 2) // swapped
1674       return isVMerge(N, UnitSize, 0, 16);
1675     else
1676       return false;
1677   } else {
1678     if (ShuffleKind == 1) // unary
1679       return isVMerge(N, UnitSize, 8, 8);
1680     else if (ShuffleKind == 0) // normal
1681       return isVMerge(N, UnitSize, 8, 24);
1682     else
1683       return false;
1684   }
1685 }
1686 
1687 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1688 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1689 /// The ShuffleKind distinguishes between big-endian merges with two
1690 /// different inputs (0), either-endian merges with two identical inputs (1),
1691 /// and little-endian merges with two different inputs (2).  For the latter,
1692 /// the input operands are swapped (see PPCInstrAltivec.td).
1693 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1694                              unsigned ShuffleKind, SelectionDAG &DAG) {
1695   if (DAG.getDataLayout().isLittleEndian()) {
1696     if (ShuffleKind == 1) // unary
1697       return isVMerge(N, UnitSize, 8, 8);
1698     else if (ShuffleKind == 2) // swapped
1699       return isVMerge(N, UnitSize, 8, 24);
1700     else
1701       return false;
1702   } else {
1703     if (ShuffleKind == 1) // unary
1704       return isVMerge(N, UnitSize, 0, 0);
1705     else if (ShuffleKind == 0) // normal
1706       return isVMerge(N, UnitSize, 0, 16);
1707     else
1708       return false;
1709   }
1710 }
1711 
1712 /**
1713  * Common function used to match vmrgew and vmrgow shuffles
1714  *
1715  * The indexOffset determines whether to look for even or odd words in
1716  * the shuffle mask. This is based on the of the endianness of the target
1717  * machine.
1718  *   - Little Endian:
1719  *     - Use offset of 0 to check for odd elements
1720  *     - Use offset of 4 to check for even elements
1721  *   - Big Endian:
1722  *     - Use offset of 0 to check for even elements
1723  *     - Use offset of 4 to check for odd elements
1724  * A detailed description of the vector element ordering for little endian and
1725  * big endian can be found at
1726  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1727  * Targeting your applications - what little endian and big endian IBM XL C/C++
1728  * compiler differences mean to you
1729  *
1730  * The mask to the shuffle vector instruction specifies the indices of the
1731  * elements from the two input vectors to place in the result. The elements are
1732  * numbered in array-access order, starting with the first vector. These vectors
1733  * are always of type v16i8, thus each vector will contain 16 elements of size
1734  * 8. More info on the shuffle vector can be found in the
1735  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1736  * Language Reference.
1737  *
1738  * The RHSStartValue indicates whether the same input vectors are used (unary)
1739  * or two different input vectors are used, based on the following:
1740  *   - If the instruction uses the same vector for both inputs, the range of the
1741  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1742  *     be 0.
1743  *   - If the instruction has two different vectors then the range of the
1744  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1745  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1746  *     to 31 specify elements in the second vector).
1747  *
1748  * \param[in] N The shuffle vector SD Node to analyze
1749  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1750  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1751  * vector to the shuffle_vector instruction
1752  * \return true iff this shuffle vector represents an even or odd word merge
1753  */
1754 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1755                      unsigned RHSStartValue) {
1756   if (N->getValueType(0) != MVT::v16i8)
1757     return false;
1758 
1759   for (unsigned i = 0; i < 2; ++i)
1760     for (unsigned j = 0; j < 4; ++j)
1761       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1762                              i*RHSStartValue+j+IndexOffset) ||
1763           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1764                              i*RHSStartValue+j+IndexOffset+8))
1765         return false;
1766   return true;
1767 }
1768 
1769 /**
1770  * Determine if the specified shuffle mask is suitable for the vmrgew or
1771  * vmrgow instructions.
1772  *
1773  * \param[in] N The shuffle vector SD Node to analyze
1774  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1775  * \param[in] ShuffleKind Identify the type of merge:
1776  *   - 0 = big-endian merge with two different inputs;
1777  *   - 1 = either-endian merge with two identical inputs;
1778  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1779  *     little-endian merges).
1780  * \param[in] DAG The current SelectionDAG
1781  * \return true iff this shuffle mask
1782  */
1783 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1784                               unsigned ShuffleKind, SelectionDAG &DAG) {
1785   if (DAG.getDataLayout().isLittleEndian()) {
1786     unsigned indexOffset = CheckEven ? 4 : 0;
1787     if (ShuffleKind == 1) // Unary
1788       return isVMerge(N, indexOffset, 0);
1789     else if (ShuffleKind == 2) // swapped
1790       return isVMerge(N, indexOffset, 16);
1791     else
1792       return false;
1793   }
1794   else {
1795     unsigned indexOffset = CheckEven ? 0 : 4;
1796     if (ShuffleKind == 1) // Unary
1797       return isVMerge(N, indexOffset, 0);
1798     else if (ShuffleKind == 0) // Normal
1799       return isVMerge(N, indexOffset, 16);
1800     else
1801       return false;
1802   }
1803   return false;
1804 }
1805 
1806 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1807 /// amount, otherwise return -1.
1808 /// The ShuffleKind distinguishes between big-endian operations with two
1809 /// different inputs (0), either-endian operations with two identical inputs
1810 /// (1), and little-endian operations with two different inputs (2).  For the
1811 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1812 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1813                              SelectionDAG &DAG) {
1814   if (N->getValueType(0) != MVT::v16i8)
1815     return -1;
1816 
1817   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1818 
1819   // Find the first non-undef value in the shuffle mask.
1820   unsigned i;
1821   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1822     /*search*/;
1823 
1824   if (i == 16) return -1;  // all undef.
1825 
1826   // Otherwise, check to see if the rest of the elements are consecutively
1827   // numbered from this value.
1828   unsigned ShiftAmt = SVOp->getMaskElt(i);
1829   if (ShiftAmt < i) return -1;
1830 
1831   ShiftAmt -= i;
1832   bool isLE = DAG.getDataLayout().isLittleEndian();
1833 
1834   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1835     // Check the rest of the elements to see if they are consecutive.
1836     for (++i; i != 16; ++i)
1837       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1838         return -1;
1839   } else if (ShuffleKind == 1) {
1840     // Check the rest of the elements to see if they are consecutive.
1841     for (++i; i != 16; ++i)
1842       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1843         return -1;
1844   } else
1845     return -1;
1846 
1847   if (isLE)
1848     ShiftAmt = 16 - ShiftAmt;
1849 
1850   return ShiftAmt;
1851 }
1852 
1853 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1854 /// specifies a splat of a single element that is suitable for input to
1855 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1856 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1857   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1858          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1859 
1860   // The consecutive indices need to specify an element, not part of two
1861   // different elements.  So abandon ship early if this isn't the case.
1862   if (N->getMaskElt(0) % EltSize != 0)
1863     return false;
1864 
1865   // This is a splat operation if each element of the permute is the same, and
1866   // if the value doesn't reference the second vector.
1867   unsigned ElementBase = N->getMaskElt(0);
1868 
1869   // FIXME: Handle UNDEF elements too!
1870   if (ElementBase >= 16)
1871     return false;
1872 
1873   // Check that the indices are consecutive, in the case of a multi-byte element
1874   // splatted with a v16i8 mask.
1875   for (unsigned i = 1; i != EltSize; ++i)
1876     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1877       return false;
1878 
1879   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1880     if (N->getMaskElt(i) < 0) continue;
1881     for (unsigned j = 0; j != EltSize; ++j)
1882       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1883         return false;
1884   }
1885   return true;
1886 }
1887 
1888 /// Check that the mask is shuffling N byte elements. Within each N byte
1889 /// element of the mask, the indices could be either in increasing or
1890 /// decreasing order as long as they are consecutive.
1891 /// \param[in] N the shuffle vector SD Node to analyze
1892 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1893 /// Word/DoubleWord/QuadWord).
1894 /// \param[in] StepLen the delta indices number among the N byte element, if
1895 /// the mask is in increasing/decreasing order then it is 1/-1.
1896 /// \return true iff the mask is shuffling N byte elements.
1897 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1898                                    int StepLen) {
1899   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1900          "Unexpected element width.");
1901   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1902 
1903   unsigned NumOfElem = 16 / Width;
1904   unsigned MaskVal[16]; //  Width is never greater than 16
1905   for (unsigned i = 0; i < NumOfElem; ++i) {
1906     MaskVal[0] = N->getMaskElt(i * Width);
1907     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1908       return false;
1909     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1910       return false;
1911     }
1912 
1913     for (unsigned int j = 1; j < Width; ++j) {
1914       MaskVal[j] = N->getMaskElt(i * Width + j);
1915       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1916         return false;
1917       }
1918     }
1919   }
1920 
1921   return true;
1922 }
1923 
1924 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1925                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1926   if (!isNByteElemShuffleMask(N, 4, 1))
1927     return false;
1928 
1929   // Now we look at mask elements 0,4,8,12
1930   unsigned M0 = N->getMaskElt(0) / 4;
1931   unsigned M1 = N->getMaskElt(4) / 4;
1932   unsigned M2 = N->getMaskElt(8) / 4;
1933   unsigned M3 = N->getMaskElt(12) / 4;
1934   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1935   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1936 
1937   // Below, let H and L be arbitrary elements of the shuffle mask
1938   // where H is in the range [4,7] and L is in the range [0,3].
1939   // H, 1, 2, 3 or L, 5, 6, 7
1940   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1941       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1942     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1943     InsertAtByte = IsLE ? 12 : 0;
1944     Swap = M0 < 4;
1945     return true;
1946   }
1947   // 0, H, 2, 3 or 4, L, 6, 7
1948   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1949       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1950     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1951     InsertAtByte = IsLE ? 8 : 4;
1952     Swap = M1 < 4;
1953     return true;
1954   }
1955   // 0, 1, H, 3 or 4, 5, L, 7
1956   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1957       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1958     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1959     InsertAtByte = IsLE ? 4 : 8;
1960     Swap = M2 < 4;
1961     return true;
1962   }
1963   // 0, 1, 2, H or 4, 5, 6, L
1964   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1965       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1966     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1967     InsertAtByte = IsLE ? 0 : 12;
1968     Swap = M3 < 4;
1969     return true;
1970   }
1971 
1972   // If both vector operands for the shuffle are the same vector, the mask will
1973   // contain only elements from the first one and the second one will be undef.
1974   if (N->getOperand(1).isUndef()) {
1975     ShiftElts = 0;
1976     Swap = true;
1977     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1978     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1979       InsertAtByte = IsLE ? 12 : 0;
1980       return true;
1981     }
1982     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1983       InsertAtByte = IsLE ? 8 : 4;
1984       return true;
1985     }
1986     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1987       InsertAtByte = IsLE ? 4 : 8;
1988       return true;
1989     }
1990     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1991       InsertAtByte = IsLE ? 0 : 12;
1992       return true;
1993     }
1994   }
1995 
1996   return false;
1997 }
1998 
1999 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2000                                bool &Swap, bool IsLE) {
2001   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2002   // Ensure each byte index of the word is consecutive.
2003   if (!isNByteElemShuffleMask(N, 4, 1))
2004     return false;
2005 
2006   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2007   unsigned M0 = N->getMaskElt(0) / 4;
2008   unsigned M1 = N->getMaskElt(4) / 4;
2009   unsigned M2 = N->getMaskElt(8) / 4;
2010   unsigned M3 = N->getMaskElt(12) / 4;
2011 
2012   // If both vector operands for the shuffle are the same vector, the mask will
2013   // contain only elements from the first one and the second one will be undef.
2014   if (N->getOperand(1).isUndef()) {
2015     assert(M0 < 4 && "Indexing into an undef vector?");
2016     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2017       return false;
2018 
2019     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2020     Swap = false;
2021     return true;
2022   }
2023 
2024   // Ensure each word index of the ShuffleVector Mask is consecutive.
2025   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2026     return false;
2027 
2028   if (IsLE) {
2029     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2030       // Input vectors don't need to be swapped if the leading element
2031       // of the result is one of the 3 left elements of the second vector
2032       // (or if there is no shift to be done at all).
2033       Swap = false;
2034       ShiftElts = (8 - M0) % 8;
2035     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2036       // Input vectors need to be swapped if the leading element
2037       // of the result is one of the 3 left elements of the first vector
2038       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2039       Swap = true;
2040       ShiftElts = (4 - M0) % 4;
2041     }
2042 
2043     return true;
2044   } else {                                          // BE
2045     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2046       // Input vectors don't need to be swapped if the leading element
2047       // of the result is one of the 4 elements of the first vector.
2048       Swap = false;
2049       ShiftElts = M0;
2050     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2051       // Input vectors need to be swapped if the leading element
2052       // of the result is one of the 4 elements of the right vector.
2053       Swap = true;
2054       ShiftElts = M0 - 4;
2055     }
2056 
2057     return true;
2058   }
2059 }
2060 
2061 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2062   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2063 
2064   if (!isNByteElemShuffleMask(N, Width, -1))
2065     return false;
2066 
2067   for (int i = 0; i < 16; i += Width)
2068     if (N->getMaskElt(i) != i + Width - 1)
2069       return false;
2070 
2071   return true;
2072 }
2073 
2074 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2075   return isXXBRShuffleMaskHelper(N, 2);
2076 }
2077 
2078 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2079   return isXXBRShuffleMaskHelper(N, 4);
2080 }
2081 
2082 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2083   return isXXBRShuffleMaskHelper(N, 8);
2084 }
2085 
2086 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2087   return isXXBRShuffleMaskHelper(N, 16);
2088 }
2089 
2090 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2091 /// if the inputs to the instruction should be swapped and set \p DM to the
2092 /// value for the immediate.
2093 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2094 /// AND element 0 of the result comes from the first input (LE) or second input
2095 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2096 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2097 /// mask.
2098 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2099                                bool &Swap, bool IsLE) {
2100   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2101 
2102   // Ensure each byte index of the double word is consecutive.
2103   if (!isNByteElemShuffleMask(N, 8, 1))
2104     return false;
2105 
2106   unsigned M0 = N->getMaskElt(0) / 8;
2107   unsigned M1 = N->getMaskElt(8) / 8;
2108   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2109 
2110   // If both vector operands for the shuffle are the same vector, the mask will
2111   // contain only elements from the first one and the second one will be undef.
2112   if (N->getOperand(1).isUndef()) {
2113     if ((M0 | M1) < 2) {
2114       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2115       Swap = false;
2116       return true;
2117     } else
2118       return false;
2119   }
2120 
2121   if (IsLE) {
2122     if (M0 > 1 && M1 < 2) {
2123       Swap = false;
2124     } else if (M0 < 2 && M1 > 1) {
2125       M0 = (M0 + 2) % 4;
2126       M1 = (M1 + 2) % 4;
2127       Swap = true;
2128     } else
2129       return false;
2130 
2131     // Note: if control flow comes here that means Swap is already set above
2132     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2133     return true;
2134   } else { // BE
2135     if (M0 < 2 && M1 > 1) {
2136       Swap = false;
2137     } else if (M0 > 1 && M1 < 2) {
2138       M0 = (M0 + 2) % 4;
2139       M1 = (M1 + 2) % 4;
2140       Swap = true;
2141     } else
2142       return false;
2143 
2144     // Note: if control flow comes here that means Swap is already set above
2145     DM = (M0 << 1) + (M1 & 1);
2146     return true;
2147   }
2148 }
2149 
2150 
2151 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2152 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2153 /// elements are counted from the left of the vector register).
2154 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2155                                          SelectionDAG &DAG) {
2156   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2157   assert(isSplatShuffleMask(SVOp, EltSize));
2158   if (DAG.getDataLayout().isLittleEndian())
2159     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2160   else
2161     return SVOp->getMaskElt(0) / EltSize;
2162 }
2163 
2164 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2165 /// by using a vspltis[bhw] instruction of the specified element size, return
2166 /// the constant being splatted.  The ByteSize field indicates the number of
2167 /// bytes of each element [124] -> [bhw].
2168 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2169   SDValue OpVal(nullptr, 0);
2170 
2171   // If ByteSize of the splat is bigger than the element size of the
2172   // build_vector, then we have a case where we are checking for a splat where
2173   // multiple elements of the buildvector are folded together into a single
2174   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2175   unsigned EltSize = 16/N->getNumOperands();
2176   if (EltSize < ByteSize) {
2177     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2178     SDValue UniquedVals[4];
2179     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2180 
2181     // See if all of the elements in the buildvector agree across.
2182     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2183       if (N->getOperand(i).isUndef()) continue;
2184       // If the element isn't a constant, bail fully out.
2185       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2186 
2187       if (!UniquedVals[i&(Multiple-1)].getNode())
2188         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2189       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2190         return SDValue();  // no match.
2191     }
2192 
2193     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2194     // either constant or undef values that are identical for each chunk.  See
2195     // if these chunks can form into a larger vspltis*.
2196 
2197     // Check to see if all of the leading entries are either 0 or -1.  If
2198     // neither, then this won't fit into the immediate field.
2199     bool LeadingZero = true;
2200     bool LeadingOnes = true;
2201     for (unsigned i = 0; i != Multiple-1; ++i) {
2202       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2203 
2204       LeadingZero &= isNullConstant(UniquedVals[i]);
2205       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2206     }
2207     // Finally, check the least significant entry.
2208     if (LeadingZero) {
2209       if (!UniquedVals[Multiple-1].getNode())
2210         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2211       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2212       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2213         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2214     }
2215     if (LeadingOnes) {
2216       if (!UniquedVals[Multiple-1].getNode())
2217         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2218       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2219       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2220         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2221     }
2222 
2223     return SDValue();
2224   }
2225 
2226   // Check to see if this buildvec has a single non-undef value in its elements.
2227   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2228     if (N->getOperand(i).isUndef()) continue;
2229     if (!OpVal.getNode())
2230       OpVal = N->getOperand(i);
2231     else if (OpVal != N->getOperand(i))
2232       return SDValue();
2233   }
2234 
2235   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2236 
2237   unsigned ValSizeInBytes = EltSize;
2238   uint64_t Value = 0;
2239   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2240     Value = CN->getZExtValue();
2241   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2242     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2243     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2244   }
2245 
2246   // If the splat value is larger than the element value, then we can never do
2247   // this splat.  The only case that we could fit the replicated bits into our
2248   // immediate field for would be zero, and we prefer to use vxor for it.
2249   if (ValSizeInBytes < ByteSize) return SDValue();
2250 
2251   // If the element value is larger than the splat value, check if it consists
2252   // of a repeated bit pattern of size ByteSize.
2253   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2254     return SDValue();
2255 
2256   // Properly sign extend the value.
2257   int MaskVal = SignExtend32(Value, ByteSize * 8);
2258 
2259   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2260   if (MaskVal == 0) return SDValue();
2261 
2262   // Finally, if this value fits in a 5 bit sext field, return it
2263   if (SignExtend32<5>(MaskVal) == MaskVal)
2264     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2265   return SDValue();
2266 }
2267 
2268 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2269 /// amount, otherwise return -1.
2270 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2271   EVT VT = N->getValueType(0);
2272   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2273     return -1;
2274 
2275   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2276 
2277   // Find the first non-undef value in the shuffle mask.
2278   unsigned i;
2279   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2280     /*search*/;
2281 
2282   if (i == 4) return -1;  // all undef.
2283 
2284   // Otherwise, check to see if the rest of the elements are consecutively
2285   // numbered from this value.
2286   unsigned ShiftAmt = SVOp->getMaskElt(i);
2287   if (ShiftAmt < i) return -1;
2288   ShiftAmt -= i;
2289 
2290   // Check the rest of the elements to see if they are consecutive.
2291   for (++i; i != 4; ++i)
2292     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2293       return -1;
2294 
2295   return ShiftAmt;
2296 }
2297 
2298 //===----------------------------------------------------------------------===//
2299 //  Addressing Mode Selection
2300 //===----------------------------------------------------------------------===//
2301 
2302 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2303 /// or 64-bit immediate, and if the value can be accurately represented as a
2304 /// sign extension from a 16-bit value.  If so, this returns true and the
2305 /// immediate.
2306 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2307   if (!isa<ConstantSDNode>(N))
2308     return false;
2309 
2310   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2311   if (N->getValueType(0) == MVT::i32)
2312     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2313   else
2314     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2315 }
2316 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2317   return isIntS16Immediate(Op.getNode(), Imm);
2318 }
2319 
2320 
2321 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2322 /// be represented as an indexed [r+r] operation.
2323 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2324                                                SDValue &Index,
2325                                                SelectionDAG &DAG) const {
2326   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2327       UI != E; ++UI) {
2328     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2329       if (Memop->getMemoryVT() == MVT::f64) {
2330           Base = N.getOperand(0);
2331           Index = N.getOperand(1);
2332           return true;
2333       }
2334     }
2335   }
2336   return false;
2337 }
2338 
2339 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2340 /// can be represented as an indexed [r+r] operation.  Returns false if it
2341 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2342 /// non-zero and N can be represented by a base register plus a signed 16-bit
2343 /// displacement, make a more precise judgement by checking (displacement % \p
2344 /// EncodingAlignment).
2345 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2346                                             SDValue &Index, SelectionDAG &DAG,
2347                                             unsigned EncodingAlignment) const {
2348   int16_t imm = 0;
2349   if (N.getOpcode() == ISD::ADD) {
2350     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2351     // SPE load/store can only handle 8-bit offsets.
2352     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2353         return true;
2354     if (isIntS16Immediate(N.getOperand(1), imm) &&
2355         (!EncodingAlignment || !(imm % EncodingAlignment)))
2356       return false; // r+i
2357     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2358       return false;    // r+i
2359 
2360     Base = N.getOperand(0);
2361     Index = N.getOperand(1);
2362     return true;
2363   } else if (N.getOpcode() == ISD::OR) {
2364     if (isIntS16Immediate(N.getOperand(1), imm) &&
2365         (!EncodingAlignment || !(imm % EncodingAlignment)))
2366       return false; // r+i can fold it if we can.
2367 
2368     // If this is an or of disjoint bitfields, we can codegen this as an add
2369     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2370     // disjoint.
2371     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2372 
2373     if (LHSKnown.Zero.getBoolValue()) {
2374       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2375       // If all of the bits are known zero on the LHS or RHS, the add won't
2376       // carry.
2377       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2378         Base = N.getOperand(0);
2379         Index = N.getOperand(1);
2380         return true;
2381       }
2382     }
2383   }
2384 
2385   return false;
2386 }
2387 
2388 // If we happen to be doing an i64 load or store into a stack slot that has
2389 // less than a 4-byte alignment, then the frame-index elimination may need to
2390 // use an indexed load or store instruction (because the offset may not be a
2391 // multiple of 4). The extra register needed to hold the offset comes from the
2392 // register scavenger, and it is possible that the scavenger will need to use
2393 // an emergency spill slot. As a result, we need to make sure that a spill slot
2394 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2395 // stack slot.
2396 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2397   // FIXME: This does not handle the LWA case.
2398   if (VT != MVT::i64)
2399     return;
2400 
2401   // NOTE: We'll exclude negative FIs here, which come from argument
2402   // lowering, because there are no known test cases triggering this problem
2403   // using packed structures (or similar). We can remove this exclusion if
2404   // we find such a test case. The reason why this is so test-case driven is
2405   // because this entire 'fixup' is only to prevent crashes (from the
2406   // register scavenger) on not-really-valid inputs. For example, if we have:
2407   //   %a = alloca i1
2408   //   %b = bitcast i1* %a to i64*
2409   //   store i64* a, i64 b
2410   // then the store should really be marked as 'align 1', but is not. If it
2411   // were marked as 'align 1' then the indexed form would have been
2412   // instruction-selected initially, and the problem this 'fixup' is preventing
2413   // won't happen regardless.
2414   if (FrameIdx < 0)
2415     return;
2416 
2417   MachineFunction &MF = DAG.getMachineFunction();
2418   MachineFrameInfo &MFI = MF.getFrameInfo();
2419 
2420   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2421   if (Align >= 4)
2422     return;
2423 
2424   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2425   FuncInfo->setHasNonRISpills();
2426 }
2427 
2428 /// Returns true if the address N can be represented by a base register plus
2429 /// a signed 16-bit displacement [r+imm], and if it is not better
2430 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2431 /// displacements that are multiples of that value.
2432 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2433                                             SDValue &Base,
2434                                             SelectionDAG &DAG,
2435                                             unsigned EncodingAlignment) const {
2436   // FIXME dl should come from parent load or store, not from address
2437   SDLoc dl(N);
2438   // If this can be more profitably realized as r+r, fail.
2439   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2440     return false;
2441 
2442   if (N.getOpcode() == ISD::ADD) {
2443     int16_t imm = 0;
2444     if (isIntS16Immediate(N.getOperand(1), imm) &&
2445         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2446       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2447       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2448         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2449         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2450       } else {
2451         Base = N.getOperand(0);
2452       }
2453       return true; // [r+i]
2454     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2455       // Match LOAD (ADD (X, Lo(G))).
2456       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2457              && "Cannot handle constant offsets yet!");
2458       Disp = N.getOperand(1).getOperand(0);  // The global address.
2459       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2460              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2461              Disp.getOpcode() == ISD::TargetConstantPool ||
2462              Disp.getOpcode() == ISD::TargetJumpTable);
2463       Base = N.getOperand(0);
2464       return true;  // [&g+r]
2465     }
2466   } else if (N.getOpcode() == ISD::OR) {
2467     int16_t imm = 0;
2468     if (isIntS16Immediate(N.getOperand(1), imm) &&
2469         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2470       // If this is an or of disjoint bitfields, we can codegen this as an add
2471       // (for better address arithmetic) if the LHS and RHS of the OR are
2472       // provably disjoint.
2473       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2474 
2475       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2476         // If all of the bits are known zero on the LHS or RHS, the add won't
2477         // carry.
2478         if (FrameIndexSDNode *FI =
2479               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2480           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2481           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2482         } else {
2483           Base = N.getOperand(0);
2484         }
2485         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2486         return true;
2487       }
2488     }
2489   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2490     // Loading from a constant address.
2491 
2492     // If this address fits entirely in a 16-bit sext immediate field, codegen
2493     // this as "d, 0"
2494     int16_t Imm;
2495     if (isIntS16Immediate(CN, Imm) &&
2496         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2497       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2498       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2499                              CN->getValueType(0));
2500       return true;
2501     }
2502 
2503     // Handle 32-bit sext immediates with LIS + addr mode.
2504     if ((CN->getValueType(0) == MVT::i32 ||
2505          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2506         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2507       int Addr = (int)CN->getZExtValue();
2508 
2509       // Otherwise, break this down into an LIS + disp.
2510       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2511 
2512       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2513                                    MVT::i32);
2514       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2515       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2516       return true;
2517     }
2518   }
2519 
2520   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2521   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2522     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2523     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2524   } else
2525     Base = N;
2526   return true;      // [r+0]
2527 }
2528 
2529 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2530 /// represented as an indexed [r+r] operation.
2531 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2532                                                 SDValue &Index,
2533                                                 SelectionDAG &DAG) const {
2534   // Check to see if we can easily represent this as an [r+r] address.  This
2535   // will fail if it thinks that the address is more profitably represented as
2536   // reg+imm, e.g. where imm = 0.
2537   if (SelectAddressRegReg(N, Base, Index, DAG))
2538     return true;
2539 
2540   // If the address is the result of an add, we will utilize the fact that the
2541   // address calculation includes an implicit add.  However, we can reduce
2542   // register pressure if we do not materialize a constant just for use as the
2543   // index register.  We only get rid of the add if it is not an add of a
2544   // value and a 16-bit signed constant and both have a single use.
2545   int16_t imm = 0;
2546   if (N.getOpcode() == ISD::ADD &&
2547       (!isIntS16Immediate(N.getOperand(1), imm) ||
2548        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2549     Base = N.getOperand(0);
2550     Index = N.getOperand(1);
2551     return true;
2552   }
2553 
2554   // Otherwise, do it the hard way, using R0 as the base register.
2555   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2556                          N.getValueType());
2557   Index = N;
2558   return true;
2559 }
2560 
2561 /// Returns true if we should use a direct load into vector instruction
2562 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2563 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2564 
2565   // If there are any other uses other than scalar to vector, then we should
2566   // keep it as a scalar load -> direct move pattern to prevent multiple
2567   // loads.
2568   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2569   if (!LD)
2570     return false;
2571 
2572   EVT MemVT = LD->getMemoryVT();
2573   if (!MemVT.isSimple())
2574     return false;
2575   switch(MemVT.getSimpleVT().SimpleTy) {
2576   case MVT::i64:
2577     break;
2578   case MVT::i32:
2579     if (!ST.hasP8Vector())
2580       return false;
2581     break;
2582   case MVT::i16:
2583   case MVT::i8:
2584     if (!ST.hasP9Vector())
2585       return false;
2586     break;
2587   default:
2588     return false;
2589   }
2590 
2591   SDValue LoadedVal(N, 0);
2592   if (!LoadedVal.hasOneUse())
2593     return false;
2594 
2595   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2596        UI != UE; ++UI)
2597     if (UI.getUse().get().getResNo() == 0 &&
2598         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2599       return false;
2600 
2601   return true;
2602 }
2603 
2604 /// getPreIndexedAddressParts - returns true by value, base pointer and
2605 /// offset pointer and addressing mode by reference if the node's address
2606 /// can be legally represented as pre-indexed load / store address.
2607 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2608                                                   SDValue &Offset,
2609                                                   ISD::MemIndexedMode &AM,
2610                                                   SelectionDAG &DAG) const {
2611   if (DisablePPCPreinc) return false;
2612 
2613   bool isLoad = true;
2614   SDValue Ptr;
2615   EVT VT;
2616   unsigned Alignment;
2617   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2618     Ptr = LD->getBasePtr();
2619     VT = LD->getMemoryVT();
2620     Alignment = LD->getAlignment();
2621   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2622     Ptr = ST->getBasePtr();
2623     VT  = ST->getMemoryVT();
2624     Alignment = ST->getAlignment();
2625     isLoad = false;
2626   } else
2627     return false;
2628 
2629   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2630   // instructions because we can fold these into a more efficient instruction
2631   // instead, (such as LXSD).
2632   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2633     return false;
2634   }
2635 
2636   // PowerPC doesn't have preinc load/store instructions for vectors (except
2637   // for QPX, which does have preinc r+r forms).
2638   if (VT.isVector()) {
2639     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2640       return false;
2641     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2642       AM = ISD::PRE_INC;
2643       return true;
2644     }
2645   }
2646 
2647   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2648     // Common code will reject creating a pre-inc form if the base pointer
2649     // is a frame index, or if N is a store and the base pointer is either
2650     // the same as or a predecessor of the value being stored.  Check for
2651     // those situations here, and try with swapped Base/Offset instead.
2652     bool Swap = false;
2653 
2654     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2655       Swap = true;
2656     else if (!isLoad) {
2657       SDValue Val = cast<StoreSDNode>(N)->getValue();
2658       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2659         Swap = true;
2660     }
2661 
2662     if (Swap)
2663       std::swap(Base, Offset);
2664 
2665     AM = ISD::PRE_INC;
2666     return true;
2667   }
2668 
2669   // LDU/STU can only handle immediates that are a multiple of 4.
2670   if (VT != MVT::i64) {
2671     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2672       return false;
2673   } else {
2674     // LDU/STU need an address with at least 4-byte alignment.
2675     if (Alignment < 4)
2676       return false;
2677 
2678     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2679       return false;
2680   }
2681 
2682   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2683     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2684     // sext i32 to i64 when addr mode is r+i.
2685     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2686         LD->getExtensionType() == ISD::SEXTLOAD &&
2687         isa<ConstantSDNode>(Offset))
2688       return false;
2689   }
2690 
2691   AM = ISD::PRE_INC;
2692   return true;
2693 }
2694 
2695 //===----------------------------------------------------------------------===//
2696 //  LowerOperation implementation
2697 //===----------------------------------------------------------------------===//
2698 
2699 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2700 /// and LoOpFlags to the target MO flags.
2701 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2702                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2703                                const GlobalValue *GV = nullptr) {
2704   HiOpFlags = PPCII::MO_HA;
2705   LoOpFlags = PPCII::MO_LO;
2706 
2707   // Don't use the pic base if not in PIC relocation model.
2708   if (IsPIC) {
2709     HiOpFlags |= PPCII::MO_PIC_FLAG;
2710     LoOpFlags |= PPCII::MO_PIC_FLAG;
2711   }
2712 }
2713 
2714 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2715                              SelectionDAG &DAG) {
2716   SDLoc DL(HiPart);
2717   EVT PtrVT = HiPart.getValueType();
2718   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2719 
2720   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2721   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2722 
2723   // With PIC, the first instruction is actually "GR+hi(&G)".
2724   if (isPIC)
2725     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2726                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2727 
2728   // Generate non-pic code that has direct accesses to the constant pool.
2729   // The address of the global is just (hi(&g)+lo(&g)).
2730   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2731 }
2732 
2733 static void setUsesTOCBasePtr(MachineFunction &MF) {
2734   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2735   FuncInfo->setUsesTOCBasePtr();
2736 }
2737 
2738 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2739   setUsesTOCBasePtr(DAG.getMachineFunction());
2740 }
2741 
2742 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2743                                        SDValue GA) const {
2744   const bool Is64Bit = Subtarget.isPPC64();
2745   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2746   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2747                         : Subtarget.isAIXABI()
2748                               ? DAG.getRegister(PPC::R2, VT)
2749                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2750   SDValue Ops[] = { GA, Reg };
2751   return DAG.getMemIntrinsicNode(
2752       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2753       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2754       MachineMemOperand::MOLoad);
2755 }
2756 
2757 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2758                                              SelectionDAG &DAG) const {
2759   EVT PtrVT = Op.getValueType();
2760   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2761   const Constant *C = CP->getConstVal();
2762 
2763   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2764   // The actual address of the GlobalValue is stored in the TOC.
2765   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2766     setUsesTOCBasePtr(DAG);
2767     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2768     return getTOCEntry(DAG, SDLoc(CP), GA);
2769   }
2770 
2771   unsigned MOHiFlag, MOLoFlag;
2772   bool IsPIC = isPositionIndependent();
2773   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2774 
2775   if (IsPIC && Subtarget.isSVR4ABI()) {
2776     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2777                                            PPCII::MO_PIC_FLAG);
2778     return getTOCEntry(DAG, SDLoc(CP), GA);
2779   }
2780 
2781   SDValue CPIHi =
2782     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2783   SDValue CPILo =
2784     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2785   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2786 }
2787 
2788 // For 64-bit PowerPC, prefer the more compact relative encodings.
2789 // This trades 32 bits per jump table entry for one or two instructions
2790 // on the jump site.
2791 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2792   if (isJumpTableRelative())
2793     return MachineJumpTableInfo::EK_LabelDifference32;
2794 
2795   return TargetLowering::getJumpTableEncoding();
2796 }
2797 
2798 bool PPCTargetLowering::isJumpTableRelative() const {
2799   if (UseAbsoluteJumpTables)
2800     return false;
2801   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2802     return true;
2803   return TargetLowering::isJumpTableRelative();
2804 }
2805 
2806 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2807                                                     SelectionDAG &DAG) const {
2808   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2809     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2810 
2811   switch (getTargetMachine().getCodeModel()) {
2812   case CodeModel::Small:
2813   case CodeModel::Medium:
2814     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2815   default:
2816     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2817                        getPointerTy(DAG.getDataLayout()));
2818   }
2819 }
2820 
2821 const MCExpr *
2822 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2823                                                 unsigned JTI,
2824                                                 MCContext &Ctx) const {
2825   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2826     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2827 
2828   switch (getTargetMachine().getCodeModel()) {
2829   case CodeModel::Small:
2830   case CodeModel::Medium:
2831     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2832   default:
2833     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2834   }
2835 }
2836 
2837 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2838   EVT PtrVT = Op.getValueType();
2839   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2840 
2841   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2842   // The actual address of the GlobalValue is stored in the TOC.
2843   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2844     setUsesTOCBasePtr(DAG);
2845     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2846     return getTOCEntry(DAG, SDLoc(JT), GA);
2847   }
2848 
2849   unsigned MOHiFlag, MOLoFlag;
2850   bool IsPIC = isPositionIndependent();
2851   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2852 
2853   if (IsPIC && Subtarget.isSVR4ABI()) {
2854     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2855                                         PPCII::MO_PIC_FLAG);
2856     return getTOCEntry(DAG, SDLoc(GA), GA);
2857   }
2858 
2859   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2860   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2861   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2862 }
2863 
2864 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2865                                              SelectionDAG &DAG) const {
2866   EVT PtrVT = Op.getValueType();
2867   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2868   const BlockAddress *BA = BASDN->getBlockAddress();
2869 
2870   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2871   // The actual BlockAddress is stored in the TOC.
2872   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2873     setUsesTOCBasePtr(DAG);
2874     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2875     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2876   }
2877 
2878   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2879   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2880     return getTOCEntry(
2881         DAG, SDLoc(BASDN),
2882         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2883 
2884   unsigned MOHiFlag, MOLoFlag;
2885   bool IsPIC = isPositionIndependent();
2886   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2887   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2888   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2889   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2890 }
2891 
2892 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2893                                               SelectionDAG &DAG) const {
2894   // FIXME: TLS addresses currently use medium model code sequences,
2895   // which is the most useful form.  Eventually support for small and
2896   // large models could be added if users need it, at the cost of
2897   // additional complexity.
2898   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2899   if (DAG.getTarget().useEmulatedTLS())
2900     return LowerToTLSEmulatedModel(GA, DAG);
2901 
2902   SDLoc dl(GA);
2903   const GlobalValue *GV = GA->getGlobal();
2904   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2905   bool is64bit = Subtarget.isPPC64();
2906   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2907   PICLevel::Level picLevel = M->getPICLevel();
2908 
2909   const TargetMachine &TM = getTargetMachine();
2910   TLSModel::Model Model = TM.getTLSModel(GV);
2911 
2912   if (Model == TLSModel::LocalExec) {
2913     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2914                                                PPCII::MO_TPREL_HA);
2915     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2916                                                PPCII::MO_TPREL_LO);
2917     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2918                              : DAG.getRegister(PPC::R2, MVT::i32);
2919 
2920     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2921     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2922   }
2923 
2924   if (Model == TLSModel::InitialExec) {
2925     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2926     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2927                                                 PPCII::MO_TLS);
2928     SDValue GOTPtr;
2929     if (is64bit) {
2930       setUsesTOCBasePtr(DAG);
2931       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2932       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2933                            PtrVT, GOTReg, TGA);
2934     } else {
2935       if (!TM.isPositionIndependent())
2936         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2937       else if (picLevel == PICLevel::SmallPIC)
2938         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2939       else
2940         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2941     }
2942     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2943                                    PtrVT, TGA, GOTPtr);
2944     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2945   }
2946 
2947   if (Model == TLSModel::GeneralDynamic) {
2948     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2949     SDValue GOTPtr;
2950     if (is64bit) {
2951       setUsesTOCBasePtr(DAG);
2952       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2953       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2954                                    GOTReg, TGA);
2955     } else {
2956       if (picLevel == PICLevel::SmallPIC)
2957         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2958       else
2959         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2960     }
2961     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2962                        GOTPtr, TGA, TGA);
2963   }
2964 
2965   if (Model == TLSModel::LocalDynamic) {
2966     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2967     SDValue GOTPtr;
2968     if (is64bit) {
2969       setUsesTOCBasePtr(DAG);
2970       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2971       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2972                            GOTReg, TGA);
2973     } else {
2974       if (picLevel == PICLevel::SmallPIC)
2975         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2976       else
2977         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2978     }
2979     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2980                                   PtrVT, GOTPtr, TGA, TGA);
2981     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2982                                       PtrVT, TLSAddr, TGA);
2983     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2984   }
2985 
2986   llvm_unreachable("Unknown TLS model!");
2987 }
2988 
2989 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2990                                               SelectionDAG &DAG) const {
2991   EVT PtrVT = Op.getValueType();
2992   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2993   SDLoc DL(GSDN);
2994   const GlobalValue *GV = GSDN->getGlobal();
2995 
2996   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2997   // The actual address of the GlobalValue is stored in the TOC.
2998   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2999     setUsesTOCBasePtr(DAG);
3000     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3001     return getTOCEntry(DAG, DL, GA);
3002   }
3003 
3004   unsigned MOHiFlag, MOLoFlag;
3005   bool IsPIC = isPositionIndependent();
3006   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3007 
3008   if (IsPIC && Subtarget.isSVR4ABI()) {
3009     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3010                                             GSDN->getOffset(),
3011                                             PPCII::MO_PIC_FLAG);
3012     return getTOCEntry(DAG, DL, GA);
3013   }
3014 
3015   SDValue GAHi =
3016     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3017   SDValue GALo =
3018     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3019 
3020   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3021 }
3022 
3023 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3024   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3025   SDLoc dl(Op);
3026 
3027   if (Op.getValueType() == MVT::v2i64) {
3028     // When the operands themselves are v2i64 values, we need to do something
3029     // special because VSX has no underlying comparison operations for these.
3030     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3031       // Equality can be handled by casting to the legal type for Altivec
3032       // comparisons, everything else needs to be expanded.
3033       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3034         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3035                  DAG.getSetCC(dl, MVT::v4i32,
3036                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3037                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3038                    CC));
3039       }
3040 
3041       return SDValue();
3042     }
3043 
3044     // We handle most of these in the usual way.
3045     return Op;
3046   }
3047 
3048   // If we're comparing for equality to zero, expose the fact that this is
3049   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3050   // fold the new nodes.
3051   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3052     return V;
3053 
3054   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3055     // Leave comparisons against 0 and -1 alone for now, since they're usually
3056     // optimized.  FIXME: revisit this when we can custom lower all setcc
3057     // optimizations.
3058     if (C->isAllOnesValue() || C->isNullValue())
3059       return SDValue();
3060   }
3061 
3062   // If we have an integer seteq/setne, turn it into a compare against zero
3063   // by xor'ing the rhs with the lhs, which is faster than setting a
3064   // condition register, reading it back out, and masking the correct bit.  The
3065   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3066   // the result to other bit-twiddling opportunities.
3067   EVT LHSVT = Op.getOperand(0).getValueType();
3068   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3069     EVT VT = Op.getValueType();
3070     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3071                                 Op.getOperand(1));
3072     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3073   }
3074   return SDValue();
3075 }
3076 
3077 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3078   SDNode *Node = Op.getNode();
3079   EVT VT = Node->getValueType(0);
3080   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3081   SDValue InChain = Node->getOperand(0);
3082   SDValue VAListPtr = Node->getOperand(1);
3083   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3084   SDLoc dl(Node);
3085 
3086   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3087 
3088   // gpr_index
3089   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3090                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3091   InChain = GprIndex.getValue(1);
3092 
3093   if (VT == MVT::i64) {
3094     // Check if GprIndex is even
3095     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3096                                  DAG.getConstant(1, dl, MVT::i32));
3097     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3098                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3099     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3100                                           DAG.getConstant(1, dl, MVT::i32));
3101     // Align GprIndex to be even if it isn't
3102     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3103                            GprIndex);
3104   }
3105 
3106   // fpr index is 1 byte after gpr
3107   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3108                                DAG.getConstant(1, dl, MVT::i32));
3109 
3110   // fpr
3111   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3112                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3113   InChain = FprIndex.getValue(1);
3114 
3115   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3116                                        DAG.getConstant(8, dl, MVT::i32));
3117 
3118   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3119                                         DAG.getConstant(4, dl, MVT::i32));
3120 
3121   // areas
3122   SDValue OverflowArea =
3123       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3124   InChain = OverflowArea.getValue(1);
3125 
3126   SDValue RegSaveArea =
3127       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3128   InChain = RegSaveArea.getValue(1);
3129 
3130   // select overflow_area if index > 8
3131   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3132                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3133 
3134   // adjustment constant gpr_index * 4/8
3135   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3136                                     VT.isInteger() ? GprIndex : FprIndex,
3137                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3138                                                     MVT::i32));
3139 
3140   // OurReg = RegSaveArea + RegConstant
3141   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3142                                RegConstant);
3143 
3144   // Floating types are 32 bytes into RegSaveArea
3145   if (VT.isFloatingPoint())
3146     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3147                          DAG.getConstant(32, dl, MVT::i32));
3148 
3149   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3150   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3151                                    VT.isInteger() ? GprIndex : FprIndex,
3152                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3153                                                    MVT::i32));
3154 
3155   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3156                               VT.isInteger() ? VAListPtr : FprPtr,
3157                               MachinePointerInfo(SV), MVT::i8);
3158 
3159   // determine if we should load from reg_save_area or overflow_area
3160   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3161 
3162   // increase overflow_area by 4/8 if gpr/fpr > 8
3163   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3164                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3165                                           dl, MVT::i32));
3166 
3167   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3168                              OverflowAreaPlusN);
3169 
3170   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3171                               MachinePointerInfo(), MVT::i32);
3172 
3173   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3174 }
3175 
3176 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3177   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3178 
3179   // We have to copy the entire va_list struct:
3180   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3181   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3182                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3183                        false, true, false, MachinePointerInfo(),
3184                        MachinePointerInfo());
3185 }
3186 
3187 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3188                                                   SelectionDAG &DAG) const {
3189   if (Subtarget.isAIXABI())
3190     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3191 
3192   return Op.getOperand(0);
3193 }
3194 
3195 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3196                                                 SelectionDAG &DAG) const {
3197   if (Subtarget.isAIXABI())
3198     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3199 
3200   SDValue Chain = Op.getOperand(0);
3201   SDValue Trmp = Op.getOperand(1); // trampoline
3202   SDValue FPtr = Op.getOperand(2); // nested function
3203   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3204   SDLoc dl(Op);
3205 
3206   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3207   bool isPPC64 = (PtrVT == MVT::i64);
3208   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3209 
3210   TargetLowering::ArgListTy Args;
3211   TargetLowering::ArgListEntry Entry;
3212 
3213   Entry.Ty = IntPtrTy;
3214   Entry.Node = Trmp; Args.push_back(Entry);
3215 
3216   // TrampSize == (isPPC64 ? 48 : 40);
3217   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3218                                isPPC64 ? MVT::i64 : MVT::i32);
3219   Args.push_back(Entry);
3220 
3221   Entry.Node = FPtr; Args.push_back(Entry);
3222   Entry.Node = Nest; Args.push_back(Entry);
3223 
3224   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3225   TargetLowering::CallLoweringInfo CLI(DAG);
3226   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3227       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3228       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3229 
3230   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3231   return CallResult.second;
3232 }
3233 
3234 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3235   MachineFunction &MF = DAG.getMachineFunction();
3236   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3237   EVT PtrVT = getPointerTy(MF.getDataLayout());
3238 
3239   SDLoc dl(Op);
3240 
3241   if (Subtarget.isPPC64()) {
3242     // vastart just stores the address of the VarArgsFrameIndex slot into the
3243     // memory location argument.
3244     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3245     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3246     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3247                         MachinePointerInfo(SV));
3248   }
3249 
3250   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3251   // We suppose the given va_list is already allocated.
3252   //
3253   // typedef struct {
3254   //  char gpr;     /* index into the array of 8 GPRs
3255   //                 * stored in the register save area
3256   //                 * gpr=0 corresponds to r3,
3257   //                 * gpr=1 to r4, etc.
3258   //                 */
3259   //  char fpr;     /* index into the array of 8 FPRs
3260   //                 * stored in the register save area
3261   //                 * fpr=0 corresponds to f1,
3262   //                 * fpr=1 to f2, etc.
3263   //                 */
3264   //  char *overflow_arg_area;
3265   //                /* location on stack that holds
3266   //                 * the next overflow argument
3267   //                 */
3268   //  char *reg_save_area;
3269   //               /* where r3:r10 and f1:f8 (if saved)
3270   //                * are stored
3271   //                */
3272   // } va_list[1];
3273 
3274   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3275   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3276   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3277                                             PtrVT);
3278   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3279                                  PtrVT);
3280 
3281   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3282   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3283 
3284   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3285   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3286 
3287   uint64_t FPROffset = 1;
3288   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3289 
3290   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3291 
3292   // Store first byte : number of int regs
3293   SDValue firstStore =
3294       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3295                         MachinePointerInfo(SV), MVT::i8);
3296   uint64_t nextOffset = FPROffset;
3297   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3298                                   ConstFPROffset);
3299 
3300   // Store second byte : number of float regs
3301   SDValue secondStore =
3302       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3303                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3304   nextOffset += StackOffset;
3305   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3306 
3307   // Store second word : arguments given on stack
3308   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3309                                     MachinePointerInfo(SV, nextOffset));
3310   nextOffset += FrameOffset;
3311   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3312 
3313   // Store third word : arguments given in registers
3314   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3315                       MachinePointerInfo(SV, nextOffset));
3316 }
3317 
3318 /// FPR - The set of FP registers that should be allocated for arguments
3319 /// on Darwin and AIX.
3320 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3321                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3322                                 PPC::F11, PPC::F12, PPC::F13};
3323 
3324 /// QFPR - The set of QPX registers that should be allocated for arguments.
3325 static const MCPhysReg QFPR[] = {
3326     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3327     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3328 
3329 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3330 /// the stack.
3331 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3332                                        unsigned PtrByteSize) {
3333   unsigned ArgSize = ArgVT.getStoreSize();
3334   if (Flags.isByVal())
3335     ArgSize = Flags.getByValSize();
3336 
3337   // Round up to multiples of the pointer size, except for array members,
3338   // which are always packed.
3339   if (!Flags.isInConsecutiveRegs())
3340     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3341 
3342   return ArgSize;
3343 }
3344 
3345 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3346 /// on the stack.
3347 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3348                                          ISD::ArgFlagsTy Flags,
3349                                          unsigned PtrByteSize) {
3350   Align Alignment(PtrByteSize);
3351 
3352   // Altivec parameters are padded to a 16 byte boundary.
3353   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3354       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3355       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3356       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3357     Alignment = Align(16);
3358   // QPX vector types stored in double-precision are padded to a 32 byte
3359   // boundary.
3360   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3361     Alignment = Align(32);
3362 
3363   // ByVal parameters are aligned as requested.
3364   if (Flags.isByVal()) {
3365     auto BVAlign = Flags.getNonZeroByValAlign();
3366     if (BVAlign > PtrByteSize) {
3367       if (BVAlign.value() % PtrByteSize != 0)
3368         llvm_unreachable(
3369             "ByVal alignment is not a multiple of the pointer size");
3370 
3371       Alignment = BVAlign;
3372     }
3373   }
3374 
3375   // Array members are always packed to their original alignment.
3376   if (Flags.isInConsecutiveRegs()) {
3377     // If the array member was split into multiple registers, the first
3378     // needs to be aligned to the size of the full type.  (Except for
3379     // ppcf128, which is only aligned as its f64 components.)
3380     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3381       Alignment = Align(OrigVT.getStoreSize());
3382     else
3383       Alignment = Align(ArgVT.getStoreSize());
3384   }
3385 
3386   return Alignment;
3387 }
3388 
3389 /// CalculateStackSlotUsed - Return whether this argument will use its
3390 /// stack slot (instead of being passed in registers).  ArgOffset,
3391 /// AvailableFPRs, and AvailableVRs must hold the current argument
3392 /// position, and will be updated to account for this argument.
3393 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3394                                    ISD::ArgFlagsTy Flags,
3395                                    unsigned PtrByteSize,
3396                                    unsigned LinkageSize,
3397                                    unsigned ParamAreaSize,
3398                                    unsigned &ArgOffset,
3399                                    unsigned &AvailableFPRs,
3400                                    unsigned &AvailableVRs, bool HasQPX) {
3401   bool UseMemory = false;
3402 
3403   // Respect alignment of argument on the stack.
3404   Align Alignment =
3405       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3406   ArgOffset = alignTo(ArgOffset, Alignment);
3407   // If there's no space left in the argument save area, we must
3408   // use memory (this check also catches zero-sized arguments).
3409   if (ArgOffset >= LinkageSize + ParamAreaSize)
3410     UseMemory = true;
3411 
3412   // Allocate argument on the stack.
3413   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3414   if (Flags.isInConsecutiveRegsLast())
3415     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3416   // If we overran the argument save area, we must use memory
3417   // (this check catches arguments passed partially in memory)
3418   if (ArgOffset > LinkageSize + ParamAreaSize)
3419     UseMemory = true;
3420 
3421   // However, if the argument is actually passed in an FPR or a VR,
3422   // we don't use memory after all.
3423   if (!Flags.isByVal()) {
3424     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3425         // QPX registers overlap with the scalar FP registers.
3426         (HasQPX && (ArgVT == MVT::v4f32 ||
3427                     ArgVT == MVT::v4f64 ||
3428                     ArgVT == MVT::v4i1)))
3429       if (AvailableFPRs > 0) {
3430         --AvailableFPRs;
3431         return false;
3432       }
3433     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3434         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3435         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3436         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3437       if (AvailableVRs > 0) {
3438         --AvailableVRs;
3439         return false;
3440       }
3441   }
3442 
3443   return UseMemory;
3444 }
3445 
3446 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3447 /// ensure minimum alignment required for target.
3448 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3449                                      unsigned NumBytes) {
3450   return alignTo(NumBytes, Lowering->getStackAlign());
3451 }
3452 
3453 SDValue PPCTargetLowering::LowerFormalArguments(
3454     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3455     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3456     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3457   if (Subtarget.isAIXABI())
3458     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3459                                     InVals);
3460   if (Subtarget.is64BitELFABI())
3461     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3462                                        InVals);
3463   if (Subtarget.is32BitELFABI())
3464     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3465                                        InVals);
3466 
3467   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3468                                      InVals);
3469 }
3470 
3471 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3472     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3473     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3474     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3475 
3476   // 32-bit SVR4 ABI Stack Frame Layout:
3477   //              +-----------------------------------+
3478   //        +-->  |            Back chain             |
3479   //        |     +-----------------------------------+
3480   //        |     | Floating-point register save area |
3481   //        |     +-----------------------------------+
3482   //        |     |    General register save area     |
3483   //        |     +-----------------------------------+
3484   //        |     |          CR save word             |
3485   //        |     +-----------------------------------+
3486   //        |     |         VRSAVE save word          |
3487   //        |     +-----------------------------------+
3488   //        |     |         Alignment padding         |
3489   //        |     +-----------------------------------+
3490   //        |     |     Vector register save area     |
3491   //        |     +-----------------------------------+
3492   //        |     |       Local variable space        |
3493   //        |     +-----------------------------------+
3494   //        |     |        Parameter list area        |
3495   //        |     +-----------------------------------+
3496   //        |     |           LR save word            |
3497   //        |     +-----------------------------------+
3498   // SP-->  +---  |            Back chain             |
3499   //              +-----------------------------------+
3500   //
3501   // Specifications:
3502   //   System V Application Binary Interface PowerPC Processor Supplement
3503   //   AltiVec Technology Programming Interface Manual
3504 
3505   MachineFunction &MF = DAG.getMachineFunction();
3506   MachineFrameInfo &MFI = MF.getFrameInfo();
3507   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3508 
3509   EVT PtrVT = getPointerTy(MF.getDataLayout());
3510   // Potential tail calls could cause overwriting of argument stack slots.
3511   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3512                        (CallConv == CallingConv::Fast));
3513   unsigned PtrByteSize = 4;
3514 
3515   // Assign locations to all of the incoming arguments.
3516   SmallVector<CCValAssign, 16> ArgLocs;
3517   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3518                  *DAG.getContext());
3519 
3520   // Reserve space for the linkage area on the stack.
3521   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3522   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3523   if (useSoftFloat())
3524     CCInfo.PreAnalyzeFormalArguments(Ins);
3525 
3526   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3527   CCInfo.clearWasPPCF128();
3528 
3529   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3530     CCValAssign &VA = ArgLocs[i];
3531 
3532     // Arguments stored in registers.
3533     if (VA.isRegLoc()) {
3534       const TargetRegisterClass *RC;
3535       EVT ValVT = VA.getValVT();
3536 
3537       switch (ValVT.getSimpleVT().SimpleTy) {
3538         default:
3539           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3540         case MVT::i1:
3541         case MVT::i32:
3542           RC = &PPC::GPRCRegClass;
3543           break;
3544         case MVT::f32:
3545           if (Subtarget.hasP8Vector())
3546             RC = &PPC::VSSRCRegClass;
3547           else if (Subtarget.hasSPE())
3548             RC = &PPC::GPRCRegClass;
3549           else
3550             RC = &PPC::F4RCRegClass;
3551           break;
3552         case MVT::f64:
3553           if (Subtarget.hasVSX())
3554             RC = &PPC::VSFRCRegClass;
3555           else if (Subtarget.hasSPE())
3556             // SPE passes doubles in GPR pairs.
3557             RC = &PPC::GPRCRegClass;
3558           else
3559             RC = &PPC::F8RCRegClass;
3560           break;
3561         case MVT::v16i8:
3562         case MVT::v8i16:
3563         case MVT::v4i32:
3564           RC = &PPC::VRRCRegClass;
3565           break;
3566         case MVT::v4f32:
3567           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3568           break;
3569         case MVT::v2f64:
3570         case MVT::v2i64:
3571           RC = &PPC::VRRCRegClass;
3572           break;
3573         case MVT::v4f64:
3574           RC = &PPC::QFRCRegClass;
3575           break;
3576         case MVT::v4i1:
3577           RC = &PPC::QBRCRegClass;
3578           break;
3579       }
3580 
3581       SDValue ArgValue;
3582       // Transform the arguments stored in physical registers into
3583       // virtual ones.
3584       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3585         assert(i + 1 < e && "No second half of double precision argument");
3586         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3587         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3588         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3589         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3590         if (!Subtarget.isLittleEndian())
3591           std::swap (ArgValueLo, ArgValueHi);
3592         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3593                                ArgValueHi);
3594       } else {
3595         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3596         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3597                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3598         if (ValVT == MVT::i1)
3599           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3600       }
3601 
3602       InVals.push_back(ArgValue);
3603     } else {
3604       // Argument stored in memory.
3605       assert(VA.isMemLoc());
3606 
3607       // Get the extended size of the argument type in stack
3608       unsigned ArgSize = VA.getLocVT().getStoreSize();
3609       // Get the actual size of the argument type
3610       unsigned ObjSize = VA.getValVT().getStoreSize();
3611       unsigned ArgOffset = VA.getLocMemOffset();
3612       // Stack objects in PPC32 are right justified.
3613       ArgOffset += ArgSize - ObjSize;
3614       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3615 
3616       // Create load nodes to retrieve arguments from the stack.
3617       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3618       InVals.push_back(
3619           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3620     }
3621   }
3622 
3623   // Assign locations to all of the incoming aggregate by value arguments.
3624   // Aggregates passed by value are stored in the local variable space of the
3625   // caller's stack frame, right above the parameter list area.
3626   SmallVector<CCValAssign, 16> ByValArgLocs;
3627   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3628                       ByValArgLocs, *DAG.getContext());
3629 
3630   // Reserve stack space for the allocations in CCInfo.
3631   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3632 
3633   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3634 
3635   // Area that is at least reserved in the caller of this function.
3636   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3637   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3638 
3639   // Set the size that is at least reserved in caller of this function.  Tail
3640   // call optimized function's reserved stack space needs to be aligned so that
3641   // taking the difference between two stack areas will result in an aligned
3642   // stack.
3643   MinReservedArea =
3644       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3645   FuncInfo->setMinReservedArea(MinReservedArea);
3646 
3647   SmallVector<SDValue, 8> MemOps;
3648 
3649   // If the function takes variable number of arguments, make a frame index for
3650   // the start of the first vararg value... for expansion of llvm.va_start.
3651   if (isVarArg) {
3652     static const MCPhysReg GPArgRegs[] = {
3653       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3654       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3655     };
3656     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3657 
3658     static const MCPhysReg FPArgRegs[] = {
3659       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3660       PPC::F8
3661     };
3662     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3663 
3664     if (useSoftFloat() || hasSPE())
3665        NumFPArgRegs = 0;
3666 
3667     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3668     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3669 
3670     // Make room for NumGPArgRegs and NumFPArgRegs.
3671     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3672                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3673 
3674     FuncInfo->setVarArgsStackOffset(
3675       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3676                             CCInfo.getNextStackOffset(), true));
3677 
3678     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3679     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3680 
3681     // The fixed integer arguments of a variadic function are stored to the
3682     // VarArgsFrameIndex on the stack so that they may be loaded by
3683     // dereferencing the result of va_next.
3684     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3685       // Get an existing live-in vreg, or add a new one.
3686       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3687       if (!VReg)
3688         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3689 
3690       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3691       SDValue Store =
3692           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3693       MemOps.push_back(Store);
3694       // Increment the address by four for the next argument to store
3695       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3696       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3697     }
3698 
3699     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3700     // is set.
3701     // The double arguments are stored to the VarArgsFrameIndex
3702     // on the stack.
3703     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3704       // Get an existing live-in vreg, or add a new one.
3705       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3706       if (!VReg)
3707         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3708 
3709       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3710       SDValue Store =
3711           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3712       MemOps.push_back(Store);
3713       // Increment the address by eight for the next argument to store
3714       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3715                                          PtrVT);
3716       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3717     }
3718   }
3719 
3720   if (!MemOps.empty())
3721     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3722 
3723   return Chain;
3724 }
3725 
3726 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3727 // value to MVT::i64 and then truncate to the correct register size.
3728 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3729                                              EVT ObjectVT, SelectionDAG &DAG,
3730                                              SDValue ArgVal,
3731                                              const SDLoc &dl) const {
3732   if (Flags.isSExt())
3733     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3734                          DAG.getValueType(ObjectVT));
3735   else if (Flags.isZExt())
3736     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3737                          DAG.getValueType(ObjectVT));
3738 
3739   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3740 }
3741 
3742 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3743     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3744     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3745     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3746   // TODO: add description of PPC stack frame format, or at least some docs.
3747   //
3748   bool isELFv2ABI = Subtarget.isELFv2ABI();
3749   bool isLittleEndian = Subtarget.isLittleEndian();
3750   MachineFunction &MF = DAG.getMachineFunction();
3751   MachineFrameInfo &MFI = MF.getFrameInfo();
3752   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3753 
3754   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3755          "fastcc not supported on varargs functions");
3756 
3757   EVT PtrVT = getPointerTy(MF.getDataLayout());
3758   // Potential tail calls could cause overwriting of argument stack slots.
3759   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3760                        (CallConv == CallingConv::Fast));
3761   unsigned PtrByteSize = 8;
3762   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3763 
3764   static const MCPhysReg GPR[] = {
3765     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3766     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3767   };
3768   static const MCPhysReg VR[] = {
3769     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3770     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3771   };
3772 
3773   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3774   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3775   const unsigned Num_VR_Regs  = array_lengthof(VR);
3776   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3777 
3778   // Do a first pass over the arguments to determine whether the ABI
3779   // guarantees that our caller has allocated the parameter save area
3780   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3781   // in the ELFv2 ABI, it is true if this is a vararg function or if
3782   // any parameter is located in a stack slot.
3783 
3784   bool HasParameterArea = !isELFv2ABI || isVarArg;
3785   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3786   unsigned NumBytes = LinkageSize;
3787   unsigned AvailableFPRs = Num_FPR_Regs;
3788   unsigned AvailableVRs = Num_VR_Regs;
3789   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3790     if (Ins[i].Flags.isNest())
3791       continue;
3792 
3793     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3794                                PtrByteSize, LinkageSize, ParamAreaSize,
3795                                NumBytes, AvailableFPRs, AvailableVRs,
3796                                Subtarget.hasQPX()))
3797       HasParameterArea = true;
3798   }
3799 
3800   // Add DAG nodes to load the arguments or copy them out of registers.  On
3801   // entry to a function on PPC, the arguments start after the linkage area,
3802   // although the first ones are often in registers.
3803 
3804   unsigned ArgOffset = LinkageSize;
3805   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3806   unsigned &QFPR_idx = FPR_idx;
3807   SmallVector<SDValue, 8> MemOps;
3808   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3809   unsigned CurArgIdx = 0;
3810   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3811     SDValue ArgVal;
3812     bool needsLoad = false;
3813     EVT ObjectVT = Ins[ArgNo].VT;
3814     EVT OrigVT = Ins[ArgNo].ArgVT;
3815     unsigned ObjSize = ObjectVT.getStoreSize();
3816     unsigned ArgSize = ObjSize;
3817     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3818     if (Ins[ArgNo].isOrigArg()) {
3819       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3820       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3821     }
3822     // We re-align the argument offset for each argument, except when using the
3823     // fast calling convention, when we need to make sure we do that only when
3824     // we'll actually use a stack slot.
3825     unsigned CurArgOffset;
3826     Align Alignment;
3827     auto ComputeArgOffset = [&]() {
3828       /* Respect alignment of argument on the stack.  */
3829       Alignment =
3830           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3831       ArgOffset = alignTo(ArgOffset, Alignment);
3832       CurArgOffset = ArgOffset;
3833     };
3834 
3835     if (CallConv != CallingConv::Fast) {
3836       ComputeArgOffset();
3837 
3838       /* Compute GPR index associated with argument offset.  */
3839       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3840       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3841     }
3842 
3843     // FIXME the codegen can be much improved in some cases.
3844     // We do not have to keep everything in memory.
3845     if (Flags.isByVal()) {
3846       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3847 
3848       if (CallConv == CallingConv::Fast)
3849         ComputeArgOffset();
3850 
3851       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3852       ObjSize = Flags.getByValSize();
3853       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3854       // Empty aggregate parameters do not take up registers.  Examples:
3855       //   struct { } a;
3856       //   union  { } b;
3857       //   int c[0];
3858       // etc.  However, we have to provide a place-holder in InVals, so
3859       // pretend we have an 8-byte item at the current address for that
3860       // purpose.
3861       if (!ObjSize) {
3862         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3863         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3864         InVals.push_back(FIN);
3865         continue;
3866       }
3867 
3868       // Create a stack object covering all stack doublewords occupied
3869       // by the argument.  If the argument is (fully or partially) on
3870       // the stack, or if the argument is fully in registers but the
3871       // caller has allocated the parameter save anyway, we can refer
3872       // directly to the caller's stack frame.  Otherwise, create a
3873       // local copy in our own frame.
3874       int FI;
3875       if (HasParameterArea ||
3876           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3877         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3878       else
3879         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3880       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3881 
3882       // Handle aggregates smaller than 8 bytes.
3883       if (ObjSize < PtrByteSize) {
3884         // The value of the object is its address, which differs from the
3885         // address of the enclosing doubleword on big-endian systems.
3886         SDValue Arg = FIN;
3887         if (!isLittleEndian) {
3888           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3889           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3890         }
3891         InVals.push_back(Arg);
3892 
3893         if (GPR_idx != Num_GPR_Regs) {
3894           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3895           FuncInfo->addLiveInAttr(VReg, Flags);
3896           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3897           SDValue Store;
3898 
3899           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3900             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3901                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3902             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3903                                       MachinePointerInfo(&*FuncArg), ObjType);
3904           } else {
3905             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3906             // store the whole register as-is to the parameter save area
3907             // slot.
3908             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3909                                  MachinePointerInfo(&*FuncArg));
3910           }
3911 
3912           MemOps.push_back(Store);
3913         }
3914         // Whether we copied from a register or not, advance the offset
3915         // into the parameter save area by a full doubleword.
3916         ArgOffset += PtrByteSize;
3917         continue;
3918       }
3919 
3920       // The value of the object is its address, which is the address of
3921       // its first stack doubleword.
3922       InVals.push_back(FIN);
3923 
3924       // Store whatever pieces of the object are in registers to memory.
3925       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3926         if (GPR_idx == Num_GPR_Regs)
3927           break;
3928 
3929         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3930         FuncInfo->addLiveInAttr(VReg, Flags);
3931         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3932         SDValue Addr = FIN;
3933         if (j) {
3934           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3935           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3936         }
3937         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3938                                      MachinePointerInfo(&*FuncArg, j));
3939         MemOps.push_back(Store);
3940         ++GPR_idx;
3941       }
3942       ArgOffset += ArgSize;
3943       continue;
3944     }
3945 
3946     switch (ObjectVT.getSimpleVT().SimpleTy) {
3947     default: llvm_unreachable("Unhandled argument type!");
3948     case MVT::i1:
3949     case MVT::i32:
3950     case MVT::i64:
3951       if (Flags.isNest()) {
3952         // The 'nest' parameter, if any, is passed in R11.
3953         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3954         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3955 
3956         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3957           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3958 
3959         break;
3960       }
3961 
3962       // These can be scalar arguments or elements of an integer array type
3963       // passed directly.  Clang may use those instead of "byval" aggregate
3964       // types to avoid forcing arguments to memory unnecessarily.
3965       if (GPR_idx != Num_GPR_Regs) {
3966         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3967         FuncInfo->addLiveInAttr(VReg, Flags);
3968         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3969 
3970         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3971           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3972           // value to MVT::i64 and then truncate to the correct register size.
3973           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3974       } else {
3975         if (CallConv == CallingConv::Fast)
3976           ComputeArgOffset();
3977 
3978         needsLoad = true;
3979         ArgSize = PtrByteSize;
3980       }
3981       if (CallConv != CallingConv::Fast || needsLoad)
3982         ArgOffset += 8;
3983       break;
3984 
3985     case MVT::f32:
3986     case MVT::f64:
3987       // These can be scalar arguments or elements of a float array type
3988       // passed directly.  The latter are used to implement ELFv2 homogenous
3989       // float aggregates.
3990       if (FPR_idx != Num_FPR_Regs) {
3991         unsigned VReg;
3992 
3993         if (ObjectVT == MVT::f32)
3994           VReg = MF.addLiveIn(FPR[FPR_idx],
3995                               Subtarget.hasP8Vector()
3996                                   ? &PPC::VSSRCRegClass
3997                                   : &PPC::F4RCRegClass);
3998         else
3999           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4000                                                 ? &PPC::VSFRCRegClass
4001                                                 : &PPC::F8RCRegClass);
4002 
4003         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4004         ++FPR_idx;
4005       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4006         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4007         // once we support fp <-> gpr moves.
4008 
4009         // This can only ever happen in the presence of f32 array types,
4010         // since otherwise we never run out of FPRs before running out
4011         // of GPRs.
4012         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4013         FuncInfo->addLiveInAttr(VReg, Flags);
4014         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4015 
4016         if (ObjectVT == MVT::f32) {
4017           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4018             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4019                                  DAG.getConstant(32, dl, MVT::i32));
4020           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4021         }
4022 
4023         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4024       } else {
4025         if (CallConv == CallingConv::Fast)
4026           ComputeArgOffset();
4027 
4028         needsLoad = true;
4029       }
4030 
4031       // When passing an array of floats, the array occupies consecutive
4032       // space in the argument area; only round up to the next doubleword
4033       // at the end of the array.  Otherwise, each float takes 8 bytes.
4034       if (CallConv != CallingConv::Fast || needsLoad) {
4035         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4036         ArgOffset += ArgSize;
4037         if (Flags.isInConsecutiveRegsLast())
4038           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4039       }
4040       break;
4041     case MVT::v4f32:
4042     case MVT::v4i32:
4043     case MVT::v8i16:
4044     case MVT::v16i8:
4045     case MVT::v2f64:
4046     case MVT::v2i64:
4047     case MVT::v1i128:
4048     case MVT::f128:
4049       if (!Subtarget.hasQPX()) {
4050         // These can be scalar arguments or elements of a vector array type
4051         // passed directly.  The latter are used to implement ELFv2 homogenous
4052         // vector aggregates.
4053         if (VR_idx != Num_VR_Regs) {
4054           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4055           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4056           ++VR_idx;
4057         } else {
4058           if (CallConv == CallingConv::Fast)
4059             ComputeArgOffset();
4060           needsLoad = true;
4061         }
4062         if (CallConv != CallingConv::Fast || needsLoad)
4063           ArgOffset += 16;
4064         break;
4065       } // not QPX
4066 
4067       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4068              "Invalid QPX parameter type");
4069       LLVM_FALLTHROUGH;
4070 
4071     case MVT::v4f64:
4072     case MVT::v4i1:
4073       // QPX vectors are treated like their scalar floating-point subregisters
4074       // (except that they're larger).
4075       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4076       if (QFPR_idx != Num_QFPR_Regs) {
4077         const TargetRegisterClass *RC;
4078         switch (ObjectVT.getSimpleVT().SimpleTy) {
4079         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4080         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4081         default:         RC = &PPC::QBRCRegClass; break;
4082         }
4083 
4084         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4085         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4086         ++QFPR_idx;
4087       } else {
4088         if (CallConv == CallingConv::Fast)
4089           ComputeArgOffset();
4090         needsLoad = true;
4091       }
4092       if (CallConv != CallingConv::Fast || needsLoad)
4093         ArgOffset += Sz;
4094       break;
4095     }
4096 
4097     // We need to load the argument to a virtual register if we determined
4098     // above that we ran out of physical registers of the appropriate type.
4099     if (needsLoad) {
4100       if (ObjSize < ArgSize && !isLittleEndian)
4101         CurArgOffset += ArgSize - ObjSize;
4102       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4103       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4104       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4105     }
4106 
4107     InVals.push_back(ArgVal);
4108   }
4109 
4110   // Area that is at least reserved in the caller of this function.
4111   unsigned MinReservedArea;
4112   if (HasParameterArea)
4113     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4114   else
4115     MinReservedArea = LinkageSize;
4116 
4117   // Set the size that is at least reserved in caller of this function.  Tail
4118   // call optimized functions' reserved stack space needs to be aligned so that
4119   // taking the difference between two stack areas will result in an aligned
4120   // stack.
4121   MinReservedArea =
4122       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4123   FuncInfo->setMinReservedArea(MinReservedArea);
4124 
4125   // If the function takes variable number of arguments, make a frame index for
4126   // the start of the first vararg value... for expansion of llvm.va_start.
4127   if (isVarArg) {
4128     int Depth = ArgOffset;
4129 
4130     FuncInfo->setVarArgsFrameIndex(
4131       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4132     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4133 
4134     // If this function is vararg, store any remaining integer argument regs
4135     // to their spots on the stack so that they may be loaded by dereferencing
4136     // the result of va_next.
4137     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4138          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4139       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4140       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4141       SDValue Store =
4142           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4143       MemOps.push_back(Store);
4144       // Increment the address by four for the next argument to store
4145       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4146       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4147     }
4148   }
4149 
4150   if (!MemOps.empty())
4151     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4152 
4153   return Chain;
4154 }
4155 
4156 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4157     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4158     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4159     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4160   // TODO: add description of PPC stack frame format, or at least some docs.
4161   //
4162   MachineFunction &MF = DAG.getMachineFunction();
4163   MachineFrameInfo &MFI = MF.getFrameInfo();
4164   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4165 
4166   EVT PtrVT = getPointerTy(MF.getDataLayout());
4167   bool isPPC64 = PtrVT == MVT::i64;
4168   // Potential tail calls could cause overwriting of argument stack slots.
4169   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4170                        (CallConv == CallingConv::Fast));
4171   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4172   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4173   unsigned ArgOffset = LinkageSize;
4174   // Area that is at least reserved in caller of this function.
4175   unsigned MinReservedArea = ArgOffset;
4176 
4177   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4178     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4179     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4180   };
4181   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4182     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4183     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4184   };
4185   static const MCPhysReg VR[] = {
4186     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4187     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4188   };
4189 
4190   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4191   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4192   const unsigned Num_VR_Regs  = array_lengthof( VR);
4193 
4194   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4195 
4196   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4197 
4198   // In 32-bit non-varargs functions, the stack space for vectors is after the
4199   // stack space for non-vectors.  We do not use this space unless we have
4200   // too many vectors to fit in registers, something that only occurs in
4201   // constructed examples:), but we have to walk the arglist to figure
4202   // that out...for the pathological case, compute VecArgOffset as the
4203   // start of the vector parameter area.  Computing VecArgOffset is the
4204   // entire point of the following loop.
4205   unsigned VecArgOffset = ArgOffset;
4206   if (!isVarArg && !isPPC64) {
4207     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4208          ++ArgNo) {
4209       EVT ObjectVT = Ins[ArgNo].VT;
4210       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4211 
4212       if (Flags.isByVal()) {
4213         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4214         unsigned ObjSize = Flags.getByValSize();
4215         unsigned ArgSize =
4216                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4217         VecArgOffset += ArgSize;
4218         continue;
4219       }
4220 
4221       switch(ObjectVT.getSimpleVT().SimpleTy) {
4222       default: llvm_unreachable("Unhandled argument type!");
4223       case MVT::i1:
4224       case MVT::i32:
4225       case MVT::f32:
4226         VecArgOffset += 4;
4227         break;
4228       case MVT::i64:  // PPC64
4229       case MVT::f64:
4230         // FIXME: We are guaranteed to be !isPPC64 at this point.
4231         // Does MVT::i64 apply?
4232         VecArgOffset += 8;
4233         break;
4234       case MVT::v4f32:
4235       case MVT::v4i32:
4236       case MVT::v8i16:
4237       case MVT::v16i8:
4238         // Nothing to do, we're only looking at Nonvector args here.
4239         break;
4240       }
4241     }
4242   }
4243   // We've found where the vector parameter area in memory is.  Skip the
4244   // first 12 parameters; these don't use that memory.
4245   VecArgOffset = ((VecArgOffset+15)/16)*16;
4246   VecArgOffset += 12*16;
4247 
4248   // Add DAG nodes to load the arguments or copy them out of registers.  On
4249   // entry to a function on PPC, the arguments start after the linkage area,
4250   // although the first ones are often in registers.
4251 
4252   SmallVector<SDValue, 8> MemOps;
4253   unsigned nAltivecParamsAtEnd = 0;
4254   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4255   unsigned CurArgIdx = 0;
4256   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4257     SDValue ArgVal;
4258     bool needsLoad = false;
4259     EVT ObjectVT = Ins[ArgNo].VT;
4260     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4261     unsigned ArgSize = ObjSize;
4262     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4263     if (Ins[ArgNo].isOrigArg()) {
4264       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4265       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4266     }
4267     unsigned CurArgOffset = ArgOffset;
4268 
4269     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4270     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4271         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4272       if (isVarArg || isPPC64) {
4273         MinReservedArea = ((MinReservedArea+15)/16)*16;
4274         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4275                                                   Flags,
4276                                                   PtrByteSize);
4277       } else  nAltivecParamsAtEnd++;
4278     } else
4279       // Calculate min reserved area.
4280       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4281                                                 Flags,
4282                                                 PtrByteSize);
4283 
4284     // FIXME the codegen can be much improved in some cases.
4285     // We do not have to keep everything in memory.
4286     if (Flags.isByVal()) {
4287       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4288 
4289       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4290       ObjSize = Flags.getByValSize();
4291       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4292       // Objects of size 1 and 2 are right justified, everything else is
4293       // left justified.  This means the memory address is adjusted forwards.
4294       if (ObjSize==1 || ObjSize==2) {
4295         CurArgOffset = CurArgOffset + (4 - ObjSize);
4296       }
4297       // The value of the object is its address.
4298       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4299       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4300       InVals.push_back(FIN);
4301       if (ObjSize==1 || ObjSize==2) {
4302         if (GPR_idx != Num_GPR_Regs) {
4303           unsigned VReg;
4304           if (isPPC64)
4305             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4306           else
4307             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4308           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4309           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4310           SDValue Store =
4311               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4312                                 MachinePointerInfo(&*FuncArg), ObjType);
4313           MemOps.push_back(Store);
4314           ++GPR_idx;
4315         }
4316 
4317         ArgOffset += PtrByteSize;
4318 
4319         continue;
4320       }
4321       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4322         // Store whatever pieces of the object are in registers
4323         // to memory.  ArgOffset will be the address of the beginning
4324         // of the object.
4325         if (GPR_idx != Num_GPR_Regs) {
4326           unsigned VReg;
4327           if (isPPC64)
4328             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4329           else
4330             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4331           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4332           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4333           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4334           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4335                                        MachinePointerInfo(&*FuncArg, j));
4336           MemOps.push_back(Store);
4337           ++GPR_idx;
4338           ArgOffset += PtrByteSize;
4339         } else {
4340           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4341           break;
4342         }
4343       }
4344       continue;
4345     }
4346 
4347     switch (ObjectVT.getSimpleVT().SimpleTy) {
4348     default: llvm_unreachable("Unhandled argument type!");
4349     case MVT::i1:
4350     case MVT::i32:
4351       if (!isPPC64) {
4352         if (GPR_idx != Num_GPR_Regs) {
4353           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4354           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4355 
4356           if (ObjectVT == MVT::i1)
4357             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4358 
4359           ++GPR_idx;
4360         } else {
4361           needsLoad = true;
4362           ArgSize = PtrByteSize;
4363         }
4364         // All int arguments reserve stack space in the Darwin ABI.
4365         ArgOffset += PtrByteSize;
4366         break;
4367       }
4368       LLVM_FALLTHROUGH;
4369     case MVT::i64:  // PPC64
4370       if (GPR_idx != Num_GPR_Regs) {
4371         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4372         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4373 
4374         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4375           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4376           // value to MVT::i64 and then truncate to the correct register size.
4377           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4378 
4379         ++GPR_idx;
4380       } else {
4381         needsLoad = true;
4382         ArgSize = PtrByteSize;
4383       }
4384       // All int arguments reserve stack space in the Darwin ABI.
4385       ArgOffset += 8;
4386       break;
4387 
4388     case MVT::f32:
4389     case MVT::f64:
4390       // Every 4 bytes of argument space consumes one of the GPRs available for
4391       // argument passing.
4392       if (GPR_idx != Num_GPR_Regs) {
4393         ++GPR_idx;
4394         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4395           ++GPR_idx;
4396       }
4397       if (FPR_idx != Num_FPR_Regs) {
4398         unsigned VReg;
4399 
4400         if (ObjectVT == MVT::f32)
4401           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4402         else
4403           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4404 
4405         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4406         ++FPR_idx;
4407       } else {
4408         needsLoad = true;
4409       }
4410 
4411       // All FP arguments reserve stack space in the Darwin ABI.
4412       ArgOffset += isPPC64 ? 8 : ObjSize;
4413       break;
4414     case MVT::v4f32:
4415     case MVT::v4i32:
4416     case MVT::v8i16:
4417     case MVT::v16i8:
4418       // Note that vector arguments in registers don't reserve stack space,
4419       // except in varargs functions.
4420       if (VR_idx != Num_VR_Regs) {
4421         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4422         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4423         if (isVarArg) {
4424           while ((ArgOffset % 16) != 0) {
4425             ArgOffset += PtrByteSize;
4426             if (GPR_idx != Num_GPR_Regs)
4427               GPR_idx++;
4428           }
4429           ArgOffset += 16;
4430           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4431         }
4432         ++VR_idx;
4433       } else {
4434         if (!isVarArg && !isPPC64) {
4435           // Vectors go after all the nonvectors.
4436           CurArgOffset = VecArgOffset;
4437           VecArgOffset += 16;
4438         } else {
4439           // Vectors are aligned.
4440           ArgOffset = ((ArgOffset+15)/16)*16;
4441           CurArgOffset = ArgOffset;
4442           ArgOffset += 16;
4443         }
4444         needsLoad = true;
4445       }
4446       break;
4447     }
4448 
4449     // We need to load the argument to a virtual register if we determined above
4450     // that we ran out of physical registers of the appropriate type.
4451     if (needsLoad) {
4452       int FI = MFI.CreateFixedObject(ObjSize,
4453                                      CurArgOffset + (ArgSize - ObjSize),
4454                                      isImmutable);
4455       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4456       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4457     }
4458 
4459     InVals.push_back(ArgVal);
4460   }
4461 
4462   // Allow for Altivec parameters at the end, if needed.
4463   if (nAltivecParamsAtEnd) {
4464     MinReservedArea = ((MinReservedArea+15)/16)*16;
4465     MinReservedArea += 16*nAltivecParamsAtEnd;
4466   }
4467 
4468   // Area that is at least reserved in the caller of this function.
4469   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4470 
4471   // Set the size that is at least reserved in caller of this function.  Tail
4472   // call optimized functions' reserved stack space needs to be aligned so that
4473   // taking the difference between two stack areas will result in an aligned
4474   // stack.
4475   MinReservedArea =
4476       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4477   FuncInfo->setMinReservedArea(MinReservedArea);
4478 
4479   // If the function takes variable number of arguments, make a frame index for
4480   // the start of the first vararg value... for expansion of llvm.va_start.
4481   if (isVarArg) {
4482     int Depth = ArgOffset;
4483 
4484     FuncInfo->setVarArgsFrameIndex(
4485       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4486                             Depth, true));
4487     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4488 
4489     // If this function is vararg, store any remaining integer argument regs
4490     // to their spots on the stack so that they may be loaded by dereferencing
4491     // the result of va_next.
4492     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4493       unsigned VReg;
4494 
4495       if (isPPC64)
4496         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4497       else
4498         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4499 
4500       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4501       SDValue Store =
4502           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4503       MemOps.push_back(Store);
4504       // Increment the address by four for the next argument to store
4505       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4506       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4507     }
4508   }
4509 
4510   if (!MemOps.empty())
4511     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4512 
4513   return Chain;
4514 }
4515 
4516 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4517 /// adjusted to accommodate the arguments for the tailcall.
4518 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4519                                    unsigned ParamSize) {
4520 
4521   if (!isTailCall) return 0;
4522 
4523   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4524   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4525   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4526   // Remember only if the new adjustment is bigger.
4527   if (SPDiff < FI->getTailCallSPDelta())
4528     FI->setTailCallSPDelta(SPDiff);
4529 
4530   return SPDiff;
4531 }
4532 
4533 static bool isFunctionGlobalAddress(SDValue Callee);
4534 
4535 static bool
4536 callsShareTOCBase(const Function *Caller, SDValue Callee,
4537                     const TargetMachine &TM) {
4538    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4539    // don't have enough information to determine if the caller and calle share
4540    // the same  TOC base, so we have to pessimistically assume they don't for
4541    // correctness.
4542    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4543    if (!G)
4544      return false;
4545 
4546    const GlobalValue *GV = G->getGlobal();
4547   // The medium and large code models are expected to provide a sufficiently
4548   // large TOC to provide all data addressing needs of a module with a
4549   // single TOC. Since each module will be addressed with a single TOC then we
4550   // only need to check that caller and callee don't cross dso boundaries.
4551   if (CodeModel::Medium == TM.getCodeModel() ||
4552       CodeModel::Large == TM.getCodeModel())
4553     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4554 
4555   // Otherwise we need to ensure callee and caller are in the same section,
4556   // since the linker may allocate multiple TOCs, and we don't know which
4557   // sections will belong to the same TOC base.
4558 
4559   if (!GV->isStrongDefinitionForLinker())
4560     return false;
4561 
4562   // Any explicitly-specified sections and section prefixes must also match.
4563   // Also, if we're using -ffunction-sections, then each function is always in
4564   // a different section (the same is true for COMDAT functions).
4565   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4566       GV->getSection() != Caller->getSection())
4567     return false;
4568   if (const auto *F = dyn_cast<Function>(GV)) {
4569     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4570       return false;
4571   }
4572 
4573   // If the callee might be interposed, then we can't assume the ultimate call
4574   // target will be in the same section. Even in cases where we can assume that
4575   // interposition won't happen, in any case where the linker might insert a
4576   // stub to allow for interposition, we must generate code as though
4577   // interposition might occur. To understand why this matters, consider a
4578   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4579   // in the same section, but a is in a different module (i.e. has a different
4580   // TOC base pointer). If the linker allows for interposition between b and c,
4581   // then it will generate a stub for the call edge between b and c which will
4582   // save the TOC pointer into the designated stack slot allocated by b. If we
4583   // return true here, and therefore allow a tail call between b and c, that
4584   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4585   // pointer into the stack slot allocated by a (where the a -> b stub saved
4586   // a's TOC base pointer). If we're not considering a tail call, but rather,
4587   // whether a nop is needed after the call instruction in b, because the linker
4588   // will insert a stub, it might complain about a missing nop if we omit it
4589   // (although many don't complain in this case).
4590   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4591     return false;
4592 
4593   return true;
4594 }
4595 
4596 static bool
4597 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4598                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4599   assert(Subtarget.is64BitELFABI());
4600 
4601   const unsigned PtrByteSize = 8;
4602   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4603 
4604   static const MCPhysReg GPR[] = {
4605     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4606     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4607   };
4608   static const MCPhysReg VR[] = {
4609     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4610     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4611   };
4612 
4613   const unsigned NumGPRs = array_lengthof(GPR);
4614   const unsigned NumFPRs = 13;
4615   const unsigned NumVRs = array_lengthof(VR);
4616   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4617 
4618   unsigned NumBytes = LinkageSize;
4619   unsigned AvailableFPRs = NumFPRs;
4620   unsigned AvailableVRs = NumVRs;
4621 
4622   for (const ISD::OutputArg& Param : Outs) {
4623     if (Param.Flags.isNest()) continue;
4624 
4625     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4626                                PtrByteSize, LinkageSize, ParamAreaSize,
4627                                NumBytes, AvailableFPRs, AvailableVRs,
4628                                Subtarget.hasQPX()))
4629       return true;
4630   }
4631   return false;
4632 }
4633 
4634 static bool
4635 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4636   if (CS.arg_size() != CallerFn->arg_size())
4637     return false;
4638 
4639   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4640   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4641   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4642 
4643   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4644     const Value* CalleeArg = *CalleeArgIter;
4645     const Value* CallerArg = &(*CallerArgIter);
4646     if (CalleeArg == CallerArg)
4647       continue;
4648 
4649     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4650     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4651     //      }
4652     // 1st argument of callee is undef and has the same type as caller.
4653     if (CalleeArg->getType() == CallerArg->getType() &&
4654         isa<UndefValue>(CalleeArg))
4655       continue;
4656 
4657     return false;
4658   }
4659 
4660   return true;
4661 }
4662 
4663 // Returns true if TCO is possible between the callers and callees
4664 // calling conventions.
4665 static bool
4666 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4667                                     CallingConv::ID CalleeCC) {
4668   // Tail calls are possible with fastcc and ccc.
4669   auto isTailCallableCC  = [] (CallingConv::ID CC){
4670       return  CC == CallingConv::C || CC == CallingConv::Fast;
4671   };
4672   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4673     return false;
4674 
4675   // We can safely tail call both fastcc and ccc callees from a c calling
4676   // convention caller. If the caller is fastcc, we may have less stack space
4677   // than a non-fastcc caller with the same signature so disable tail-calls in
4678   // that case.
4679   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4680 }
4681 
4682 bool
4683 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4684                                     SDValue Callee,
4685                                     CallingConv::ID CalleeCC,
4686                                     ImmutableCallSite CS,
4687                                     bool isVarArg,
4688                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4689                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4690                                     SelectionDAG& DAG) const {
4691   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4692 
4693   if (DisableSCO && !TailCallOpt) return false;
4694 
4695   // Variadic argument functions are not supported.
4696   if (isVarArg) return false;
4697 
4698   auto &Caller = DAG.getMachineFunction().getFunction();
4699   // Check that the calling conventions are compatible for tco.
4700   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4701     return false;
4702 
4703   // Caller contains any byval parameter is not supported.
4704   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4705     return false;
4706 
4707   // Callee contains any byval parameter is not supported, too.
4708   // Note: This is a quick work around, because in some cases, e.g.
4709   // caller's stack size > callee's stack size, we are still able to apply
4710   // sibling call optimization. For example, gcc is able to do SCO for caller1
4711   // in the following example, but not for caller2.
4712   //   struct test {
4713   //     long int a;
4714   //     char ary[56];
4715   //   } gTest;
4716   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4717   //     b->a = v.a;
4718   //     return 0;
4719   //   }
4720   //   void caller1(struct test a, struct test c, struct test *b) {
4721   //     callee(gTest, b); }
4722   //   void caller2(struct test *b) { callee(gTest, b); }
4723   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4724     return false;
4725 
4726   // If callee and caller use different calling conventions, we cannot pass
4727   // parameters on stack since offsets for the parameter area may be different.
4728   if (Caller.getCallingConv() != CalleeCC &&
4729       needStackSlotPassParameters(Subtarget, Outs))
4730     return false;
4731 
4732   // No TCO/SCO on indirect call because Caller have to restore its TOC
4733   if (!isFunctionGlobalAddress(Callee) &&
4734       !isa<ExternalSymbolSDNode>(Callee))
4735     return false;
4736 
4737   // If the caller and callee potentially have different TOC bases then we
4738   // cannot tail call since we need to restore the TOC pointer after the call.
4739   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4740   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4741     return false;
4742 
4743   // TCO allows altering callee ABI, so we don't have to check further.
4744   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4745     return true;
4746 
4747   if (DisableSCO) return false;
4748 
4749   // If callee use the same argument list that caller is using, then we can
4750   // apply SCO on this case. If it is not, then we need to check if callee needs
4751   // stack for passing arguments.
4752   if (!hasSameArgumentList(&Caller, CS) &&
4753       needStackSlotPassParameters(Subtarget, Outs)) {
4754     return false;
4755   }
4756 
4757   return true;
4758 }
4759 
4760 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4761 /// for tail call optimization. Targets which want to do tail call
4762 /// optimization should implement this function.
4763 bool
4764 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4765                                                      CallingConv::ID CalleeCC,
4766                                                      bool isVarArg,
4767                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4768                                                      SelectionDAG& DAG) const {
4769   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4770     return false;
4771 
4772   // Variable argument functions are not supported.
4773   if (isVarArg)
4774     return false;
4775 
4776   MachineFunction &MF = DAG.getMachineFunction();
4777   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4778   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4779     // Functions containing by val parameters are not supported.
4780     for (unsigned i = 0; i != Ins.size(); i++) {
4781        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4782        if (Flags.isByVal()) return false;
4783     }
4784 
4785     // Non-PIC/GOT tail calls are supported.
4786     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4787       return true;
4788 
4789     // At the moment we can only do local tail calls (in same module, hidden
4790     // or protected) if we are generating PIC.
4791     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4792       return G->getGlobal()->hasHiddenVisibility()
4793           || G->getGlobal()->hasProtectedVisibility();
4794   }
4795 
4796   return false;
4797 }
4798 
4799 /// isCallCompatibleAddress - Return the immediate to use if the specified
4800 /// 32-bit value is representable in the immediate field of a BxA instruction.
4801 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4802   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4803   if (!C) return nullptr;
4804 
4805   int Addr = C->getZExtValue();
4806   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4807       SignExtend32<26>(Addr) != Addr)
4808     return nullptr;  // Top 6 bits have to be sext of immediate.
4809 
4810   return DAG
4811       .getConstant(
4812           (int)C->getZExtValue() >> 2, SDLoc(Op),
4813           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4814       .getNode();
4815 }
4816 
4817 namespace {
4818 
4819 struct TailCallArgumentInfo {
4820   SDValue Arg;
4821   SDValue FrameIdxOp;
4822   int FrameIdx = 0;
4823 
4824   TailCallArgumentInfo() = default;
4825 };
4826 
4827 } // end anonymous namespace
4828 
4829 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4830 static void StoreTailCallArgumentsToStackSlot(
4831     SelectionDAG &DAG, SDValue Chain,
4832     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4833     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4834   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4835     SDValue Arg = TailCallArgs[i].Arg;
4836     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4837     int FI = TailCallArgs[i].FrameIdx;
4838     // Store relative to framepointer.
4839     MemOpChains.push_back(DAG.getStore(
4840         Chain, dl, Arg, FIN,
4841         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4842   }
4843 }
4844 
4845 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4846 /// the appropriate stack slot for the tail call optimized function call.
4847 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4848                                              SDValue OldRetAddr, SDValue OldFP,
4849                                              int SPDiff, const SDLoc &dl) {
4850   if (SPDiff) {
4851     // Calculate the new stack slot for the return address.
4852     MachineFunction &MF = DAG.getMachineFunction();
4853     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4854     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4855     bool isPPC64 = Subtarget.isPPC64();
4856     int SlotSize = isPPC64 ? 8 : 4;
4857     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4858     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4859                                                          NewRetAddrLoc, true);
4860     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4861     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4862     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4863                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4864   }
4865   return Chain;
4866 }
4867 
4868 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4869 /// the position of the argument.
4870 static void
4871 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4872                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4873                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4874   int Offset = ArgOffset + SPDiff;
4875   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4876   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4877   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4878   SDValue FIN = DAG.getFrameIndex(FI, VT);
4879   TailCallArgumentInfo Info;
4880   Info.Arg = Arg;
4881   Info.FrameIdxOp = FIN;
4882   Info.FrameIdx = FI;
4883   TailCallArguments.push_back(Info);
4884 }
4885 
4886 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4887 /// stack slot. Returns the chain as result and the loaded frame pointers in
4888 /// LROpOut/FPOpout. Used when tail calling.
4889 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4890     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4891     SDValue &FPOpOut, const SDLoc &dl) const {
4892   if (SPDiff) {
4893     // Load the LR and FP stack slot for later adjusting.
4894     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4895     LROpOut = getReturnAddrFrameIndex(DAG);
4896     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4897     Chain = SDValue(LROpOut.getNode(), 1);
4898   }
4899   return Chain;
4900 }
4901 
4902 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4903 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4904 /// specified by the specific parameter attribute. The copy will be passed as
4905 /// a byval function parameter.
4906 /// Sometimes what we are copying is the end of a larger object, the part that
4907 /// does not fit in registers.
4908 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4909                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4910                                          SelectionDAG &DAG, const SDLoc &dl) {
4911   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4912   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4913                        Flags.getNonZeroByValAlign(), false, false, false,
4914                        MachinePointerInfo(), MachinePointerInfo());
4915 }
4916 
4917 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4918 /// tail calls.
4919 static void LowerMemOpCallTo(
4920     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4921     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4922     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4923     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4924   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4925   if (!isTailCall) {
4926     if (isVector) {
4927       SDValue StackPtr;
4928       if (isPPC64)
4929         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4930       else
4931         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4932       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4933                            DAG.getConstant(ArgOffset, dl, PtrVT));
4934     }
4935     MemOpChains.push_back(
4936         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4937     // Calculate and remember argument location.
4938   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4939                                   TailCallArguments);
4940 }
4941 
4942 static void
4943 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4944                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4945                 SDValue FPOp,
4946                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4947   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4948   // might overwrite each other in case of tail call optimization.
4949   SmallVector<SDValue, 8> MemOpChains2;
4950   // Do not flag preceding copytoreg stuff together with the following stuff.
4951   InFlag = SDValue();
4952   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4953                                     MemOpChains2, dl);
4954   if (!MemOpChains2.empty())
4955     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4956 
4957   // Store the return address to the appropriate stack slot.
4958   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4959 
4960   // Emit callseq_end just before tailcall node.
4961   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4962                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4963   InFlag = Chain.getValue(1);
4964 }
4965 
4966 // Is this global address that of a function that can be called by name? (as
4967 // opposed to something that must hold a descriptor for an indirect call).
4968 static bool isFunctionGlobalAddress(SDValue Callee) {
4969   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4970     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4971         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4972       return false;
4973 
4974     return G->getGlobal()->getValueType()->isFunctionTy();
4975   }
4976 
4977   return false;
4978 }
4979 
4980 SDValue PPCTargetLowering::LowerCallResult(
4981     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4982     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4983     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4984   SmallVector<CCValAssign, 16> RVLocs;
4985   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4986                     *DAG.getContext());
4987 
4988   CCRetInfo.AnalyzeCallResult(
4989       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4990                ? RetCC_PPC_Cold
4991                : RetCC_PPC);
4992 
4993   // Copy all of the result registers out of their specified physreg.
4994   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4995     CCValAssign &VA = RVLocs[i];
4996     assert(VA.isRegLoc() && "Can only return in registers!");
4997 
4998     SDValue Val;
4999 
5000     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5001       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5002                                       InFlag);
5003       Chain = Lo.getValue(1);
5004       InFlag = Lo.getValue(2);
5005       VA = RVLocs[++i]; // skip ahead to next loc
5006       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5007                                       InFlag);
5008       Chain = Hi.getValue(1);
5009       InFlag = Hi.getValue(2);
5010       if (!Subtarget.isLittleEndian())
5011         std::swap (Lo, Hi);
5012       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5013     } else {
5014       Val = DAG.getCopyFromReg(Chain, dl,
5015                                VA.getLocReg(), VA.getLocVT(), InFlag);
5016       Chain = Val.getValue(1);
5017       InFlag = Val.getValue(2);
5018     }
5019 
5020     switch (VA.getLocInfo()) {
5021     default: llvm_unreachable("Unknown loc info!");
5022     case CCValAssign::Full: break;
5023     case CCValAssign::AExt:
5024       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5025       break;
5026     case CCValAssign::ZExt:
5027       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5028                         DAG.getValueType(VA.getValVT()));
5029       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5030       break;
5031     case CCValAssign::SExt:
5032       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5033                         DAG.getValueType(VA.getValVT()));
5034       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5035       break;
5036     }
5037 
5038     InVals.push_back(Val);
5039   }
5040 
5041   return Chain;
5042 }
5043 
5044 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5045                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5046   // PatchPoint calls are not indirect.
5047   if (isPatchPoint)
5048     return false;
5049 
5050   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5051     return false;
5052 
5053   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5054   // becuase the immediate function pointer points to a descriptor instead of
5055   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5056   // pointer immediate points to the global entry point, while the BLA would
5057   // need to jump to the local entry point (see rL211174).
5058   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5059       isBLACompatibleAddress(Callee, DAG))
5060     return false;
5061 
5062   return true;
5063 }
5064 
5065 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5066                               const Function &Caller,
5067                               const SDValue &Callee,
5068                               const PPCSubtarget &Subtarget,
5069                               const TargetMachine &TM) {
5070   if (CFlags.IsTailCall)
5071     return PPCISD::TC_RETURN;
5072 
5073   // This is a call through a function pointer.
5074   if (CFlags.IsIndirect) {
5075     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5076     // indirect calls. The save of the caller's TOC pointer to the stack will be
5077     // inserted into the DAG as part of call lowering. The restore of the TOC
5078     // pointer is modeled by using a pseudo instruction for the call opcode that
5079     // represents the 2 instruction sequence of an indirect branch and link,
5080     // immediately followed by a load of the TOC pointer from the the stack save
5081     // slot into gpr2.
5082     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5083       return PPCISD::BCTRL_LOAD_TOC;
5084 
5085     // An indirect call that does not need a TOC restore.
5086     return PPCISD::BCTRL;
5087   }
5088 
5089   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5090   // immediately following the call instruction if the caller and callee may
5091   // have different TOC bases. At link time if the linker determines the calls
5092   // may not share a TOC base, the call is redirected to a trampoline inserted
5093   // by the linker. The trampoline will (among other things) save the callers
5094   // TOC pointer at an ABI designated offset in the linkage area and the linker
5095   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5096   // into gpr2.
5097   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5098     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5099                                                   : PPCISD::CALL_NOP;
5100 
5101   return PPCISD::CALL;
5102 }
5103 
5104 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5105                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5106   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5107     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5108       return SDValue(Dest, 0);
5109 
5110   // Returns true if the callee is local, and false otherwise.
5111   auto isLocalCallee = [&]() {
5112     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5113     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5114     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5115 
5116     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5117            !dyn_cast_or_null<GlobalIFunc>(GV);
5118   };
5119 
5120   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5121   // a static relocation model causes some versions of GNU LD (2.17.50, at
5122   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5123   // built with secure-PLT.
5124   bool UsePlt =
5125       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5126       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5127 
5128   // On AIX, direct function calls reference the symbol for the function's
5129   // entry point, which is named by prepending a "." before the function's
5130   // C-linkage name.
5131   const auto getAIXFuncEntryPointSymbolSDNode =
5132       [&](StringRef FuncName, bool IsDeclaration,
5133           const XCOFF::StorageClass &SC) {
5134         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5135 
5136         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5137             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5138 
5139         if (IsDeclaration && !S->hasContainingCsect()) {
5140           // On AIX, an undefined symbol needs to be associated with a
5141           // MCSectionXCOFF to get the correct storage mapping class.
5142           // In this case, XCOFF::XMC_PR.
5143           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5144               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5145               SectionKind::getMetadata());
5146           S->setContainingCsect(Sec);
5147         }
5148 
5149         MVT PtrVT =
5150             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5151         return DAG.getMCSymbol(S, PtrVT);
5152       };
5153 
5154   if (isFunctionGlobalAddress(Callee)) {
5155     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5156     const GlobalValue *GV = G->getGlobal();
5157 
5158     if (!Subtarget.isAIXABI())
5159       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5160                                         UsePlt ? PPCII::MO_PLT : 0);
5161 
5162     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5163     const GlobalObject *GO = cast<GlobalObject>(GV);
5164     const XCOFF::StorageClass SC =
5165         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5166     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5167                                             SC);
5168   }
5169 
5170   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5171     const char *SymName = S->getSymbol();
5172     if (!Subtarget.isAIXABI())
5173       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5174                                          UsePlt ? PPCII::MO_PLT : 0);
5175 
5176     // If there exists a user-declared function whose name is the same as the
5177     // ExternalSymbol's, then we pick up the user-declared version.
5178     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5179     if (const Function *F =
5180             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5181       const XCOFF::StorageClass SC =
5182           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5183       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5184                                               SC);
5185     }
5186 
5187     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5188   }
5189 
5190   // No transformation needed.
5191   assert(Callee.getNode() && "What no callee?");
5192   return Callee;
5193 }
5194 
5195 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5196   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5197          "Expected a CALLSEQ_STARTSDNode.");
5198 
5199   // The last operand is the chain, except when the node has glue. If the node
5200   // has glue, then the last operand is the glue, and the chain is the second
5201   // last operand.
5202   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5203   if (LastValue.getValueType() != MVT::Glue)
5204     return LastValue;
5205 
5206   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5207 }
5208 
5209 // Creates the node that moves a functions address into the count register
5210 // to prepare for an indirect call instruction.
5211 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5212                                 SDValue &Glue, SDValue &Chain,
5213                                 const SDLoc &dl) {
5214   SDValue MTCTROps[] = {Chain, Callee, Glue};
5215   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5216   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5217                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5218   // The glue is the second value produced.
5219   Glue = Chain.getValue(1);
5220 }
5221 
5222 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5223                                           SDValue &Glue, SDValue &Chain,
5224                                           SDValue CallSeqStart,
5225                                           ImmutableCallSite CS, const SDLoc &dl,
5226                                           bool hasNest,
5227                                           const PPCSubtarget &Subtarget) {
5228   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5229   // entry point, but to the function descriptor (the function entry point
5230   // address is part of the function descriptor though).
5231   // The function descriptor is a three doubleword structure with the
5232   // following fields: function entry point, TOC base address and
5233   // environment pointer.
5234   // Thus for a call through a function pointer, the following actions need
5235   // to be performed:
5236   //   1. Save the TOC of the caller in the TOC save area of its stack
5237   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5238   //   2. Load the address of the function entry point from the function
5239   //      descriptor.
5240   //   3. Load the TOC of the callee from the function descriptor into r2.
5241   //   4. Load the environment pointer from the function descriptor into
5242   //      r11.
5243   //   5. Branch to the function entry point address.
5244   //   6. On return of the callee, the TOC of the caller needs to be
5245   //      restored (this is done in FinishCall()).
5246   //
5247   // The loads are scheduled at the beginning of the call sequence, and the
5248   // register copies are flagged together to ensure that no other
5249   // operations can be scheduled in between. E.g. without flagging the
5250   // copies together, a TOC access in the caller could be scheduled between
5251   // the assignment of the callee TOC and the branch to the callee, which leads
5252   // to incorrect code.
5253 
5254   // Start by loading the function address from the descriptor.
5255   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5256   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5257                       ? (MachineMemOperand::MODereferenceable |
5258                          MachineMemOperand::MOInvariant)
5259                       : MachineMemOperand::MONone;
5260 
5261   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5262 
5263   // Registers used in building the DAG.
5264   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5265   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5266 
5267   // Offsets of descriptor members.
5268   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5269   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5270 
5271   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5272   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5273 
5274   // One load for the functions entry point address.
5275   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5276                                     Alignment, MMOFlags);
5277 
5278   // One for loading the TOC anchor for the module that contains the called
5279   // function.
5280   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5281   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5282   SDValue TOCPtr =
5283       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5284                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5285 
5286   // One for loading the environment pointer.
5287   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5288   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5289   SDValue LoadEnvPtr =
5290       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5291                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5292 
5293 
5294   // Then copy the newly loaded TOC anchor to the TOC pointer.
5295   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5296   Chain = TOCVal.getValue(0);
5297   Glue = TOCVal.getValue(1);
5298 
5299   // If the function call has an explicit 'nest' parameter, it takes the
5300   // place of the environment pointer.
5301   assert((!hasNest || !Subtarget.isAIXABI()) &&
5302          "Nest parameter is not supported on AIX.");
5303   if (!hasNest) {
5304     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5305     Chain = EnvVal.getValue(0);
5306     Glue = EnvVal.getValue(1);
5307   }
5308 
5309   // The rest of the indirect call sequence is the same as the non-descriptor
5310   // DAG.
5311   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5312 }
5313 
5314 static void
5315 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5316                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5317                   SelectionDAG &DAG,
5318                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5319                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5320                   const PPCSubtarget &Subtarget) {
5321   const bool IsPPC64 = Subtarget.isPPC64();
5322   // MVT for a general purpose register.
5323   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5324 
5325   // First operand is always the chain.
5326   Ops.push_back(Chain);
5327 
5328   // If it's a direct call pass the callee as the second operand.
5329   if (!CFlags.IsIndirect)
5330     Ops.push_back(Callee);
5331   else {
5332     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5333 
5334     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5335     // on the stack (this would have been done in `LowerCall_64SVR4` or
5336     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5337     // represents both the indirect branch and a load that restores the TOC
5338     // pointer from the linkage area. The operand for the TOC restore is an add
5339     // of the TOC save offset to the stack pointer. This must be the second
5340     // operand: after the chain input but before any other variadic arguments.
5341     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5342       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5343 
5344       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5345       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5346       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5347       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5348       Ops.push_back(AddTOC);
5349     }
5350 
5351     // Add the register used for the environment pointer.
5352     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5353       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5354                                     RegVT));
5355 
5356 
5357     // Add CTR register as callee so a bctr can be emitted later.
5358     if (CFlags.IsTailCall)
5359       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5360   }
5361 
5362   // If this is a tail call add stack pointer delta.
5363   if (CFlags.IsTailCall)
5364     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5365 
5366   // Add argument registers to the end of the list so that they are known live
5367   // into the call.
5368   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5369     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5370                                   RegsToPass[i].second.getValueType()));
5371 
5372   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5373   // no way to mark dependencies as implicit here.
5374   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5375   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5376       !CFlags.IsPatchPoint)
5377     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5378 
5379   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5380   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5381     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5382 
5383   // Add a register mask operand representing the call-preserved registers.
5384   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5385   const uint32_t *Mask =
5386       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5387   assert(Mask && "Missing call preserved mask for calling convention");
5388   Ops.push_back(DAG.getRegisterMask(Mask));
5389 
5390   // If the glue is valid, it is the last operand.
5391   if (Glue.getNode())
5392     Ops.push_back(Glue);
5393 }
5394 
5395 SDValue PPCTargetLowering::FinishCall(
5396     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5397     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5398     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5399     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5400     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5401 
5402   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5403     setUsesTOCBasePtr(DAG);
5404 
5405   unsigned CallOpc =
5406       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5407                     Subtarget, DAG.getTarget());
5408 
5409   if (!CFlags.IsIndirect)
5410     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5411   else if (Subtarget.usesFunctionDescriptors())
5412     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5413                                   dl, CFlags.HasNest, Subtarget);
5414   else
5415     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5416 
5417   // Build the operand list for the call instruction.
5418   SmallVector<SDValue, 8> Ops;
5419   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5420                     SPDiff, Subtarget);
5421 
5422   // Emit tail call.
5423   if (CFlags.IsTailCall) {
5424     assert(((Callee.getOpcode() == ISD::Register &&
5425              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5426             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5427             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5428             isa<ConstantSDNode>(Callee)) &&
5429            "Expecting a global address, external symbol, absolute value or "
5430            "register");
5431     assert(CallOpc == PPCISD::TC_RETURN &&
5432            "Unexpected call opcode for a tail call.");
5433     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5434     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5435   }
5436 
5437   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5438   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5439   Glue = Chain.getValue(1);
5440 
5441   // When performing tail call optimization the callee pops its arguments off
5442   // the stack. Account for this here so these bytes can be pushed back on in
5443   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5444   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5445                          getTargetMachine().Options.GuaranteedTailCallOpt)
5446                             ? NumBytes
5447                             : 0;
5448 
5449   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5450                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5451                              Glue, dl);
5452   Glue = Chain.getValue(1);
5453 
5454   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5455                          DAG, InVals);
5456 }
5457 
5458 SDValue
5459 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5460                              SmallVectorImpl<SDValue> &InVals) const {
5461   SelectionDAG &DAG                     = CLI.DAG;
5462   SDLoc &dl                             = CLI.DL;
5463   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5464   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5465   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5466   SDValue Chain                         = CLI.Chain;
5467   SDValue Callee                        = CLI.Callee;
5468   bool &isTailCall                      = CLI.IsTailCall;
5469   CallingConv::ID CallConv              = CLI.CallConv;
5470   bool isVarArg                         = CLI.IsVarArg;
5471   bool isPatchPoint                     = CLI.IsPatchPoint;
5472   ImmutableCallSite CS                  = CLI.CS;
5473 
5474   if (isTailCall) {
5475     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5476       isTailCall = false;
5477     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5478       isTailCall =
5479         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5480                                                  isVarArg, Outs, Ins, DAG);
5481     else
5482       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5483                                                      Ins, DAG);
5484     if (isTailCall) {
5485       ++NumTailCalls;
5486       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5487         ++NumSiblingCalls;
5488 
5489       assert(isa<GlobalAddressSDNode>(Callee) &&
5490              "Callee should be an llvm::Function object.");
5491       LLVM_DEBUG(
5492           const GlobalValue *GV =
5493               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5494           const unsigned Width =
5495               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5496           dbgs() << "TCO caller: "
5497                  << left_justify(DAG.getMachineFunction().getName(), Width)
5498                  << ", callee linkage: " << GV->getVisibility() << ", "
5499                  << GV->getLinkage() << "\n");
5500     }
5501   }
5502 
5503   if (!isTailCall && CS && CS.isMustTailCall())
5504     report_fatal_error("failed to perform tail call elimination on a call "
5505                        "site marked musttail");
5506 
5507   // When long calls (i.e. indirect calls) are always used, calls are always
5508   // made via function pointer. If we have a function name, first translate it
5509   // into a pointer.
5510   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5511       !isTailCall)
5512     Callee = LowerGlobalAddress(Callee, DAG);
5513 
5514   CallFlags CFlags(
5515       CallConv, isTailCall, isVarArg, isPatchPoint,
5516       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5517       // hasNest
5518       Subtarget.is64BitELFABI() &&
5519           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5520 
5521   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5522     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5523                             InVals, CS);
5524 
5525   if (Subtarget.isSVR4ABI())
5526     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5527                             InVals, CS);
5528 
5529   if (Subtarget.isAIXABI())
5530     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5531                          InVals, CS);
5532 
5533   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5534                           InVals, CS);
5535 }
5536 
5537 SDValue PPCTargetLowering::LowerCall_32SVR4(
5538     SDValue Chain, SDValue Callee, CallFlags CFlags,
5539     const SmallVectorImpl<ISD::OutputArg> &Outs,
5540     const SmallVectorImpl<SDValue> &OutVals,
5541     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5542     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5543     ImmutableCallSite CS) const {
5544   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5545   // of the 32-bit SVR4 ABI stack frame layout.
5546 
5547   const CallingConv::ID CallConv = CFlags.CallConv;
5548   const bool IsVarArg = CFlags.IsVarArg;
5549   const bool IsTailCall = CFlags.IsTailCall;
5550 
5551   assert((CallConv == CallingConv::C ||
5552           CallConv == CallingConv::Cold ||
5553           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5554 
5555   unsigned PtrByteSize = 4;
5556 
5557   MachineFunction &MF = DAG.getMachineFunction();
5558 
5559   // Mark this function as potentially containing a function that contains a
5560   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5561   // and restoring the callers stack pointer in this functions epilog. This is
5562   // done because by tail calling the called function might overwrite the value
5563   // in this function's (MF) stack pointer stack slot 0(SP).
5564   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5565       CallConv == CallingConv::Fast)
5566     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5567 
5568   // Count how many bytes are to be pushed on the stack, including the linkage
5569   // area, parameter list area and the part of the local variable space which
5570   // contains copies of aggregates which are passed by value.
5571 
5572   // Assign locations to all of the outgoing arguments.
5573   SmallVector<CCValAssign, 16> ArgLocs;
5574   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5575 
5576   // Reserve space for the linkage area on the stack.
5577   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5578                        PtrByteSize);
5579   if (useSoftFloat())
5580     CCInfo.PreAnalyzeCallOperands(Outs);
5581 
5582   if (IsVarArg) {
5583     // Handle fixed and variable vector arguments differently.
5584     // Fixed vector arguments go into registers as long as registers are
5585     // available. Variable vector arguments always go into memory.
5586     unsigned NumArgs = Outs.size();
5587 
5588     for (unsigned i = 0; i != NumArgs; ++i) {
5589       MVT ArgVT = Outs[i].VT;
5590       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5591       bool Result;
5592 
5593       if (Outs[i].IsFixed) {
5594         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5595                                CCInfo);
5596       } else {
5597         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5598                                       ArgFlags, CCInfo);
5599       }
5600 
5601       if (Result) {
5602 #ifndef NDEBUG
5603         errs() << "Call operand #" << i << " has unhandled type "
5604              << EVT(ArgVT).getEVTString() << "\n";
5605 #endif
5606         llvm_unreachable(nullptr);
5607       }
5608     }
5609   } else {
5610     // All arguments are treated the same.
5611     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5612   }
5613   CCInfo.clearWasPPCF128();
5614 
5615   // Assign locations to all of the outgoing aggregate by value arguments.
5616   SmallVector<CCValAssign, 16> ByValArgLocs;
5617   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5618 
5619   // Reserve stack space for the allocations in CCInfo.
5620   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5621 
5622   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5623 
5624   // Size of the linkage area, parameter list area and the part of the local
5625   // space variable where copies of aggregates which are passed by value are
5626   // stored.
5627   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5628 
5629   // Calculate by how many bytes the stack has to be adjusted in case of tail
5630   // call optimization.
5631   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5632 
5633   // Adjust the stack pointer for the new arguments...
5634   // These operations are automatically eliminated by the prolog/epilog pass
5635   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5636   SDValue CallSeqStart = Chain;
5637 
5638   // Load the return address and frame pointer so it can be moved somewhere else
5639   // later.
5640   SDValue LROp, FPOp;
5641   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5642 
5643   // Set up a copy of the stack pointer for use loading and storing any
5644   // arguments that may not fit in the registers available for argument
5645   // passing.
5646   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5647 
5648   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5649   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5650   SmallVector<SDValue, 8> MemOpChains;
5651 
5652   bool seenFloatArg = false;
5653   // Walk the register/memloc assignments, inserting copies/loads.
5654   // i - Tracks the index into the list of registers allocated for the call
5655   // RealArgIdx - Tracks the index into the list of actual function arguments
5656   // j - Tracks the index into the list of byval arguments
5657   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5658        i != e;
5659        ++i, ++RealArgIdx) {
5660     CCValAssign &VA = ArgLocs[i];
5661     SDValue Arg = OutVals[RealArgIdx];
5662     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5663 
5664     if (Flags.isByVal()) {
5665       // Argument is an aggregate which is passed by value, thus we need to
5666       // create a copy of it in the local variable space of the current stack
5667       // frame (which is the stack frame of the caller) and pass the address of
5668       // this copy to the callee.
5669       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5670       CCValAssign &ByValVA = ByValArgLocs[j++];
5671       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5672 
5673       // Memory reserved in the local variable space of the callers stack frame.
5674       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5675 
5676       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5677       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5678                            StackPtr, PtrOff);
5679 
5680       // Create a copy of the argument in the local area of the current
5681       // stack frame.
5682       SDValue MemcpyCall =
5683         CreateCopyOfByValArgument(Arg, PtrOff,
5684                                   CallSeqStart.getNode()->getOperand(0),
5685                                   Flags, DAG, dl);
5686 
5687       // This must go outside the CALLSEQ_START..END.
5688       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5689                                                      SDLoc(MemcpyCall));
5690       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5691                              NewCallSeqStart.getNode());
5692       Chain = CallSeqStart = NewCallSeqStart;
5693 
5694       // Pass the address of the aggregate copy on the stack either in a
5695       // physical register or in the parameter list area of the current stack
5696       // frame to the callee.
5697       Arg = PtrOff;
5698     }
5699 
5700     // When useCRBits() is true, there can be i1 arguments.
5701     // It is because getRegisterType(MVT::i1) => MVT::i1,
5702     // and for other integer types getRegisterType() => MVT::i32.
5703     // Extend i1 and ensure callee will get i32.
5704     if (Arg.getValueType() == MVT::i1)
5705       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5706                         dl, MVT::i32, Arg);
5707 
5708     if (VA.isRegLoc()) {
5709       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5710       // Put argument in a physical register.
5711       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5712         bool IsLE = Subtarget.isLittleEndian();
5713         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5714                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5715         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5716         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5717                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5718         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5719                              SVal.getValue(0)));
5720       } else
5721         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5722     } else {
5723       // Put argument in the parameter list area of the current stack frame.
5724       assert(VA.isMemLoc());
5725       unsigned LocMemOffset = VA.getLocMemOffset();
5726 
5727       if (!IsTailCall) {
5728         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5729         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5730                              StackPtr, PtrOff);
5731 
5732         MemOpChains.push_back(
5733             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5734       } else {
5735         // Calculate and remember argument location.
5736         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5737                                  TailCallArguments);
5738       }
5739     }
5740   }
5741 
5742   if (!MemOpChains.empty())
5743     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5744 
5745   // Build a sequence of copy-to-reg nodes chained together with token chain
5746   // and flag operands which copy the outgoing args into the appropriate regs.
5747   SDValue InFlag;
5748   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5749     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5750                              RegsToPass[i].second, InFlag);
5751     InFlag = Chain.getValue(1);
5752   }
5753 
5754   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5755   // registers.
5756   if (IsVarArg) {
5757     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5758     SDValue Ops[] = { Chain, InFlag };
5759 
5760     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5761                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5762 
5763     InFlag = Chain.getValue(1);
5764   }
5765 
5766   if (IsTailCall)
5767     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5768                     TailCallArguments);
5769 
5770   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5771                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
5772 }
5773 
5774 // Copy an argument into memory, being careful to do this outside the
5775 // call sequence for the call to which the argument belongs.
5776 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5777     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5778     SelectionDAG &DAG, const SDLoc &dl) const {
5779   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5780                         CallSeqStart.getNode()->getOperand(0),
5781                         Flags, DAG, dl);
5782   // The MEMCPY must go outside the CALLSEQ_START..END.
5783   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5784   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5785                                                  SDLoc(MemcpyCall));
5786   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5787                          NewCallSeqStart.getNode());
5788   return NewCallSeqStart;
5789 }
5790 
5791 SDValue PPCTargetLowering::LowerCall_64SVR4(
5792     SDValue Chain, SDValue Callee, CallFlags CFlags,
5793     const SmallVectorImpl<ISD::OutputArg> &Outs,
5794     const SmallVectorImpl<SDValue> &OutVals,
5795     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5796     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5797     ImmutableCallSite CS) const {
5798   bool isELFv2ABI = Subtarget.isELFv2ABI();
5799   bool isLittleEndian = Subtarget.isLittleEndian();
5800   unsigned NumOps = Outs.size();
5801   bool IsSibCall = false;
5802   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5803 
5804   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5805   unsigned PtrByteSize = 8;
5806 
5807   MachineFunction &MF = DAG.getMachineFunction();
5808 
5809   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5810     IsSibCall = true;
5811 
5812   // Mark this function as potentially containing a function that contains a
5813   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5814   // and restoring the callers stack pointer in this functions epilog. This is
5815   // done because by tail calling the called function might overwrite the value
5816   // in this function's (MF) stack pointer stack slot 0(SP).
5817   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5818     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5819 
5820   assert(!(IsFastCall && CFlags.IsVarArg) &&
5821          "fastcc not supported on varargs functions");
5822 
5823   // Count how many bytes are to be pushed on the stack, including the linkage
5824   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5825   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5826   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5827   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5828   unsigned NumBytes = LinkageSize;
5829   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5830   unsigned &QFPR_idx = FPR_idx;
5831 
5832   static const MCPhysReg GPR[] = {
5833     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5834     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5835   };
5836   static const MCPhysReg VR[] = {
5837     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5838     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5839   };
5840 
5841   const unsigned NumGPRs = array_lengthof(GPR);
5842   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5843   const unsigned NumVRs  = array_lengthof(VR);
5844   const unsigned NumQFPRs = NumFPRs;
5845 
5846   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5847   // can be passed to the callee in registers.
5848   // For the fast calling convention, there is another check below.
5849   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5850   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5851   if (!HasParameterArea) {
5852     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5853     unsigned AvailableFPRs = NumFPRs;
5854     unsigned AvailableVRs = NumVRs;
5855     unsigned NumBytesTmp = NumBytes;
5856     for (unsigned i = 0; i != NumOps; ++i) {
5857       if (Outs[i].Flags.isNest()) continue;
5858       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5859                                 PtrByteSize, LinkageSize, ParamAreaSize,
5860                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5861                                 Subtarget.hasQPX()))
5862         HasParameterArea = true;
5863     }
5864   }
5865 
5866   // When using the fast calling convention, we don't provide backing for
5867   // arguments that will be in registers.
5868   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5869 
5870   // Avoid allocating parameter area for fastcc functions if all the arguments
5871   // can be passed in the registers.
5872   if (IsFastCall)
5873     HasParameterArea = false;
5874 
5875   // Add up all the space actually used.
5876   for (unsigned i = 0; i != NumOps; ++i) {
5877     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5878     EVT ArgVT = Outs[i].VT;
5879     EVT OrigVT = Outs[i].ArgVT;
5880 
5881     if (Flags.isNest())
5882       continue;
5883 
5884     if (IsFastCall) {
5885       if (Flags.isByVal()) {
5886         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5887         if (NumGPRsUsed > NumGPRs)
5888           HasParameterArea = true;
5889       } else {
5890         switch (ArgVT.getSimpleVT().SimpleTy) {
5891         default: llvm_unreachable("Unexpected ValueType for argument!");
5892         case MVT::i1:
5893         case MVT::i32:
5894         case MVT::i64:
5895           if (++NumGPRsUsed <= NumGPRs)
5896             continue;
5897           break;
5898         case MVT::v4i32:
5899         case MVT::v8i16:
5900         case MVT::v16i8:
5901         case MVT::v2f64:
5902         case MVT::v2i64:
5903         case MVT::v1i128:
5904         case MVT::f128:
5905           if (++NumVRsUsed <= NumVRs)
5906             continue;
5907           break;
5908         case MVT::v4f32:
5909           // When using QPX, this is handled like a FP register, otherwise, it
5910           // is an Altivec register.
5911           if (Subtarget.hasQPX()) {
5912             if (++NumFPRsUsed <= NumFPRs)
5913               continue;
5914           } else {
5915             if (++NumVRsUsed <= NumVRs)
5916               continue;
5917           }
5918           break;
5919         case MVT::f32:
5920         case MVT::f64:
5921         case MVT::v4f64: // QPX
5922         case MVT::v4i1:  // QPX
5923           if (++NumFPRsUsed <= NumFPRs)
5924             continue;
5925           break;
5926         }
5927         HasParameterArea = true;
5928       }
5929     }
5930 
5931     /* Respect alignment of argument on the stack.  */
5932     auto Alignement =
5933         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5934     NumBytes = alignTo(NumBytes, Alignement);
5935 
5936     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5937     if (Flags.isInConsecutiveRegsLast())
5938       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5939   }
5940 
5941   unsigned NumBytesActuallyUsed = NumBytes;
5942 
5943   // In the old ELFv1 ABI,
5944   // the prolog code of the callee may store up to 8 GPR argument registers to
5945   // the stack, allowing va_start to index over them in memory if its varargs.
5946   // Because we cannot tell if this is needed on the caller side, we have to
5947   // conservatively assume that it is needed.  As such, make sure we have at
5948   // least enough stack space for the caller to store the 8 GPRs.
5949   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5950   // really requires memory operands, e.g. a vararg function.
5951   if (HasParameterArea)
5952     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5953   else
5954     NumBytes = LinkageSize;
5955 
5956   // Tail call needs the stack to be aligned.
5957   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5958     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5959 
5960   int SPDiff = 0;
5961 
5962   // Calculate by how many bytes the stack has to be adjusted in case of tail
5963   // call optimization.
5964   if (!IsSibCall)
5965     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5966 
5967   // To protect arguments on the stack from being clobbered in a tail call,
5968   // force all the loads to happen before doing any other lowering.
5969   if (CFlags.IsTailCall)
5970     Chain = DAG.getStackArgumentTokenFactor(Chain);
5971 
5972   // Adjust the stack pointer for the new arguments...
5973   // These operations are automatically eliminated by the prolog/epilog pass
5974   if (!IsSibCall)
5975     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5976   SDValue CallSeqStart = Chain;
5977 
5978   // Load the return address and frame pointer so it can be move somewhere else
5979   // later.
5980   SDValue LROp, FPOp;
5981   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5982 
5983   // Set up a copy of the stack pointer for use loading and storing any
5984   // arguments that may not fit in the registers available for argument
5985   // passing.
5986   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5987 
5988   // Figure out which arguments are going to go in registers, and which in
5989   // memory.  Also, if this is a vararg function, floating point operations
5990   // must be stored to our stack, and loaded into integer regs as well, if
5991   // any integer regs are available for argument passing.
5992   unsigned ArgOffset = LinkageSize;
5993 
5994   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5995   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5996 
5997   SmallVector<SDValue, 8> MemOpChains;
5998   for (unsigned i = 0; i != NumOps; ++i) {
5999     SDValue Arg = OutVals[i];
6000     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6001     EVT ArgVT = Outs[i].VT;
6002     EVT OrigVT = Outs[i].ArgVT;
6003 
6004     // PtrOff will be used to store the current argument to the stack if a
6005     // register cannot be found for it.
6006     SDValue PtrOff;
6007 
6008     // We re-align the argument offset for each argument, except when using the
6009     // fast calling convention, when we need to make sure we do that only when
6010     // we'll actually use a stack slot.
6011     auto ComputePtrOff = [&]() {
6012       /* Respect alignment of argument on the stack.  */
6013       auto Alignment =
6014           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6015       ArgOffset = alignTo(ArgOffset, Alignment);
6016 
6017       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6018 
6019       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6020     };
6021 
6022     if (!IsFastCall) {
6023       ComputePtrOff();
6024 
6025       /* Compute GPR index associated with argument offset.  */
6026       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6027       GPR_idx = std::min(GPR_idx, NumGPRs);
6028     }
6029 
6030     // Promote integers to 64-bit values.
6031     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6032       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6033       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6034       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6035     }
6036 
6037     // FIXME memcpy is used way more than necessary.  Correctness first.
6038     // Note: "by value" is code for passing a structure by value, not
6039     // basic types.
6040     if (Flags.isByVal()) {
6041       // Note: Size includes alignment padding, so
6042       //   struct x { short a; char b; }
6043       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6044       // These are the proper values we need for right-justifying the
6045       // aggregate in a parameter register.
6046       unsigned Size = Flags.getByValSize();
6047 
6048       // An empty aggregate parameter takes up no storage and no
6049       // registers.
6050       if (Size == 0)
6051         continue;
6052 
6053       if (IsFastCall)
6054         ComputePtrOff();
6055 
6056       // All aggregates smaller than 8 bytes must be passed right-justified.
6057       if (Size==1 || Size==2 || Size==4) {
6058         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6059         if (GPR_idx != NumGPRs) {
6060           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6061                                         MachinePointerInfo(), VT);
6062           MemOpChains.push_back(Load.getValue(1));
6063           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6064 
6065           ArgOffset += PtrByteSize;
6066           continue;
6067         }
6068       }
6069 
6070       if (GPR_idx == NumGPRs && Size < 8) {
6071         SDValue AddPtr = PtrOff;
6072         if (!isLittleEndian) {
6073           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6074                                           PtrOff.getValueType());
6075           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6076         }
6077         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6078                                                           CallSeqStart,
6079                                                           Flags, DAG, dl);
6080         ArgOffset += PtrByteSize;
6081         continue;
6082       }
6083       // Copy entire object into memory.  There are cases where gcc-generated
6084       // code assumes it is there, even if it could be put entirely into
6085       // registers.  (This is not what the doc says.)
6086 
6087       // FIXME: The above statement is likely due to a misunderstanding of the
6088       // documents.  All arguments must be copied into the parameter area BY
6089       // THE CALLEE in the event that the callee takes the address of any
6090       // formal argument.  That has not yet been implemented.  However, it is
6091       // reasonable to use the stack area as a staging area for the register
6092       // load.
6093 
6094       // Skip this for small aggregates, as we will use the same slot for a
6095       // right-justified copy, below.
6096       if (Size >= 8)
6097         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6098                                                           CallSeqStart,
6099                                                           Flags, DAG, dl);
6100 
6101       // When a register is available, pass a small aggregate right-justified.
6102       if (Size < 8 && GPR_idx != NumGPRs) {
6103         // The easiest way to get this right-justified in a register
6104         // is to copy the structure into the rightmost portion of a
6105         // local variable slot, then load the whole slot into the
6106         // register.
6107         // FIXME: The memcpy seems to produce pretty awful code for
6108         // small aggregates, particularly for packed ones.
6109         // FIXME: It would be preferable to use the slot in the
6110         // parameter save area instead of a new local variable.
6111         SDValue AddPtr = PtrOff;
6112         if (!isLittleEndian) {
6113           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6114           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6115         }
6116         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6117                                                           CallSeqStart,
6118                                                           Flags, DAG, dl);
6119 
6120         // Load the slot into the register.
6121         SDValue Load =
6122             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6123         MemOpChains.push_back(Load.getValue(1));
6124         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6125 
6126         // Done with this argument.
6127         ArgOffset += PtrByteSize;
6128         continue;
6129       }
6130 
6131       // For aggregates larger than PtrByteSize, copy the pieces of the
6132       // object that fit into registers from the parameter save area.
6133       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6134         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6135         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6136         if (GPR_idx != NumGPRs) {
6137           SDValue Load =
6138               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6139           MemOpChains.push_back(Load.getValue(1));
6140           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6141           ArgOffset += PtrByteSize;
6142         } else {
6143           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6144           break;
6145         }
6146       }
6147       continue;
6148     }
6149 
6150     switch (Arg.getSimpleValueType().SimpleTy) {
6151     default: llvm_unreachable("Unexpected ValueType for argument!");
6152     case MVT::i1:
6153     case MVT::i32:
6154     case MVT::i64:
6155       if (Flags.isNest()) {
6156         // The 'nest' parameter, if any, is passed in R11.
6157         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6158         break;
6159       }
6160 
6161       // These can be scalar arguments or elements of an integer array type
6162       // passed directly.  Clang may use those instead of "byval" aggregate
6163       // types to avoid forcing arguments to memory unnecessarily.
6164       if (GPR_idx != NumGPRs) {
6165         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6166       } else {
6167         if (IsFastCall)
6168           ComputePtrOff();
6169 
6170         assert(HasParameterArea &&
6171                "Parameter area must exist to pass an argument in memory.");
6172         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6173                          true, CFlags.IsTailCall, false, MemOpChains,
6174                          TailCallArguments, dl);
6175         if (IsFastCall)
6176           ArgOffset += PtrByteSize;
6177       }
6178       if (!IsFastCall)
6179         ArgOffset += PtrByteSize;
6180       break;
6181     case MVT::f32:
6182     case MVT::f64: {
6183       // These can be scalar arguments or elements of a float array type
6184       // passed directly.  The latter are used to implement ELFv2 homogenous
6185       // float aggregates.
6186 
6187       // Named arguments go into FPRs first, and once they overflow, the
6188       // remaining arguments go into GPRs and then the parameter save area.
6189       // Unnamed arguments for vararg functions always go to GPRs and
6190       // then the parameter save area.  For now, put all arguments to vararg
6191       // routines always in both locations (FPR *and* GPR or stack slot).
6192       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6193       bool NeededLoad = false;
6194 
6195       // First load the argument into the next available FPR.
6196       if (FPR_idx != NumFPRs)
6197         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6198 
6199       // Next, load the argument into GPR or stack slot if needed.
6200       if (!NeedGPROrStack)
6201         ;
6202       else if (GPR_idx != NumGPRs && !IsFastCall) {
6203         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6204         // once we support fp <-> gpr moves.
6205 
6206         // In the non-vararg case, this can only ever happen in the
6207         // presence of f32 array types, since otherwise we never run
6208         // out of FPRs before running out of GPRs.
6209         SDValue ArgVal;
6210 
6211         // Double values are always passed in a single GPR.
6212         if (Arg.getValueType() != MVT::f32) {
6213           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6214 
6215         // Non-array float values are extended and passed in a GPR.
6216         } else if (!Flags.isInConsecutiveRegs()) {
6217           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6218           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6219 
6220         // If we have an array of floats, we collect every odd element
6221         // together with its predecessor into one GPR.
6222         } else if (ArgOffset % PtrByteSize != 0) {
6223           SDValue Lo, Hi;
6224           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6225           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6226           if (!isLittleEndian)
6227             std::swap(Lo, Hi);
6228           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6229 
6230         // The final element, if even, goes into the first half of a GPR.
6231         } else if (Flags.isInConsecutiveRegsLast()) {
6232           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6233           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6234           if (!isLittleEndian)
6235             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6236                                  DAG.getConstant(32, dl, MVT::i32));
6237 
6238         // Non-final even elements are skipped; they will be handled
6239         // together the with subsequent argument on the next go-around.
6240         } else
6241           ArgVal = SDValue();
6242 
6243         if (ArgVal.getNode())
6244           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6245       } else {
6246         if (IsFastCall)
6247           ComputePtrOff();
6248 
6249         // Single-precision floating-point values are mapped to the
6250         // second (rightmost) word of the stack doubleword.
6251         if (Arg.getValueType() == MVT::f32 &&
6252             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6253           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6254           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6255         }
6256 
6257         assert(HasParameterArea &&
6258                "Parameter area must exist to pass an argument in memory.");
6259         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6260                          true, CFlags.IsTailCall, false, MemOpChains,
6261                          TailCallArguments, dl);
6262 
6263         NeededLoad = true;
6264       }
6265       // When passing an array of floats, the array occupies consecutive
6266       // space in the argument area; only round up to the next doubleword
6267       // at the end of the array.  Otherwise, each float takes 8 bytes.
6268       if (!IsFastCall || NeededLoad) {
6269         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6270                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6271         if (Flags.isInConsecutiveRegsLast())
6272           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6273       }
6274       break;
6275     }
6276     case MVT::v4f32:
6277     case MVT::v4i32:
6278     case MVT::v8i16:
6279     case MVT::v16i8:
6280     case MVT::v2f64:
6281     case MVT::v2i64:
6282     case MVT::v1i128:
6283     case MVT::f128:
6284       if (!Subtarget.hasQPX()) {
6285       // These can be scalar arguments or elements of a vector array type
6286       // passed directly.  The latter are used to implement ELFv2 homogenous
6287       // vector aggregates.
6288 
6289       // For a varargs call, named arguments go into VRs or on the stack as
6290       // usual; unnamed arguments always go to the stack or the corresponding
6291       // GPRs when within range.  For now, we always put the value in both
6292       // locations (or even all three).
6293       if (CFlags.IsVarArg) {
6294         assert(HasParameterArea &&
6295                "Parameter area must exist if we have a varargs call.");
6296         // We could elide this store in the case where the object fits
6297         // entirely in R registers.  Maybe later.
6298         SDValue Store =
6299             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6300         MemOpChains.push_back(Store);
6301         if (VR_idx != NumVRs) {
6302           SDValue Load =
6303               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6304           MemOpChains.push_back(Load.getValue(1));
6305           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6306         }
6307         ArgOffset += 16;
6308         for (unsigned i=0; i<16; i+=PtrByteSize) {
6309           if (GPR_idx == NumGPRs)
6310             break;
6311           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6312                                    DAG.getConstant(i, dl, PtrVT));
6313           SDValue Load =
6314               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6315           MemOpChains.push_back(Load.getValue(1));
6316           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6317         }
6318         break;
6319       }
6320 
6321       // Non-varargs Altivec params go into VRs or on the stack.
6322       if (VR_idx != NumVRs) {
6323         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6324       } else {
6325         if (IsFastCall)
6326           ComputePtrOff();
6327 
6328         assert(HasParameterArea &&
6329                "Parameter area must exist to pass an argument in memory.");
6330         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6331                          true, CFlags.IsTailCall, true, MemOpChains,
6332                          TailCallArguments, dl);
6333         if (IsFastCall)
6334           ArgOffset += 16;
6335       }
6336 
6337       if (!IsFastCall)
6338         ArgOffset += 16;
6339       break;
6340       } // not QPX
6341 
6342       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6343              "Invalid QPX parameter type");
6344 
6345       LLVM_FALLTHROUGH;
6346     case MVT::v4f64:
6347     case MVT::v4i1: {
6348       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6349       if (CFlags.IsVarArg) {
6350         assert(HasParameterArea &&
6351                "Parameter area must exist if we have a varargs call.");
6352         // We could elide this store in the case where the object fits
6353         // entirely in R registers.  Maybe later.
6354         SDValue Store =
6355             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6356         MemOpChains.push_back(Store);
6357         if (QFPR_idx != NumQFPRs) {
6358           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6359                                      PtrOff, MachinePointerInfo());
6360           MemOpChains.push_back(Load.getValue(1));
6361           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6362         }
6363         ArgOffset += (IsF32 ? 16 : 32);
6364         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6365           if (GPR_idx == NumGPRs)
6366             break;
6367           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6368                                    DAG.getConstant(i, dl, PtrVT));
6369           SDValue Load =
6370               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6371           MemOpChains.push_back(Load.getValue(1));
6372           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6373         }
6374         break;
6375       }
6376 
6377       // Non-varargs QPX params go into registers or on the stack.
6378       if (QFPR_idx != NumQFPRs) {
6379         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6380       } else {
6381         if (IsFastCall)
6382           ComputePtrOff();
6383 
6384         assert(HasParameterArea &&
6385                "Parameter area must exist to pass an argument in memory.");
6386         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6387                          true, CFlags.IsTailCall, true, MemOpChains,
6388                          TailCallArguments, dl);
6389         if (IsFastCall)
6390           ArgOffset += (IsF32 ? 16 : 32);
6391       }
6392 
6393       if (!IsFastCall)
6394         ArgOffset += (IsF32 ? 16 : 32);
6395       break;
6396       }
6397     }
6398   }
6399 
6400   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6401          "mismatch in size of parameter area");
6402   (void)NumBytesActuallyUsed;
6403 
6404   if (!MemOpChains.empty())
6405     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6406 
6407   // Check if this is an indirect call (MTCTR/BCTRL).
6408   // See prepareDescriptorIndirectCall and buildCallOperands for more
6409   // information about calls through function pointers in the 64-bit SVR4 ABI.
6410   if (CFlags.IsIndirect) {
6411     assert(!CFlags.IsTailCall &&  "Indirect tails calls not supported");
6412     // Load r2 into a virtual register and store it to the TOC save area.
6413     setUsesTOCBasePtr(DAG);
6414     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6415     // TOC save area offset.
6416     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6417     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6418     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6419     Chain = DAG.getStore(
6420         Val.getValue(1), dl, Val, AddPtr,
6421         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6422     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6423     // This does not mean the MTCTR instruction must use R12; it's easier
6424     // to model this as an extra parameter, so do that.
6425     if (isELFv2ABI && !CFlags.IsPatchPoint)
6426       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6427   }
6428 
6429   // Build a sequence of copy-to-reg nodes chained together with token chain
6430   // and flag operands which copy the outgoing args into the appropriate regs.
6431   SDValue InFlag;
6432   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6433     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6434                              RegsToPass[i].second, InFlag);
6435     InFlag = Chain.getValue(1);
6436   }
6437 
6438   if (CFlags.IsTailCall && !IsSibCall)
6439     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6440                     TailCallArguments);
6441 
6442   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6443                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6444 }
6445 
6446 SDValue PPCTargetLowering::LowerCall_Darwin(
6447     SDValue Chain, SDValue Callee, CallFlags CFlags,
6448     const SmallVectorImpl<ISD::OutputArg> &Outs,
6449     const SmallVectorImpl<SDValue> &OutVals,
6450     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6451     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6452     ImmutableCallSite CS) const {
6453   unsigned NumOps = Outs.size();
6454 
6455   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6456   bool isPPC64 = PtrVT == MVT::i64;
6457   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6458 
6459   MachineFunction &MF = DAG.getMachineFunction();
6460 
6461   // Mark this function as potentially containing a function that contains a
6462   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6463   // and restoring the callers stack pointer in this functions epilog. This is
6464   // done because by tail calling the called function might overwrite the value
6465   // in this function's (MF) stack pointer stack slot 0(SP).
6466   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6467       CFlags.CallConv == CallingConv::Fast)
6468     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6469 
6470   // Count how many bytes are to be pushed on the stack, including the linkage
6471   // area, and parameter passing area.  We start with 24/48 bytes, which is
6472   // prereserved space for [SP][CR][LR][3 x unused].
6473   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6474   unsigned NumBytes = LinkageSize;
6475 
6476   // Add up all the space actually used.
6477   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6478   // they all go in registers, but we must reserve stack space for them for
6479   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6480   // assigned stack space in order, with padding so Altivec parameters are
6481   // 16-byte aligned.
6482   unsigned nAltivecParamsAtEnd = 0;
6483   for (unsigned i = 0; i != NumOps; ++i) {
6484     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6485     EVT ArgVT = Outs[i].VT;
6486     // Varargs Altivec parameters are padded to a 16 byte boundary.
6487     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6488         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6489         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6490       if (!CFlags.IsVarArg && !isPPC64) {
6491         // Non-varargs Altivec parameters go after all the non-Altivec
6492         // parameters; handle those later so we know how much padding we need.
6493         nAltivecParamsAtEnd++;
6494         continue;
6495       }
6496       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6497       NumBytes = ((NumBytes+15)/16)*16;
6498     }
6499     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6500   }
6501 
6502   // Allow for Altivec parameters at the end, if needed.
6503   if (nAltivecParamsAtEnd) {
6504     NumBytes = ((NumBytes+15)/16)*16;
6505     NumBytes += 16*nAltivecParamsAtEnd;
6506   }
6507 
6508   // The prolog code of the callee may store up to 8 GPR argument registers to
6509   // the stack, allowing va_start to index over them in memory if its varargs.
6510   // Because we cannot tell if this is needed on the caller side, we have to
6511   // conservatively assume that it is needed.  As such, make sure we have at
6512   // least enough stack space for the caller to store the 8 GPRs.
6513   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6514 
6515   // Tail call needs the stack to be aligned.
6516   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6517       CFlags.CallConv == CallingConv::Fast)
6518     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6519 
6520   // Calculate by how many bytes the stack has to be adjusted in case of tail
6521   // call optimization.
6522   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6523 
6524   // To protect arguments on the stack from being clobbered in a tail call,
6525   // force all the loads to happen before doing any other lowering.
6526   if (CFlags.IsTailCall)
6527     Chain = DAG.getStackArgumentTokenFactor(Chain);
6528 
6529   // Adjust the stack pointer for the new arguments...
6530   // These operations are automatically eliminated by the prolog/epilog pass
6531   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6532   SDValue CallSeqStart = Chain;
6533 
6534   // Load the return address and frame pointer so it can be move somewhere else
6535   // later.
6536   SDValue LROp, FPOp;
6537   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6538 
6539   // Set up a copy of the stack pointer for use loading and storing any
6540   // arguments that may not fit in the registers available for argument
6541   // passing.
6542   SDValue StackPtr;
6543   if (isPPC64)
6544     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6545   else
6546     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6547 
6548   // Figure out which arguments are going to go in registers, and which in
6549   // memory.  Also, if this is a vararg function, floating point operations
6550   // must be stored to our stack, and loaded into integer regs as well, if
6551   // any integer regs are available for argument passing.
6552   unsigned ArgOffset = LinkageSize;
6553   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6554 
6555   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6556     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6557     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6558   };
6559   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6560     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6561     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6562   };
6563   static const MCPhysReg VR[] = {
6564     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6565     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6566   };
6567   const unsigned NumGPRs = array_lengthof(GPR_32);
6568   const unsigned NumFPRs = 13;
6569   const unsigned NumVRs  = array_lengthof(VR);
6570 
6571   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6572 
6573   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6574   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6575 
6576   SmallVector<SDValue, 8> MemOpChains;
6577   for (unsigned i = 0; i != NumOps; ++i) {
6578     SDValue Arg = OutVals[i];
6579     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6580 
6581     // PtrOff will be used to store the current argument to the stack if a
6582     // register cannot be found for it.
6583     SDValue PtrOff;
6584 
6585     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6586 
6587     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6588 
6589     // On PPC64, promote integers to 64-bit values.
6590     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6591       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6592       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6593       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6594     }
6595 
6596     // FIXME memcpy is used way more than necessary.  Correctness first.
6597     // Note: "by value" is code for passing a structure by value, not
6598     // basic types.
6599     if (Flags.isByVal()) {
6600       unsigned Size = Flags.getByValSize();
6601       // Very small objects are passed right-justified.  Everything else is
6602       // passed left-justified.
6603       if (Size==1 || Size==2) {
6604         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6605         if (GPR_idx != NumGPRs) {
6606           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6607                                         MachinePointerInfo(), VT);
6608           MemOpChains.push_back(Load.getValue(1));
6609           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6610 
6611           ArgOffset += PtrByteSize;
6612         } else {
6613           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6614                                           PtrOff.getValueType());
6615           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6616           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6617                                                             CallSeqStart,
6618                                                             Flags, DAG, dl);
6619           ArgOffset += PtrByteSize;
6620         }
6621         continue;
6622       }
6623       // Copy entire object into memory.  There are cases where gcc-generated
6624       // code assumes it is there, even if it could be put entirely into
6625       // registers.  (This is not what the doc says.)
6626       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6627                                                         CallSeqStart,
6628                                                         Flags, DAG, dl);
6629 
6630       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6631       // copy the pieces of the object that fit into registers from the
6632       // parameter save area.
6633       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6634         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6635         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6636         if (GPR_idx != NumGPRs) {
6637           SDValue Load =
6638               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6639           MemOpChains.push_back(Load.getValue(1));
6640           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6641           ArgOffset += PtrByteSize;
6642         } else {
6643           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6644           break;
6645         }
6646       }
6647       continue;
6648     }
6649 
6650     switch (Arg.getSimpleValueType().SimpleTy) {
6651     default: llvm_unreachable("Unexpected ValueType for argument!");
6652     case MVT::i1:
6653     case MVT::i32:
6654     case MVT::i64:
6655       if (GPR_idx != NumGPRs) {
6656         if (Arg.getValueType() == MVT::i1)
6657           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6658 
6659         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6660       } else {
6661         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6662                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6663                          TailCallArguments, dl);
6664       }
6665       ArgOffset += PtrByteSize;
6666       break;
6667     case MVT::f32:
6668     case MVT::f64:
6669       if (FPR_idx != NumFPRs) {
6670         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6671 
6672         if (CFlags.IsVarArg) {
6673           SDValue Store =
6674               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6675           MemOpChains.push_back(Store);
6676 
6677           // Float varargs are always shadowed in available integer registers
6678           if (GPR_idx != NumGPRs) {
6679             SDValue Load =
6680                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6681             MemOpChains.push_back(Load.getValue(1));
6682             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6683           }
6684           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6685             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6686             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6687             SDValue Load =
6688                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6689             MemOpChains.push_back(Load.getValue(1));
6690             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6691           }
6692         } else {
6693           // If we have any FPRs remaining, we may also have GPRs remaining.
6694           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6695           // GPRs.
6696           if (GPR_idx != NumGPRs)
6697             ++GPR_idx;
6698           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6699               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6700             ++GPR_idx;
6701         }
6702       } else
6703         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6704                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6705                          TailCallArguments, dl);
6706       if (isPPC64)
6707         ArgOffset += 8;
6708       else
6709         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6710       break;
6711     case MVT::v4f32:
6712     case MVT::v4i32:
6713     case MVT::v8i16:
6714     case MVT::v16i8:
6715       if (CFlags.IsVarArg) {
6716         // These go aligned on the stack, or in the corresponding R registers
6717         // when within range.  The Darwin PPC ABI doc claims they also go in
6718         // V registers; in fact gcc does this only for arguments that are
6719         // prototyped, not for those that match the ...  We do it for all
6720         // arguments, seems to work.
6721         while (ArgOffset % 16 !=0) {
6722           ArgOffset += PtrByteSize;
6723           if (GPR_idx != NumGPRs)
6724             GPR_idx++;
6725         }
6726         // We could elide this store in the case where the object fits
6727         // entirely in R registers.  Maybe later.
6728         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6729                              DAG.getConstant(ArgOffset, dl, PtrVT));
6730         SDValue Store =
6731             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6732         MemOpChains.push_back(Store);
6733         if (VR_idx != NumVRs) {
6734           SDValue Load =
6735               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6736           MemOpChains.push_back(Load.getValue(1));
6737           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6738         }
6739         ArgOffset += 16;
6740         for (unsigned i=0; i<16; i+=PtrByteSize) {
6741           if (GPR_idx == NumGPRs)
6742             break;
6743           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6744                                    DAG.getConstant(i, dl, PtrVT));
6745           SDValue Load =
6746               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6747           MemOpChains.push_back(Load.getValue(1));
6748           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6749         }
6750         break;
6751       }
6752 
6753       // Non-varargs Altivec params generally go in registers, but have
6754       // stack space allocated at the end.
6755       if (VR_idx != NumVRs) {
6756         // Doesn't have GPR space allocated.
6757         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6758       } else if (nAltivecParamsAtEnd==0) {
6759         // We are emitting Altivec params in order.
6760         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6761                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6762                          TailCallArguments, dl);
6763         ArgOffset += 16;
6764       }
6765       break;
6766     }
6767   }
6768   // If all Altivec parameters fit in registers, as they usually do,
6769   // they get stack space following the non-Altivec parameters.  We
6770   // don't track this here because nobody below needs it.
6771   // If there are more Altivec parameters than fit in registers emit
6772   // the stores here.
6773   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6774     unsigned j = 0;
6775     // Offset is aligned; skip 1st 12 params which go in V registers.
6776     ArgOffset = ((ArgOffset+15)/16)*16;
6777     ArgOffset += 12*16;
6778     for (unsigned i = 0; i != NumOps; ++i) {
6779       SDValue Arg = OutVals[i];
6780       EVT ArgType = Outs[i].VT;
6781       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6782           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6783         if (++j > NumVRs) {
6784           SDValue PtrOff;
6785           // We are emitting Altivec params in order.
6786           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6787                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6788                            TailCallArguments, dl);
6789           ArgOffset += 16;
6790         }
6791       }
6792     }
6793   }
6794 
6795   if (!MemOpChains.empty())
6796     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6797 
6798   // On Darwin, R12 must contain the address of an indirect callee.  This does
6799   // not mean the MTCTR instruction must use R12; it's easier to model this as
6800   // an extra parameter, so do that.
6801   if (CFlags.IsIndirect) {
6802     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6803     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6804                                                    PPC::R12), Callee));
6805   }
6806 
6807   // Build a sequence of copy-to-reg nodes chained together with token chain
6808   // and flag operands which copy the outgoing args into the appropriate regs.
6809   SDValue InFlag;
6810   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6811     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6812                              RegsToPass[i].second, InFlag);
6813     InFlag = Chain.getValue(1);
6814   }
6815 
6816   if (CFlags.IsTailCall)
6817     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6818                     TailCallArguments);
6819 
6820   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6821                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6822 }
6823 
6824 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6825                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6826                    CCState &State) {
6827 
6828   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6829       State.getMachineFunction().getSubtarget());
6830   const bool IsPPC64 = Subtarget.isPPC64();
6831   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6832   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6833 
6834   assert((!ValVT.isInteger() ||
6835           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6836          "Integer argument exceeds register size: should have been legalized");
6837 
6838   if (ValVT == MVT::f128)
6839     report_fatal_error("f128 is unimplemented on AIX.");
6840 
6841   if (ArgFlags.isNest())
6842     report_fatal_error("Nest arguments are unimplemented.");
6843 
6844   if (ValVT.isVector() || LocVT.isVector())
6845     report_fatal_error("Vector arguments are unimplemented on AIX.");
6846 
6847   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6848                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6849                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6850   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6851                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6852                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6853 
6854   if (ArgFlags.isByVal()) {
6855     if (ArgFlags.getNonZeroByValAlign() > PtrByteSize)
6856       report_fatal_error("Pass-by-value arguments with alignment greater than "
6857                          "register width are not supported.");
6858 
6859     const unsigned ByValSize = ArgFlags.getByValSize();
6860 
6861     // An empty aggregate parameter takes up no storage and no registers,
6862     // but needs a MemLoc for a stack slot for the formal arguments side.
6863     if (ByValSize == 0) {
6864       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6865                                        State.getNextStackOffset(), RegVT,
6866                                        LocInfo));
6867       return false;
6868     }
6869 
6870     if (ByValSize <= PtrByteSize) {
6871       State.AllocateStack(PtrByteSize, PtrByteSize);
6872       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6873         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6874         return false;
6875       }
6876     }
6877 
6878     report_fatal_error(
6879         "Pass-by-value arguments are only supported in a single register.");
6880   }
6881 
6882   // Arguments always reserve parameter save area.
6883   switch (ValVT.SimpleTy) {
6884   default:
6885     report_fatal_error("Unhandled value type for argument.");
6886   case MVT::i64:
6887     // i64 arguments should have been split to i32 for PPC32.
6888     assert(IsPPC64 && "PPC32 should have split i64 values.");
6889     LLVM_FALLTHROUGH;
6890   case MVT::i1:
6891   case MVT::i32: {
6892     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
6893     // AIX integer arguments are always passed in register width.
6894     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6895       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6896                                   : CCValAssign::LocInfo::ZExt;
6897     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6898       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6899     else
6900       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6901 
6902     return false;
6903   }
6904   case MVT::f32:
6905   case MVT::f64: {
6906     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6907     const unsigned StoreSize = LocVT.getStoreSize();
6908     // Floats are always 4-byte aligned in the PSA on AIX.
6909     // This includes f64 in 64-bit mode for ABI compatibility.
6910     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6911     unsigned FReg = State.AllocateReg(FPR);
6912     if (FReg)
6913       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6914 
6915     // Reserve and initialize GPRs or initialize the PSA as required.
6916     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
6917       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6918         assert(FReg && "An FPR should be available when a GPR is reserved.");
6919         if (State.isVarArg()) {
6920           // Successfully reserved GPRs are only initialized for vararg calls.
6921           // Custom handling is required for:
6922           //   f64 in PPC32 needs to be split into 2 GPRs.
6923           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6924           State.addLoc(
6925               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6926         }
6927       } else {
6928         // If there are insufficient GPRs, the PSA needs to be initialized.
6929         // Initialization occurs even if an FPR was initialized for
6930         // compatibility with the AIX XL compiler. The full memory for the
6931         // argument will be initialized even if a prior word is saved in GPR.
6932         // A custom memLoc is used when the argument also passes in FPR so
6933         // that the callee handling can skip over it easily.
6934         State.addLoc(
6935             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6936                                              LocInfo)
6937                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6938         break;
6939       }
6940     }
6941 
6942     return false;
6943   }
6944   }
6945   return true;
6946 }
6947 
6948 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6949                                                     bool IsPPC64) {
6950   assert((IsPPC64 || SVT != MVT::i64) &&
6951          "i64 should have been split for 32-bit codegen.");
6952 
6953   switch (SVT) {
6954   default:
6955     report_fatal_error("Unexpected value type for formal argument");
6956   case MVT::i1:
6957   case MVT::i32:
6958   case MVT::i64:
6959     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6960   case MVT::f32:
6961     return &PPC::F4RCRegClass;
6962   case MVT::f64:
6963     return &PPC::F8RCRegClass;
6964   }
6965 }
6966 
6967 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6968                                         SelectionDAG &DAG, SDValue ArgValue,
6969                                         MVT LocVT, const SDLoc &dl) {
6970   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6971   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6972 
6973   if (Flags.isSExt())
6974     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6975                            DAG.getValueType(ValVT));
6976   else if (Flags.isZExt())
6977     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6978                            DAG.getValueType(ValVT));
6979 
6980   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6981 }
6982 
6983 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6984   const unsigned LASize = FL->getLinkageSize();
6985 
6986   if (PPC::GPRCRegClass.contains(Reg)) {
6987     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6988            "Reg must be a valid argument register!");
6989     return LASize + 4 * (Reg - PPC::R3);
6990   }
6991 
6992   if (PPC::G8RCRegClass.contains(Reg)) {
6993     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6994            "Reg must be a valid argument register!");
6995     return LASize + 8 * (Reg - PPC::X3);
6996   }
6997 
6998   llvm_unreachable("Only general purpose registers expected.");
6999 }
7000 
7001 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7002     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7003     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7004     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7005 
7006   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7007           CallConv == CallingConv::Fast) &&
7008          "Unexpected calling convention!");
7009 
7010   if (isVarArg)
7011     report_fatal_error("This call type is unimplemented on AIX.");
7012 
7013   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7014     report_fatal_error("Tail call support is unimplemented on AIX.");
7015 
7016   if (useSoftFloat())
7017     report_fatal_error("Soft float support is unimplemented on AIX.");
7018 
7019   const PPCSubtarget &Subtarget =
7020       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7021   if (Subtarget.hasQPX())
7022     report_fatal_error("QPX support is not supported on AIX.");
7023 
7024   const bool IsPPC64 = Subtarget.isPPC64();
7025   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7026 
7027   // Assign locations to all of the incoming arguments.
7028   SmallVector<CCValAssign, 16> ArgLocs;
7029   MachineFunction &MF = DAG.getMachineFunction();
7030   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7031 
7032   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7033   // Reserve space for the linkage area on the stack.
7034   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7035   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7036   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7037 
7038   SmallVector<SDValue, 8> MemOps;
7039 
7040   for (CCValAssign &VA : ArgLocs) {
7041     EVT ValVT = VA.getValVT();
7042     MVT LocVT = VA.getLocVT();
7043     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7044     assert((VA.isRegLoc() || VA.isMemLoc()) &&
7045            "Unexpected location for function call argument.");
7046 
7047     // For compatibility with the AIX XL compiler, the float args in the
7048     // parameter save area are initialized even if the argument is available
7049     // in register.  The caller is required to initialize both the register
7050     // and memory, however, the callee can choose to expect it in either.
7051     // The memloc is dismissed here because the argument is retrieved from
7052     // the register.
7053     if (VA.isMemLoc() && VA.needsCustom())
7054       continue;
7055 
7056     if (Flags.isByVal() && VA.isMemLoc()) {
7057       if (Flags.getByValSize() != 0)
7058         report_fatal_error(
7059             "ByVal arguments passed on stack not implemented yet");
7060 
7061       const int FI = MF.getFrameInfo().CreateFixedObject(
7062           PtrByteSize, VA.getLocMemOffset(), /* IsImmutable */ false,
7063           /* IsAliased */ true);
7064       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7065       InVals.push_back(FIN);
7066 
7067       continue;
7068     }
7069 
7070     if (Flags.isByVal()) {
7071       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7072 
7073       const unsigned ByValSize = Flags.getByValSize();
7074       if (ByValSize > PtrByteSize)
7075         report_fatal_error("Formal arguments greater then register size not "
7076                            "implemented yet.");
7077 
7078       const MCPhysReg ArgReg = VA.getLocReg();
7079       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7080       const unsigned Offset = mapArgRegToOffsetAIX(ArgReg, FL);
7081 
7082       const unsigned StackSize = alignTo(ByValSize, PtrByteSize);
7083       const int FI = MF.getFrameInfo().CreateFixedObject(
7084           StackSize, Offset, /* IsImmutable */ false, /* IsAliased */ true);
7085       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7086 
7087       InVals.push_back(FIN);
7088 
7089       const unsigned VReg = MF.addLiveIn(ArgReg, IsPPC64 ? &PPC::G8RCRegClass
7090                                                          : &PPC::GPRCRegClass);
7091 
7092       // Since the callers side has left justified the aggregate in the
7093       // register, we can simply store the entire register into the stack
7094       // slot.
7095       // The store to the fixedstack object is needed becuase accessing a
7096       // field of the ByVal will use a gep and load. Ideally we will optimize
7097       // to extracting the value from the register directly, and elide the
7098       // stores when the arguments address is not taken, but that will need to
7099       // be future work.
7100       SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7101       SDValue Store =
7102           DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, FIN,
7103                        MachinePointerInfo::getFixedStack(MF, FI, 0));
7104 
7105       MemOps.push_back(Store);
7106       continue;
7107     }
7108 
7109     if (VA.isRegLoc()) {
7110       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7111       unsigned VReg =
7112           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7113       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7114       if (ValVT.isScalarInteger() &&
7115           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7116         ArgValue =
7117             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7118       }
7119       InVals.push_back(ArgValue);
7120       continue;
7121     }
7122 
7123     const unsigned LocSize = LocVT.getStoreSize();
7124     const unsigned ValSize = ValVT.getStoreSize();
7125     assert((ValSize <= LocSize) && "Object size is larger than size of MemLoc");
7126     int CurArgOffset = VA.getLocMemOffset();
7127     // Objects are right-justified because AIX is big-endian.
7128     if (LocSize > ValSize)
7129       CurArgOffset += LocSize - ValSize;
7130     MachineFrameInfo &MFI = MF.getFrameInfo();
7131     // Potential tail calls could cause overwriting of argument stack slots.
7132     const bool IsImmutable =
7133         !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7134           (CallConv == CallingConv::Fast));
7135     int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7136     SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7137     SDValue ArgValue = DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7138     InVals.push_back(ArgValue);
7139   }
7140 
7141   // On AIX a minimum of 8 words is saved to the parameter save area.
7142   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7143   // Area that is at least reserved in the caller of this function.
7144   unsigned CallerReservedArea =
7145       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7146 
7147   // Set the size that is at least reserved in caller of this function. Tail
7148   // call optimized function's reserved stack space needs to be aligned so
7149   // that taking the difference between two stack areas will result in an
7150   // aligned stack.
7151   CallerReservedArea =
7152       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7153   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7154   FuncInfo->setMinReservedArea(CallerReservedArea);
7155 
7156   if (!MemOps.empty())
7157     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7158 
7159   return Chain;
7160 }
7161 
7162 SDValue PPCTargetLowering::LowerCall_AIX(
7163     SDValue Chain, SDValue Callee, CallFlags CFlags,
7164     const SmallVectorImpl<ISD::OutputArg> &Outs,
7165     const SmallVectorImpl<SDValue> &OutVals,
7166     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7167     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7168     ImmutableCallSite CS) const {
7169 
7170   assert((CFlags.CallConv == CallingConv::C ||
7171           CFlags.CallConv == CallingConv::Cold ||
7172           CFlags.CallConv == CallingConv::Fast) &&
7173          "Unexpected calling convention!");
7174 
7175   if (CFlags.IsPatchPoint)
7176     report_fatal_error("This call type is unimplemented on AIX.");
7177 
7178   const PPCSubtarget& Subtarget =
7179       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7180   if (Subtarget.hasQPX())
7181     report_fatal_error("QPX is not supported on AIX.");
7182   if (Subtarget.hasAltivec())
7183     report_fatal_error("Altivec support is unimplemented on AIX.");
7184 
7185   MachineFunction &MF = DAG.getMachineFunction();
7186   SmallVector<CCValAssign, 16> ArgLocs;
7187   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7188                  *DAG.getContext());
7189 
7190   // Reserve space for the linkage save area (LSA) on the stack.
7191   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7192   //   [SP][CR][LR][2 x reserved][TOC].
7193   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7194   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7195   const bool IsPPC64 = Subtarget.isPPC64();
7196   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7197   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7198   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7199   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7200 
7201   // The prolog code of the callee may store up to 8 GPR argument registers to
7202   // the stack, allowing va_start to index over them in memory if the callee
7203   // is variadic.
7204   // Because we cannot tell if this is needed on the caller side, we have to
7205   // conservatively assume that it is needed.  As such, make sure we have at
7206   // least enough stack space for the caller to store the 8 GPRs.
7207   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7208   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7209                                      CCInfo.getNextStackOffset());
7210 
7211   // Adjust the stack pointer for the new arguments...
7212   // These operations are automatically eliminated by the prolog/epilog pass.
7213   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7214   SDValue CallSeqStart = Chain;
7215 
7216   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7217   SmallVector<SDValue, 8> MemOpChains;
7218 
7219   // Set up a copy of the stack pointer for loading and storing any
7220   // arguments that may not fit in the registers available for argument
7221   // passing.
7222   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7223                                    : DAG.getRegister(PPC::R1, MVT::i32);
7224 
7225   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7226     CCValAssign &VA = ArgLocs[I++];
7227 
7228     SDValue Arg = OutVals[VA.getValNo()];
7229     ISD::ArgFlagsTy Flags = Outs[VA.getValNo()].Flags;
7230     const MVT LocVT = VA.getLocVT();
7231     const MVT ValVT = VA.getValVT();
7232 
7233     if (Flags.isByVal()) {
7234       const unsigned ByValSize = Flags.getByValSize();
7235 
7236       // Nothing to do for zero-sized ByVals on the caller side.
7237       if (!ByValSize)
7238         continue;
7239 
7240       assert(
7241           VA.isRegLoc() && ByValSize <= PtrByteSize &&
7242           "Pass-by-value arguments are only supported in a single register.");
7243 
7244       // Loads must be a power-of-2 size and cannot be larger than the
7245       // ByValSize. For example: a 7 byte by-val arg requires 4, 2 and 1 byte
7246       // loads.
7247       SDValue RegVal;
7248       for (unsigned Bytes = 0; Bytes != ByValSize;) {
7249         unsigned N = PowerOf2Floor(ByValSize - Bytes);
7250         const MVT VT =
7251             N == 1 ? MVT::i8
7252                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7253 
7254         SDValue LoadAddr = Arg;
7255         if (Bytes != 0) {
7256           // Adjust the load offset by the number of bytes read so far.
7257           SDNodeFlags Flags;
7258           Flags.setNoUnsignedWrap(true);
7259           LoadAddr = DAG.getNode(ISD::ADD, dl, LocVT, Arg,
7260                                  DAG.getConstant(Bytes, dl, LocVT), Flags);
7261         }
7262         SDValue Load = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, LoadAddr,
7263                                       MachinePointerInfo(), VT);
7264         MemOpChains.push_back(Load.getValue(1));
7265 
7266         Bytes += N;
7267         assert(LocVT.getSizeInBits() >= (Bytes * 8));
7268         if (unsigned NumSHLBits = LocVT.getSizeInBits() - (Bytes * 8)) {
7269           // By-val arguments are passed left-justfied in register.
7270           EVT ShiftAmountTy =
7271               getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7272           SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7273           SDValue ShiftedLoad =
7274               DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7275           RegVal = RegVal ? DAG.getNode(ISD::OR, dl, LocVT, RegVal, ShiftedLoad)
7276                           : ShiftedLoad;
7277         } else {
7278           assert(!RegVal && Bytes == ByValSize &&
7279                  "Pass-by-value argument handling unexpectedly incomplete.");
7280           RegVal = Load;
7281         }
7282       }
7283 
7284       RegsToPass.push_back(std::make_pair(VA.getLocReg(), RegVal));
7285       continue;
7286     }
7287 
7288     switch (VA.getLocInfo()) {
7289     default:
7290       report_fatal_error("Unexpected argument extension type.");
7291     case CCValAssign::Full:
7292       break;
7293     case CCValAssign::ZExt:
7294       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7295       break;
7296     case CCValAssign::SExt:
7297       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7298       break;
7299     }
7300 
7301     if (VA.isRegLoc() && !VA.needsCustom()) {
7302       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7303       continue;
7304     }
7305 
7306     if (VA.isMemLoc()) {
7307       SDValue PtrOff =
7308           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7309       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7310       MemOpChains.push_back(
7311           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7312 
7313       continue;
7314     }
7315 
7316     // Custom handling is used for GPR initializations for vararg float
7317     // arguments.
7318     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7319            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7320            "Unexpected register handling for calling convention.");
7321 
7322     SDValue ArgAsInt =
7323         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7324 
7325     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7326       // f32 in 32-bit GPR
7327       // f64 in 64-bit GPR
7328       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7329     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7330       // f32 in 64-bit GPR.
7331       RegsToPass.push_back(std::make_pair(
7332           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7333     else {
7334       // f64 in two 32-bit GPRs
7335       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7336       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7337              "Unexpected custom register for argument!");
7338       CCValAssign &GPR1 = VA;
7339       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7340                                      DAG.getConstant(32, dl, MVT::i8));
7341       RegsToPass.push_back(std::make_pair(
7342           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7343 
7344       if (I != E) {
7345         // If only 1 GPR was available, there will only be one custom GPR and
7346         // the argument will also pass in memory.
7347         CCValAssign &PeekArg = ArgLocs[I];
7348         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7349           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7350           CCValAssign &GPR2 = ArgLocs[I++];
7351           RegsToPass.push_back(std::make_pair(
7352               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7353         }
7354       }
7355     }
7356   }
7357 
7358   if (!MemOpChains.empty())
7359     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7360 
7361   // For indirect calls, we need to save the TOC base to the stack for
7362   // restoration after the call.
7363   if (CFlags.IsIndirect) {
7364     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7365     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7366     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7367     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7368     const unsigned TOCSaveOffset =
7369         Subtarget.getFrameLowering()->getTOCSaveOffset();
7370 
7371     setUsesTOCBasePtr(DAG);
7372     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7373     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7374     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7375     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7376     Chain = DAG.getStore(
7377         Val.getValue(1), dl, Val, AddPtr,
7378         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7379   }
7380 
7381   // Build a sequence of copy-to-reg nodes chained together with token chain
7382   // and flag operands which copy the outgoing args into the appropriate regs.
7383   SDValue InFlag;
7384   for (auto Reg : RegsToPass) {
7385     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7386     InFlag = Chain.getValue(1);
7387   }
7388 
7389   const int SPDiff = 0;
7390   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7391                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
7392 }
7393 
7394 bool
7395 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7396                                   MachineFunction &MF, bool isVarArg,
7397                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7398                                   LLVMContext &Context) const {
7399   SmallVector<CCValAssign, 16> RVLocs;
7400   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7401   return CCInfo.CheckReturn(
7402       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7403                 ? RetCC_PPC_Cold
7404                 : RetCC_PPC);
7405 }
7406 
7407 SDValue
7408 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7409                                bool isVarArg,
7410                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7411                                const SmallVectorImpl<SDValue> &OutVals,
7412                                const SDLoc &dl, SelectionDAG &DAG) const {
7413   SmallVector<CCValAssign, 16> RVLocs;
7414   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7415                  *DAG.getContext());
7416   CCInfo.AnalyzeReturn(Outs,
7417                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7418                            ? RetCC_PPC_Cold
7419                            : RetCC_PPC);
7420 
7421   SDValue Flag;
7422   SmallVector<SDValue, 4> RetOps(1, Chain);
7423 
7424   // Copy the result values into the output registers.
7425   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7426     CCValAssign &VA = RVLocs[i];
7427     assert(VA.isRegLoc() && "Can only return in registers!");
7428 
7429     SDValue Arg = OutVals[RealResIdx];
7430 
7431     switch (VA.getLocInfo()) {
7432     default: llvm_unreachable("Unknown loc info!");
7433     case CCValAssign::Full: break;
7434     case CCValAssign::AExt:
7435       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7436       break;
7437     case CCValAssign::ZExt:
7438       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7439       break;
7440     case CCValAssign::SExt:
7441       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7442       break;
7443     }
7444     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7445       bool isLittleEndian = Subtarget.isLittleEndian();
7446       // Legalize ret f64 -> ret 2 x i32.
7447       SDValue SVal =
7448           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7449                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7450       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7451       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7452       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7453                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7454       Flag = Chain.getValue(1);
7455       VA = RVLocs[++i]; // skip ahead to next loc
7456       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7457     } else
7458       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7459     Flag = Chain.getValue(1);
7460     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7461   }
7462 
7463   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7464   const MCPhysReg *I =
7465     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7466   if (I) {
7467     for (; *I; ++I) {
7468 
7469       if (PPC::G8RCRegClass.contains(*I))
7470         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7471       else if (PPC::F8RCRegClass.contains(*I))
7472         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7473       else if (PPC::CRRCRegClass.contains(*I))
7474         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7475       else if (PPC::VRRCRegClass.contains(*I))
7476         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7477       else
7478         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7479     }
7480   }
7481 
7482   RetOps[0] = Chain;  // Update chain.
7483 
7484   // Add the flag if we have it.
7485   if (Flag.getNode())
7486     RetOps.push_back(Flag);
7487 
7488   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7489 }
7490 
7491 SDValue
7492 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7493                                                 SelectionDAG &DAG) const {
7494   SDLoc dl(Op);
7495 
7496   // Get the correct type for integers.
7497   EVT IntVT = Op.getValueType();
7498 
7499   // Get the inputs.
7500   SDValue Chain = Op.getOperand(0);
7501   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7502   // Build a DYNAREAOFFSET node.
7503   SDValue Ops[2] = {Chain, FPSIdx};
7504   SDVTList VTs = DAG.getVTList(IntVT);
7505   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7506 }
7507 
7508 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7509                                              SelectionDAG &DAG) const {
7510   // When we pop the dynamic allocation we need to restore the SP link.
7511   SDLoc dl(Op);
7512 
7513   // Get the correct type for pointers.
7514   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7515 
7516   // Construct the stack pointer operand.
7517   bool isPPC64 = Subtarget.isPPC64();
7518   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7519   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7520 
7521   // Get the operands for the STACKRESTORE.
7522   SDValue Chain = Op.getOperand(0);
7523   SDValue SaveSP = Op.getOperand(1);
7524 
7525   // Load the old link SP.
7526   SDValue LoadLinkSP =
7527       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7528 
7529   // Restore the stack pointer.
7530   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7531 
7532   // Store the old link SP.
7533   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7534 }
7535 
7536 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7537   MachineFunction &MF = DAG.getMachineFunction();
7538   bool isPPC64 = Subtarget.isPPC64();
7539   EVT PtrVT = getPointerTy(MF.getDataLayout());
7540 
7541   // Get current frame pointer save index.  The users of this index will be
7542   // primarily DYNALLOC instructions.
7543   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7544   int RASI = FI->getReturnAddrSaveIndex();
7545 
7546   // If the frame pointer save index hasn't been defined yet.
7547   if (!RASI) {
7548     // Find out what the fix offset of the frame pointer save area.
7549     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7550     // Allocate the frame index for frame pointer save area.
7551     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7552     // Save the result.
7553     FI->setReturnAddrSaveIndex(RASI);
7554   }
7555   return DAG.getFrameIndex(RASI, PtrVT);
7556 }
7557 
7558 SDValue
7559 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7560   MachineFunction &MF = DAG.getMachineFunction();
7561   bool isPPC64 = Subtarget.isPPC64();
7562   EVT PtrVT = getPointerTy(MF.getDataLayout());
7563 
7564   // Get current frame pointer save index.  The users of this index will be
7565   // primarily DYNALLOC instructions.
7566   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7567   int FPSI = FI->getFramePointerSaveIndex();
7568 
7569   // If the frame pointer save index hasn't been defined yet.
7570   if (!FPSI) {
7571     // Find out what the fix offset of the frame pointer save area.
7572     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7573     // Allocate the frame index for frame pointer save area.
7574     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7575     // Save the result.
7576     FI->setFramePointerSaveIndex(FPSI);
7577   }
7578   return DAG.getFrameIndex(FPSI, PtrVT);
7579 }
7580 
7581 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7582                                                    SelectionDAG &DAG) const {
7583   // Get the inputs.
7584   SDValue Chain = Op.getOperand(0);
7585   SDValue Size  = Op.getOperand(1);
7586   SDLoc dl(Op);
7587 
7588   // Get the correct type for pointers.
7589   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7590   // Negate the size.
7591   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7592                                 DAG.getConstant(0, dl, PtrVT), Size);
7593   // Construct a node for the frame pointer save index.
7594   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7595   // Build a DYNALLOC node.
7596   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7597   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7598   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7599 }
7600 
7601 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7602                                                      SelectionDAG &DAG) const {
7603   MachineFunction &MF = DAG.getMachineFunction();
7604 
7605   bool isPPC64 = Subtarget.isPPC64();
7606   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7607 
7608   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7609   return DAG.getFrameIndex(FI, PtrVT);
7610 }
7611 
7612 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7613                                                SelectionDAG &DAG) const {
7614   SDLoc DL(Op);
7615   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7616                      DAG.getVTList(MVT::i32, MVT::Other),
7617                      Op.getOperand(0), Op.getOperand(1));
7618 }
7619 
7620 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7621                                                 SelectionDAG &DAG) const {
7622   SDLoc DL(Op);
7623   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7624                      Op.getOperand(0), Op.getOperand(1));
7625 }
7626 
7627 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7628   if (Op.getValueType().isVector())
7629     return LowerVectorLoad(Op, DAG);
7630 
7631   assert(Op.getValueType() == MVT::i1 &&
7632          "Custom lowering only for i1 loads");
7633 
7634   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7635 
7636   SDLoc dl(Op);
7637   LoadSDNode *LD = cast<LoadSDNode>(Op);
7638 
7639   SDValue Chain = LD->getChain();
7640   SDValue BasePtr = LD->getBasePtr();
7641   MachineMemOperand *MMO = LD->getMemOperand();
7642 
7643   SDValue NewLD =
7644       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7645                      BasePtr, MVT::i8, MMO);
7646   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7647 
7648   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7649   return DAG.getMergeValues(Ops, dl);
7650 }
7651 
7652 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7653   if (Op.getOperand(1).getValueType().isVector())
7654     return LowerVectorStore(Op, DAG);
7655 
7656   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7657          "Custom lowering only for i1 stores");
7658 
7659   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7660 
7661   SDLoc dl(Op);
7662   StoreSDNode *ST = cast<StoreSDNode>(Op);
7663 
7664   SDValue Chain = ST->getChain();
7665   SDValue BasePtr = ST->getBasePtr();
7666   SDValue Value = ST->getValue();
7667   MachineMemOperand *MMO = ST->getMemOperand();
7668 
7669   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7670                       Value);
7671   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7672 }
7673 
7674 // FIXME: Remove this once the ANDI glue bug is fixed:
7675 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7676   assert(Op.getValueType() == MVT::i1 &&
7677          "Custom lowering only for i1 results");
7678 
7679   SDLoc DL(Op);
7680   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7681 }
7682 
7683 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7684                                                SelectionDAG &DAG) const {
7685 
7686   // Implements a vector truncate that fits in a vector register as a shuffle.
7687   // We want to legalize vector truncates down to where the source fits in
7688   // a vector register (and target is therefore smaller than vector register
7689   // size).  At that point legalization will try to custom lower the sub-legal
7690   // result and get here - where we can contain the truncate as a single target
7691   // operation.
7692 
7693   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7694   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7695   //
7696   // We will implement it for big-endian ordering as this (where x denotes
7697   // undefined):
7698   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7699   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7700   //
7701   // The same operation in little-endian ordering will be:
7702   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7703   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7704 
7705   assert(Op.getValueType().isVector() && "Vector type expected.");
7706 
7707   SDLoc DL(Op);
7708   SDValue N1 = Op.getOperand(0);
7709   unsigned SrcSize = N1.getValueType().getSizeInBits();
7710   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7711   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7712 
7713   EVT TrgVT = Op.getValueType();
7714   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7715   EVT EltVT = TrgVT.getVectorElementType();
7716   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7717   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7718 
7719   // First list the elements we want to keep.
7720   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7721   SmallVector<int, 16> ShuffV;
7722   if (Subtarget.isLittleEndian())
7723     for (unsigned i = 0; i < TrgNumElts; ++i)
7724       ShuffV.push_back(i * SizeMult);
7725   else
7726     for (unsigned i = 1; i <= TrgNumElts; ++i)
7727       ShuffV.push_back(i * SizeMult - 1);
7728 
7729   // Populate the remaining elements with undefs.
7730   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7731     // ShuffV.push_back(i + WideNumElts);
7732     ShuffV.push_back(WideNumElts + 1);
7733 
7734   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7735   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7736 }
7737 
7738 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7739 /// possible.
7740 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7741   // Not FP? Not a fsel.
7742   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7743       !Op.getOperand(2).getValueType().isFloatingPoint())
7744     return Op;
7745 
7746   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7747 
7748   EVT ResVT = Op.getValueType();
7749   EVT CmpVT = Op.getOperand(0).getValueType();
7750   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7751   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7752   SDLoc dl(Op);
7753 
7754   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7755   // presence of infinities.
7756   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7757     switch (CC) {
7758     default:
7759       break;
7760     case ISD::SETOGT:
7761     case ISD::SETGT:
7762       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7763     case ISD::SETOLT:
7764     case ISD::SETLT:
7765       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7766     }
7767   }
7768 
7769   // We might be able to do better than this under some circumstances, but in
7770   // general, fsel-based lowering of select is a finite-math-only optimization.
7771   // For more information, see section F.3 of the 2.06 ISA specification.
7772   // With ISA 3.0
7773   if (!DAG.getTarget().Options.NoInfsFPMath ||
7774       !DAG.getTarget().Options.NoNaNsFPMath)
7775     return Op;
7776 
7777   // TODO: Propagate flags from the select rather than global settings.
7778   SDNodeFlags Flags;
7779   Flags.setNoInfs(true);
7780   Flags.setNoNaNs(true);
7781 
7782   // If the RHS of the comparison is a 0.0, we don't need to do the
7783   // subtraction at all.
7784   SDValue Sel1;
7785   if (isFloatingPointZero(RHS))
7786     switch (CC) {
7787     default: break;       // SETUO etc aren't handled by fsel.
7788     case ISD::SETNE:
7789       std::swap(TV, FV);
7790       LLVM_FALLTHROUGH;
7791     case ISD::SETEQ:
7792       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7793         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7794       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7795       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7796         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7797       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7798                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7799     case ISD::SETULT:
7800     case ISD::SETLT:
7801       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7802       LLVM_FALLTHROUGH;
7803     case ISD::SETOGE:
7804     case ISD::SETGE:
7805       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7806         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7807       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7808     case ISD::SETUGT:
7809     case ISD::SETGT:
7810       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7811       LLVM_FALLTHROUGH;
7812     case ISD::SETOLE:
7813     case ISD::SETLE:
7814       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7815         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7816       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7817                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7818     }
7819 
7820   SDValue Cmp;
7821   switch (CC) {
7822   default: break;       // SETUO etc aren't handled by fsel.
7823   case ISD::SETNE:
7824     std::swap(TV, FV);
7825     LLVM_FALLTHROUGH;
7826   case ISD::SETEQ:
7827     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7828     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7829       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7830     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7831     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7832       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7833     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7834                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7835   case ISD::SETULT:
7836   case ISD::SETLT:
7837     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7838     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7839       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7840     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7841   case ISD::SETOGE:
7842   case ISD::SETGE:
7843     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7844     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7845       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7846     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7847   case ISD::SETUGT:
7848   case ISD::SETGT:
7849     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7850     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7851       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7852     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7853   case ISD::SETOLE:
7854   case ISD::SETLE:
7855     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7856     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7857       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7858     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7859   }
7860   return Op;
7861 }
7862 
7863 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7864                                                SelectionDAG &DAG,
7865                                                const SDLoc &dl) const {
7866   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7867   SDValue Src = Op.getOperand(0);
7868   if (Src.getValueType() == MVT::f32)
7869     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7870 
7871   SDValue Tmp;
7872   switch (Op.getSimpleValueType().SimpleTy) {
7873   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7874   case MVT::i32:
7875     Tmp = DAG.getNode(
7876         Op.getOpcode() == ISD::FP_TO_SINT
7877             ? PPCISD::FCTIWZ
7878             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7879         dl, MVT::f64, Src);
7880     break;
7881   case MVT::i64:
7882     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7883            "i64 FP_TO_UINT is supported only with FPCVT");
7884     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7885                                                         PPCISD::FCTIDUZ,
7886                       dl, MVT::f64, Src);
7887     break;
7888   }
7889 
7890   // Convert the FP value to an int value through memory.
7891   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7892     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7893   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7894   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7895   MachinePointerInfo MPI =
7896       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7897 
7898   // Emit a store to the stack slot.
7899   SDValue Chain;
7900   if (i32Stack) {
7901     MachineFunction &MF = DAG.getMachineFunction();
7902     MachineMemOperand *MMO =
7903         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(4));
7904     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7905     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7906               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7907   } else
7908     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7909 
7910   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7911   // add in a bias on big endian.
7912   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7913     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7914                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7915     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7916   }
7917 
7918   RLI.Chain = Chain;
7919   RLI.Ptr = FIPtr;
7920   RLI.MPI = MPI;
7921 }
7922 
7923 /// Custom lowers floating point to integer conversions to use
7924 /// the direct move instructions available in ISA 2.07 to avoid the
7925 /// need for load/store combinations.
7926 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7927                                                     SelectionDAG &DAG,
7928                                                     const SDLoc &dl) const {
7929   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7930   SDValue Src = Op.getOperand(0);
7931 
7932   if (Src.getValueType() == MVT::f32)
7933     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7934 
7935   SDValue Tmp;
7936   switch (Op.getSimpleValueType().SimpleTy) {
7937   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7938   case MVT::i32:
7939     Tmp = DAG.getNode(
7940         Op.getOpcode() == ISD::FP_TO_SINT
7941             ? PPCISD::FCTIWZ
7942             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7943         dl, MVT::f64, Src);
7944     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7945     break;
7946   case MVT::i64:
7947     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7948            "i64 FP_TO_UINT is supported only with FPCVT");
7949     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7950                                                         PPCISD::FCTIDUZ,
7951                       dl, MVT::f64, Src);
7952     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7953     break;
7954   }
7955   return Tmp;
7956 }
7957 
7958 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7959                                           const SDLoc &dl) const {
7960 
7961   // FP to INT conversions are legal for f128.
7962   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7963     return Op;
7964 
7965   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7966   // PPC (the libcall is not available).
7967   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7968     if (Op.getValueType() == MVT::i32) {
7969       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7970         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7971                                  MVT::f64, Op.getOperand(0),
7972                                  DAG.getIntPtrConstant(0, dl));
7973         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7974                                  MVT::f64, Op.getOperand(0),
7975                                  DAG.getIntPtrConstant(1, dl));
7976 
7977         // Add the two halves of the long double in round-to-zero mode.
7978         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7979 
7980         // Now use a smaller FP_TO_SINT.
7981         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7982       }
7983       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7984         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7985         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7986         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7987         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7988         // FIXME: generated code sucks.
7989         // TODO: Are there fast-math-flags to propagate to this FSUB?
7990         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7991                                    Op.getOperand(0), Tmp);
7992         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7993         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7994                            DAG.getConstant(0x80000000, dl, MVT::i32));
7995         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7996                                     Op.getOperand(0));
7997         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7998                                ISD::SETGE);
7999       }
8000     }
8001 
8002     return SDValue();
8003   }
8004 
8005   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8006     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8007 
8008   ReuseLoadInfo RLI;
8009   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8010 
8011   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8012                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8013 }
8014 
8015 // We're trying to insert a regular store, S, and then a load, L. If the
8016 // incoming value, O, is a load, we might just be able to have our load use the
8017 // address used by O. However, we don't know if anything else will store to
8018 // that address before we can load from it. To prevent this situation, we need
8019 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8020 // the same chain operand as O, we create a token factor from the chain results
8021 // of O and L, and we replace all uses of O's chain result with that token
8022 // factor (see spliceIntoChain below for this last part).
8023 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8024                                             ReuseLoadInfo &RLI,
8025                                             SelectionDAG &DAG,
8026                                             ISD::LoadExtType ET) const {
8027   SDLoc dl(Op);
8028   if (ET == ISD::NON_EXTLOAD &&
8029       (Op.getOpcode() == ISD::FP_TO_UINT ||
8030        Op.getOpcode() == ISD::FP_TO_SINT) &&
8031       isOperationLegalOrCustom(Op.getOpcode(),
8032                                Op.getOperand(0).getValueType())) {
8033 
8034     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8035     return true;
8036   }
8037 
8038   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8039   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8040       LD->isNonTemporal())
8041     return false;
8042   if (LD->getMemoryVT() != MemVT)
8043     return false;
8044 
8045   RLI.Ptr = LD->getBasePtr();
8046   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8047     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8048            "Non-pre-inc AM on PPC?");
8049     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8050                           LD->getOffset());
8051   }
8052 
8053   RLI.Chain = LD->getChain();
8054   RLI.MPI = LD->getPointerInfo();
8055   RLI.IsDereferenceable = LD->isDereferenceable();
8056   RLI.IsInvariant = LD->isInvariant();
8057   RLI.Alignment = LD->getAlign();
8058   RLI.AAInfo = LD->getAAInfo();
8059   RLI.Ranges = LD->getRanges();
8060 
8061   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8062   return true;
8063 }
8064 
8065 // Given the head of the old chain, ResChain, insert a token factor containing
8066 // it and NewResChain, and make users of ResChain now be users of that token
8067 // factor.
8068 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8069 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8070                                         SDValue NewResChain,
8071                                         SelectionDAG &DAG) const {
8072   if (!ResChain)
8073     return;
8074 
8075   SDLoc dl(NewResChain);
8076 
8077   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8078                            NewResChain, DAG.getUNDEF(MVT::Other));
8079   assert(TF.getNode() != NewResChain.getNode() &&
8080          "A new TF really is required here");
8081 
8082   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8083   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8084 }
8085 
8086 /// Analyze profitability of direct move
8087 /// prefer float load to int load plus direct move
8088 /// when there is no integer use of int load
8089 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8090   SDNode *Origin = Op.getOperand(0).getNode();
8091   if (Origin->getOpcode() != ISD::LOAD)
8092     return true;
8093 
8094   // If there is no LXSIBZX/LXSIHZX, like Power8,
8095   // prefer direct move if the memory size is 1 or 2 bytes.
8096   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8097   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8098     return true;
8099 
8100   for (SDNode::use_iterator UI = Origin->use_begin(),
8101                             UE = Origin->use_end();
8102        UI != UE; ++UI) {
8103 
8104     // Only look at the users of the loaded value.
8105     if (UI.getUse().get().getResNo() != 0)
8106       continue;
8107 
8108     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8109         UI->getOpcode() != ISD::UINT_TO_FP)
8110       return true;
8111   }
8112 
8113   return false;
8114 }
8115 
8116 /// Custom lowers integer to floating point conversions to use
8117 /// the direct move instructions available in ISA 2.07 to avoid the
8118 /// need for load/store combinations.
8119 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8120                                                     SelectionDAG &DAG,
8121                                                     const SDLoc &dl) const {
8122   assert((Op.getValueType() == MVT::f32 ||
8123           Op.getValueType() == MVT::f64) &&
8124          "Invalid floating point type as target of conversion");
8125   assert(Subtarget.hasFPCVT() &&
8126          "Int to FP conversions with direct moves require FPCVT");
8127   SDValue FP;
8128   SDValue Src = Op.getOperand(0);
8129   bool SinglePrec = Op.getValueType() == MVT::f32;
8130   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8131   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8132   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8133                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8134 
8135   if (WordInt) {
8136     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8137                      dl, MVT::f64, Src);
8138     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8139   }
8140   else {
8141     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8142     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8143   }
8144 
8145   return FP;
8146 }
8147 
8148 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8149 
8150   EVT VecVT = Vec.getValueType();
8151   assert(VecVT.isVector() && "Expected a vector type.");
8152   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8153 
8154   EVT EltVT = VecVT.getVectorElementType();
8155   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8156   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8157 
8158   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8159   SmallVector<SDValue, 16> Ops(NumConcat);
8160   Ops[0] = Vec;
8161   SDValue UndefVec = DAG.getUNDEF(VecVT);
8162   for (unsigned i = 1; i < NumConcat; ++i)
8163     Ops[i] = UndefVec;
8164 
8165   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8166 }
8167 
8168 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8169                                                 const SDLoc &dl) const {
8170 
8171   unsigned Opc = Op.getOpcode();
8172   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8173          "Unexpected conversion type");
8174   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8175          "Supports conversions to v2f64/v4f32 only.");
8176 
8177   bool SignedConv = Opc == ISD::SINT_TO_FP;
8178   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8179 
8180   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8181   EVT WideVT = Wide.getValueType();
8182   unsigned WideNumElts = WideVT.getVectorNumElements();
8183   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8184 
8185   SmallVector<int, 16> ShuffV;
8186   for (unsigned i = 0; i < WideNumElts; ++i)
8187     ShuffV.push_back(i + WideNumElts);
8188 
8189   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8190   int SaveElts = FourEltRes ? 4 : 2;
8191   if (Subtarget.isLittleEndian())
8192     for (int i = 0; i < SaveElts; i++)
8193       ShuffV[i * Stride] = i;
8194   else
8195     for (int i = 1; i <= SaveElts; i++)
8196       ShuffV[i * Stride - 1] = i - 1;
8197 
8198   SDValue ShuffleSrc2 =
8199       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8200   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8201 
8202   SDValue Extend;
8203   if (SignedConv) {
8204     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8205     EVT ExtVT = Op.getOperand(0).getValueType();
8206     if (Subtarget.hasP9Altivec())
8207       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8208                                IntermediateVT.getVectorNumElements());
8209 
8210     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8211                          DAG.getValueType(ExtVT));
8212   } else
8213     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8214 
8215   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8216 }
8217 
8218 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8219                                           SelectionDAG &DAG) const {
8220   SDLoc dl(Op);
8221 
8222   EVT InVT = Op.getOperand(0).getValueType();
8223   EVT OutVT = Op.getValueType();
8224   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8225       isOperationCustom(Op.getOpcode(), InVT))
8226     return LowerINT_TO_FPVector(Op, DAG, dl);
8227 
8228   // Conversions to f128 are legal.
8229   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8230     return Op;
8231 
8232   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8233     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8234       return SDValue();
8235 
8236     SDValue Value = Op.getOperand(0);
8237     // The values are now known to be -1 (false) or 1 (true). To convert this
8238     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8239     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8240     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8241 
8242     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8243 
8244     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8245 
8246     if (Op.getValueType() != MVT::v4f64)
8247       Value = DAG.getNode(ISD::FP_ROUND, dl,
8248                           Op.getValueType(), Value,
8249                           DAG.getIntPtrConstant(1, dl));
8250     return Value;
8251   }
8252 
8253   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8254   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8255     return SDValue();
8256 
8257   if (Op.getOperand(0).getValueType() == MVT::i1)
8258     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8259                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8260                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8261 
8262   // If we have direct moves, we can do all the conversion, skip the store/load
8263   // however, without FPCVT we can't do most conversions.
8264   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8265       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8266     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8267 
8268   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8269          "UINT_TO_FP is supported only with FPCVT");
8270 
8271   // If we have FCFIDS, then use it when converting to single-precision.
8272   // Otherwise, convert to double-precision and then round.
8273   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8274                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8275                                                             : PPCISD::FCFIDS)
8276                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8277                                                             : PPCISD::FCFID);
8278   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8279                   ? MVT::f32
8280                   : MVT::f64;
8281 
8282   if (Op.getOperand(0).getValueType() == MVT::i64) {
8283     SDValue SINT = Op.getOperand(0);
8284     // When converting to single-precision, we actually need to convert
8285     // to double-precision first and then round to single-precision.
8286     // To avoid double-rounding effects during that operation, we have
8287     // to prepare the input operand.  Bits that might be truncated when
8288     // converting to double-precision are replaced by a bit that won't
8289     // be lost at this stage, but is below the single-precision rounding
8290     // position.
8291     //
8292     // However, if -enable-unsafe-fp-math is in effect, accept double
8293     // rounding to avoid the extra overhead.
8294     if (Op.getValueType() == MVT::f32 &&
8295         !Subtarget.hasFPCVT() &&
8296         !DAG.getTarget().Options.UnsafeFPMath) {
8297 
8298       // Twiddle input to make sure the low 11 bits are zero.  (If this
8299       // is the case, we are guaranteed the value will fit into the 53 bit
8300       // mantissa of an IEEE double-precision value without rounding.)
8301       // If any of those low 11 bits were not zero originally, make sure
8302       // bit 12 (value 2048) is set instead, so that the final rounding
8303       // to single-precision gets the correct result.
8304       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8305                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8306       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8307                           Round, DAG.getConstant(2047, dl, MVT::i64));
8308       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8309       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8310                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8311 
8312       // However, we cannot use that value unconditionally: if the magnitude
8313       // of the input value is small, the bit-twiddling we did above might
8314       // end up visibly changing the output.  Fortunately, in that case, we
8315       // don't need to twiddle bits since the original input will convert
8316       // exactly to double-precision floating-point already.  Therefore,
8317       // construct a conditional to use the original value if the top 11
8318       // bits are all sign-bit copies, and use the rounded value computed
8319       // above otherwise.
8320       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8321                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8322       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8323                          Cond, DAG.getConstant(1, dl, MVT::i64));
8324       Cond = DAG.getSetCC(
8325           dl,
8326           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8327           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8328 
8329       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8330     }
8331 
8332     ReuseLoadInfo RLI;
8333     SDValue Bits;
8334 
8335     MachineFunction &MF = DAG.getMachineFunction();
8336     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8337       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8338                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8339       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8340     } else if (Subtarget.hasLFIWAX() &&
8341                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8342       MachineMemOperand *MMO =
8343         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8344                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8345       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8346       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8347                                      DAG.getVTList(MVT::f64, MVT::Other),
8348                                      Ops, MVT::i32, MMO);
8349       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8350     } else if (Subtarget.hasFPCVT() &&
8351                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8352       MachineMemOperand *MMO =
8353         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8354                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8355       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8356       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8357                                      DAG.getVTList(MVT::f64, MVT::Other),
8358                                      Ops, MVT::i32, MMO);
8359       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8360     } else if (((Subtarget.hasLFIWAX() &&
8361                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8362                 (Subtarget.hasFPCVT() &&
8363                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8364                SINT.getOperand(0).getValueType() == MVT::i32) {
8365       MachineFrameInfo &MFI = MF.getFrameInfo();
8366       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8367 
8368       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8369       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8370 
8371       SDValue Store =
8372           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8373                        MachinePointerInfo::getFixedStack(
8374                            DAG.getMachineFunction(), FrameIdx));
8375 
8376       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8377              "Expected an i32 store");
8378 
8379       RLI.Ptr = FIdx;
8380       RLI.Chain = Store;
8381       RLI.MPI =
8382           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8383       RLI.Alignment = Align(4);
8384 
8385       MachineMemOperand *MMO =
8386         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8387                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8388       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8389       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8390                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8391                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8392                                      Ops, MVT::i32, MMO);
8393     } else
8394       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8395 
8396     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8397 
8398     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8399       FP = DAG.getNode(ISD::FP_ROUND, dl,
8400                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8401     return FP;
8402   }
8403 
8404   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8405          "Unhandled INT_TO_FP type in custom expander!");
8406   // Since we only generate this in 64-bit mode, we can take advantage of
8407   // 64-bit registers.  In particular, sign extend the input value into the
8408   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8409   // then lfd it and fcfid it.
8410   MachineFunction &MF = DAG.getMachineFunction();
8411   MachineFrameInfo &MFI = MF.getFrameInfo();
8412   EVT PtrVT = getPointerTy(MF.getDataLayout());
8413 
8414   SDValue Ld;
8415   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8416     ReuseLoadInfo RLI;
8417     bool ReusingLoad;
8418     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8419                                             DAG))) {
8420       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8421       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8422 
8423       SDValue Store =
8424           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8425                        MachinePointerInfo::getFixedStack(
8426                            DAG.getMachineFunction(), FrameIdx));
8427 
8428       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8429              "Expected an i32 store");
8430 
8431       RLI.Ptr = FIdx;
8432       RLI.Chain = Store;
8433       RLI.MPI =
8434           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8435       RLI.Alignment = Align(4);
8436     }
8437 
8438     MachineMemOperand *MMO =
8439       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8440                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8441     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8442     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8443                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8444                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8445                                  Ops, MVT::i32, MMO);
8446     if (ReusingLoad)
8447       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8448   } else {
8449     assert(Subtarget.isPPC64() &&
8450            "i32->FP without LFIWAX supported only on PPC64");
8451 
8452     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8453     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8454 
8455     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8456                                 Op.getOperand(0));
8457 
8458     // STD the extended value into the stack slot.
8459     SDValue Store = DAG.getStore(
8460         DAG.getEntryNode(), dl, Ext64, FIdx,
8461         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8462 
8463     // Load the value as a double.
8464     Ld = DAG.getLoad(
8465         MVT::f64, dl, Store, FIdx,
8466         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8467   }
8468 
8469   // FCFID it and return it.
8470   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8471   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8472     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8473                      DAG.getIntPtrConstant(0, dl));
8474   return FP;
8475 }
8476 
8477 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8478                                             SelectionDAG &DAG) const {
8479   SDLoc dl(Op);
8480   /*
8481    The rounding mode is in bits 30:31 of FPSR, and has the following
8482    settings:
8483      00 Round to nearest
8484      01 Round to 0
8485      10 Round to +inf
8486      11 Round to -inf
8487 
8488   FLT_ROUNDS, on the other hand, expects the following:
8489     -1 Undefined
8490      0 Round to 0
8491      1 Round to nearest
8492      2 Round to +inf
8493      3 Round to -inf
8494 
8495   To perform the conversion, we do:
8496     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8497   */
8498 
8499   MachineFunction &MF = DAG.getMachineFunction();
8500   EVT VT = Op.getValueType();
8501   EVT PtrVT = getPointerTy(MF.getDataLayout());
8502 
8503   // Save FP Control Word to register
8504   SDValue Chain = Op.getOperand(0);
8505   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8506   Chain = MFFS.getValue(1);
8507 
8508   // Save FP register to stack slot
8509   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8510   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8511   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8512 
8513   // Load FP Control Word from low 32 bits of stack slot.
8514   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8515   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8516   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8517   Chain = CWD.getValue(1);
8518 
8519   // Transform as necessary
8520   SDValue CWD1 =
8521     DAG.getNode(ISD::AND, dl, MVT::i32,
8522                 CWD, DAG.getConstant(3, dl, MVT::i32));
8523   SDValue CWD2 =
8524     DAG.getNode(ISD::SRL, dl, MVT::i32,
8525                 DAG.getNode(ISD::AND, dl, MVT::i32,
8526                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8527                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8528                             DAG.getConstant(3, dl, MVT::i32)),
8529                 DAG.getConstant(1, dl, MVT::i32));
8530 
8531   SDValue RetVal =
8532     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8533 
8534   RetVal =
8535       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8536                   dl, VT, RetVal);
8537 
8538   return DAG.getMergeValues({RetVal, Chain}, dl);
8539 }
8540 
8541 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8542   EVT VT = Op.getValueType();
8543   unsigned BitWidth = VT.getSizeInBits();
8544   SDLoc dl(Op);
8545   assert(Op.getNumOperands() == 3 &&
8546          VT == Op.getOperand(1).getValueType() &&
8547          "Unexpected SHL!");
8548 
8549   // Expand into a bunch of logical ops.  Note that these ops
8550   // depend on the PPC behavior for oversized shift amounts.
8551   SDValue Lo = Op.getOperand(0);
8552   SDValue Hi = Op.getOperand(1);
8553   SDValue Amt = Op.getOperand(2);
8554   EVT AmtVT = Amt.getValueType();
8555 
8556   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8557                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8558   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8559   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8560   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8561   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8562                              DAG.getConstant(-BitWidth, dl, AmtVT));
8563   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8564   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8565   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8566   SDValue OutOps[] = { OutLo, OutHi };
8567   return DAG.getMergeValues(OutOps, dl);
8568 }
8569 
8570 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8571   EVT VT = Op.getValueType();
8572   SDLoc dl(Op);
8573   unsigned BitWidth = VT.getSizeInBits();
8574   assert(Op.getNumOperands() == 3 &&
8575          VT == Op.getOperand(1).getValueType() &&
8576          "Unexpected SRL!");
8577 
8578   // Expand into a bunch of logical ops.  Note that these ops
8579   // depend on the PPC behavior for oversized shift amounts.
8580   SDValue Lo = Op.getOperand(0);
8581   SDValue Hi = Op.getOperand(1);
8582   SDValue Amt = Op.getOperand(2);
8583   EVT AmtVT = Amt.getValueType();
8584 
8585   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8586                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8587   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8588   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8589   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8590   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8591                              DAG.getConstant(-BitWidth, dl, AmtVT));
8592   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8593   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8594   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8595   SDValue OutOps[] = { OutLo, OutHi };
8596   return DAG.getMergeValues(OutOps, dl);
8597 }
8598 
8599 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8600   SDLoc dl(Op);
8601   EVT VT = Op.getValueType();
8602   unsigned BitWidth = VT.getSizeInBits();
8603   assert(Op.getNumOperands() == 3 &&
8604          VT == Op.getOperand(1).getValueType() &&
8605          "Unexpected SRA!");
8606 
8607   // Expand into a bunch of logical ops, followed by a select_cc.
8608   SDValue Lo = Op.getOperand(0);
8609   SDValue Hi = Op.getOperand(1);
8610   SDValue Amt = Op.getOperand(2);
8611   EVT AmtVT = Amt.getValueType();
8612 
8613   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8614                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8615   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8616   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8617   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8618   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8619                              DAG.getConstant(-BitWidth, dl, AmtVT));
8620   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8621   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8622   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8623                                   Tmp4, Tmp6, ISD::SETLE);
8624   SDValue OutOps[] = { OutLo, OutHi };
8625   return DAG.getMergeValues(OutOps, dl);
8626 }
8627 
8628 //===----------------------------------------------------------------------===//
8629 // Vector related lowering.
8630 //
8631 
8632 /// BuildSplatI - Build a canonical splati of Val with an element size of
8633 /// SplatSize.  Cast the result to VT.
8634 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8635                            SelectionDAG &DAG, const SDLoc &dl) {
8636   static const MVT VTys[] = { // canonical VT to use for each size.
8637     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8638   };
8639 
8640   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8641 
8642   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8643   if (Val == -1)
8644     SplatSize = 1;
8645 
8646   EVT CanonicalVT = VTys[SplatSize-1];
8647 
8648   // Build a canonical splat for this value.
8649   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8650 }
8651 
8652 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8653 /// specified intrinsic ID.
8654 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8655                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8656   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8657   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8658                      DAG.getConstant(IID, dl, MVT::i32), Op);
8659 }
8660 
8661 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8662 /// specified intrinsic ID.
8663 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8664                                 SelectionDAG &DAG, const SDLoc &dl,
8665                                 EVT DestVT = MVT::Other) {
8666   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8667   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8668                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8669 }
8670 
8671 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8672 /// specified intrinsic ID.
8673 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8674                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8675                                 EVT DestVT = MVT::Other) {
8676   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8677   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8678                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8679 }
8680 
8681 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8682 /// amount.  The result has the specified value type.
8683 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8684                            SelectionDAG &DAG, const SDLoc &dl) {
8685   // Force LHS/RHS to be the right type.
8686   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8687   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8688 
8689   int Ops[16];
8690   for (unsigned i = 0; i != 16; ++i)
8691     Ops[i] = i + Amt;
8692   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8693   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8694 }
8695 
8696 /// Do we have an efficient pattern in a .td file for this node?
8697 ///
8698 /// \param V - pointer to the BuildVectorSDNode being matched
8699 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8700 ///
8701 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8702 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8703 /// the opposite is true (expansion is beneficial) are:
8704 /// - The node builds a vector out of integers that are not 32 or 64-bits
8705 /// - The node builds a vector out of constants
8706 /// - The node is a "load-and-splat"
8707 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8708 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8709                                             bool HasDirectMove,
8710                                             bool HasP8Vector) {
8711   EVT VecVT = V->getValueType(0);
8712   bool RightType = VecVT == MVT::v2f64 ||
8713     (HasP8Vector && VecVT == MVT::v4f32) ||
8714     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8715   if (!RightType)
8716     return false;
8717 
8718   bool IsSplat = true;
8719   bool IsLoad = false;
8720   SDValue Op0 = V->getOperand(0);
8721 
8722   // This function is called in a block that confirms the node is not a constant
8723   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8724   // different constants.
8725   if (V->isConstant())
8726     return false;
8727   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8728     if (V->getOperand(i).isUndef())
8729       return false;
8730     // We want to expand nodes that represent load-and-splat even if the
8731     // loaded value is a floating point truncation or conversion to int.
8732     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8733         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8734          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8735         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8736          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8737         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8738          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8739       IsLoad = true;
8740     // If the operands are different or the input is not a load and has more
8741     // uses than just this BV node, then it isn't a splat.
8742     if (V->getOperand(i) != Op0 ||
8743         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8744       IsSplat = false;
8745   }
8746   return !(IsSplat && IsLoad);
8747 }
8748 
8749 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8750 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8751 
8752   SDLoc dl(Op);
8753   SDValue Op0 = Op->getOperand(0);
8754 
8755   if (!EnableQuadPrecision ||
8756       (Op.getValueType() != MVT::f128 ) ||
8757       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8758       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8759       (Op0.getOperand(1).getValueType() != MVT::i64))
8760     return SDValue();
8761 
8762   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8763                      Op0.getOperand(1));
8764 }
8765 
8766 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8767   const SDValue *InputLoad = &Op;
8768   if (InputLoad->getOpcode() == ISD::BITCAST)
8769     InputLoad = &InputLoad->getOperand(0);
8770   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8771     InputLoad = &InputLoad->getOperand(0);
8772   if (InputLoad->getOpcode() != ISD::LOAD)
8773     return nullptr;
8774   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8775   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8776 }
8777 
8778 // If this is a case we can't handle, return null and let the default
8779 // expansion code take care of it.  If we CAN select this case, and if it
8780 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8781 // this case more efficiently than a constant pool load, lower it to the
8782 // sequence of ops that should be used.
8783 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8784                                              SelectionDAG &DAG) const {
8785   SDLoc dl(Op);
8786   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8787   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8788 
8789   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8790     // We first build an i32 vector, load it into a QPX register,
8791     // then convert it to a floating-point vector and compare it
8792     // to a zero vector to get the boolean result.
8793     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8794     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8795     MachinePointerInfo PtrInfo =
8796         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8797     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8798     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8799 
8800     assert(BVN->getNumOperands() == 4 &&
8801       "BUILD_VECTOR for v4i1 does not have 4 operands");
8802 
8803     bool IsConst = true;
8804     for (unsigned i = 0; i < 4; ++i) {
8805       if (BVN->getOperand(i).isUndef()) continue;
8806       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8807         IsConst = false;
8808         break;
8809       }
8810     }
8811 
8812     if (IsConst) {
8813       Constant *One =
8814         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8815       Constant *NegOne =
8816         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8817 
8818       Constant *CV[4];
8819       for (unsigned i = 0; i < 4; ++i) {
8820         if (BVN->getOperand(i).isUndef())
8821           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8822         else if (isNullConstant(BVN->getOperand(i)))
8823           CV[i] = NegOne;
8824         else
8825           CV[i] = One;
8826       }
8827 
8828       Constant *CP = ConstantVector::get(CV);
8829       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8830                                           16 /* alignment */);
8831 
8832       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8833       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8834       return DAG.getMemIntrinsicNode(
8835           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8836           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8837     }
8838 
8839     SmallVector<SDValue, 4> Stores;
8840     for (unsigned i = 0; i < 4; ++i) {
8841       if (BVN->getOperand(i).isUndef()) continue;
8842 
8843       unsigned Offset = 4*i;
8844       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8845       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8846 
8847       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8848       if (StoreSize > 4) {
8849         Stores.push_back(
8850             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8851                               PtrInfo.getWithOffset(Offset), MVT::i32));
8852       } else {
8853         SDValue StoreValue = BVN->getOperand(i);
8854         if (StoreSize < 4)
8855           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8856 
8857         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8858                                       PtrInfo.getWithOffset(Offset)));
8859       }
8860     }
8861 
8862     SDValue StoreChain;
8863     if (!Stores.empty())
8864       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8865     else
8866       StoreChain = DAG.getEntryNode();
8867 
8868     // Now load from v4i32 into the QPX register; this will extend it to
8869     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8870     // is typed as v4f64 because the QPX register integer states are not
8871     // explicitly represented.
8872 
8873     SDValue Ops[] = {StoreChain,
8874                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8875                      FIdx};
8876     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8877 
8878     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8879       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8880     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8881       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8882       LoadedVect);
8883 
8884     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8885 
8886     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8887   }
8888 
8889   // All other QPX vectors are handled by generic code.
8890   if (Subtarget.hasQPX())
8891     return SDValue();
8892 
8893   // Check if this is a splat of a constant value.
8894   APInt APSplatBits, APSplatUndef;
8895   unsigned SplatBitSize;
8896   bool HasAnyUndefs;
8897   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8898                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8899       SplatBitSize > 32) {
8900 
8901     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8902     // Handle load-and-splat patterns as we have instructions that will do this
8903     // in one go.
8904     if (InputLoad && DAG.isSplatValue(Op, true)) {
8905       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8906 
8907       // We have handling for 4 and 8 byte elements.
8908       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8909 
8910       // Checking for a single use of this load, we have to check for vector
8911       // width (128 bits) / ElementSize uses (since each operand of the
8912       // BUILD_VECTOR is a separate use of the value.
8913       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8914           ((Subtarget.hasVSX() && ElementSize == 64) ||
8915            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8916         SDValue Ops[] = {
8917           LD->getChain(),    // Chain
8918           LD->getBasePtr(),  // Ptr
8919           DAG.getValueType(Op.getValueType()) // VT
8920         };
8921         return
8922           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8923                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8924                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8925       }
8926     }
8927 
8928     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8929     // lowered to VSX instructions under certain conditions.
8930     // Without VSX, there is no pattern more efficient than expanding the node.
8931     if (Subtarget.hasVSX() &&
8932         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8933                                         Subtarget.hasP8Vector()))
8934       return Op;
8935     return SDValue();
8936   }
8937 
8938   unsigned SplatBits = APSplatBits.getZExtValue();
8939   unsigned SplatUndef = APSplatUndef.getZExtValue();
8940   unsigned SplatSize = SplatBitSize / 8;
8941 
8942   // First, handle single instruction cases.
8943 
8944   // All zeros?
8945   if (SplatBits == 0) {
8946     // Canonicalize all zero vectors to be v4i32.
8947     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8948       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8949       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8950     }
8951     return Op;
8952   }
8953 
8954   // We have XXSPLTIB for constant splats one byte wide
8955   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
8956   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
8957   if (Subtarget.hasP9Vector() && SplatSize == 1)
8958     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
8959 
8960   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8961   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8962                     (32-SplatBitSize));
8963   if (SextVal >= -16 && SextVal <= 15)
8964     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8965 
8966   // Two instruction sequences.
8967 
8968   // If this value is in the range [-32,30] and is even, use:
8969   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8970   // If this value is in the range [17,31] and is odd, use:
8971   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8972   // If this value is in the range [-31,-17] and is odd, use:
8973   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8974   // Note the last two are three-instruction sequences.
8975   if (SextVal >= -32 && SextVal <= 31) {
8976     // To avoid having these optimizations undone by constant folding,
8977     // we convert to a pseudo that will be expanded later into one of
8978     // the above forms.
8979     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8980     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8981               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8982     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8983     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8984     if (VT == Op.getValueType())
8985       return RetVal;
8986     else
8987       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8988   }
8989 
8990   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8991   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8992   // for fneg/fabs.
8993   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8994     // Make -1 and vspltisw -1:
8995     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8996 
8997     // Make the VSLW intrinsic, computing 0x8000_0000.
8998     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8999                                    OnesV, DAG, dl);
9000 
9001     // xor by OnesV to invert it.
9002     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9003     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9004   }
9005 
9006   // Check to see if this is a wide variety of vsplti*, binop self cases.
9007   static const signed char SplatCsts[] = {
9008     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9009     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9010   };
9011 
9012   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9013     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9014     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9015     int i = SplatCsts[idx];
9016 
9017     // Figure out what shift amount will be used by altivec if shifted by i in
9018     // this splat size.
9019     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9020 
9021     // vsplti + shl self.
9022     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9023       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9024       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9025         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9026         Intrinsic::ppc_altivec_vslw
9027       };
9028       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9029       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9030     }
9031 
9032     // vsplti + srl self.
9033     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9034       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9035       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9036         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9037         Intrinsic::ppc_altivec_vsrw
9038       };
9039       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9040       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9041     }
9042 
9043     // vsplti + sra self.
9044     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9045       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9046       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9047         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9048         Intrinsic::ppc_altivec_vsraw
9049       };
9050       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9051       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9052     }
9053 
9054     // vsplti + rol self.
9055     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9056                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9057       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9058       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9059         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9060         Intrinsic::ppc_altivec_vrlw
9061       };
9062       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9063       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9064     }
9065 
9066     // t = vsplti c, result = vsldoi t, t, 1
9067     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9068       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9069       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9070       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9071     }
9072     // t = vsplti c, result = vsldoi t, t, 2
9073     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9074       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9075       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9076       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9077     }
9078     // t = vsplti c, result = vsldoi t, t, 3
9079     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9080       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9081       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9082       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9083     }
9084   }
9085 
9086   return SDValue();
9087 }
9088 
9089 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9090 /// the specified operations to build the shuffle.
9091 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9092                                       SDValue RHS, SelectionDAG &DAG,
9093                                       const SDLoc &dl) {
9094   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9095   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9096   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9097 
9098   enum {
9099     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9100     OP_VMRGHW,
9101     OP_VMRGLW,
9102     OP_VSPLTISW0,
9103     OP_VSPLTISW1,
9104     OP_VSPLTISW2,
9105     OP_VSPLTISW3,
9106     OP_VSLDOI4,
9107     OP_VSLDOI8,
9108     OP_VSLDOI12
9109   };
9110 
9111   if (OpNum == OP_COPY) {
9112     if (LHSID == (1*9+2)*9+3) return LHS;
9113     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9114     return RHS;
9115   }
9116 
9117   SDValue OpLHS, OpRHS;
9118   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9119   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9120 
9121   int ShufIdxs[16];
9122   switch (OpNum) {
9123   default: llvm_unreachable("Unknown i32 permute!");
9124   case OP_VMRGHW:
9125     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9126     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9127     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9128     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9129     break;
9130   case OP_VMRGLW:
9131     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9132     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9133     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9134     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9135     break;
9136   case OP_VSPLTISW0:
9137     for (unsigned i = 0; i != 16; ++i)
9138       ShufIdxs[i] = (i&3)+0;
9139     break;
9140   case OP_VSPLTISW1:
9141     for (unsigned i = 0; i != 16; ++i)
9142       ShufIdxs[i] = (i&3)+4;
9143     break;
9144   case OP_VSPLTISW2:
9145     for (unsigned i = 0; i != 16; ++i)
9146       ShufIdxs[i] = (i&3)+8;
9147     break;
9148   case OP_VSPLTISW3:
9149     for (unsigned i = 0; i != 16; ++i)
9150       ShufIdxs[i] = (i&3)+12;
9151     break;
9152   case OP_VSLDOI4:
9153     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9154   case OP_VSLDOI8:
9155     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9156   case OP_VSLDOI12:
9157     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9158   }
9159   EVT VT = OpLHS.getValueType();
9160   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9161   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9162   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9163   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9164 }
9165 
9166 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9167 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9168 /// SDValue.
9169 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9170                                            SelectionDAG &DAG) const {
9171   const unsigned BytesInVector = 16;
9172   bool IsLE = Subtarget.isLittleEndian();
9173   SDLoc dl(N);
9174   SDValue V1 = N->getOperand(0);
9175   SDValue V2 = N->getOperand(1);
9176   unsigned ShiftElts = 0, InsertAtByte = 0;
9177   bool Swap = false;
9178 
9179   // Shifts required to get the byte we want at element 7.
9180   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9181                                    0, 15, 14, 13, 12, 11, 10, 9};
9182   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9183                                 1, 2,  3,  4,  5,  6,  7,  8};
9184 
9185   ArrayRef<int> Mask = N->getMask();
9186   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9187 
9188   // For each mask element, find out if we're just inserting something
9189   // from V2 into V1 or vice versa.
9190   // Possible permutations inserting an element from V2 into V1:
9191   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9192   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9193   //   ...
9194   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9195   // Inserting from V1 into V2 will be similar, except mask range will be
9196   // [16,31].
9197 
9198   bool FoundCandidate = false;
9199   // If both vector operands for the shuffle are the same vector, the mask
9200   // will contain only elements from the first one and the second one will be
9201   // undef.
9202   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9203   // Go through the mask of half-words to find an element that's being moved
9204   // from one vector to the other.
9205   for (unsigned i = 0; i < BytesInVector; ++i) {
9206     unsigned CurrentElement = Mask[i];
9207     // If 2nd operand is undefined, we should only look for element 7 in the
9208     // Mask.
9209     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9210       continue;
9211 
9212     bool OtherElementsInOrder = true;
9213     // Examine the other elements in the Mask to see if they're in original
9214     // order.
9215     for (unsigned j = 0; j < BytesInVector; ++j) {
9216       if (j == i)
9217         continue;
9218       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9219       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9220       // in which we always assume we're always picking from the 1st operand.
9221       int MaskOffset =
9222           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9223       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9224         OtherElementsInOrder = false;
9225         break;
9226       }
9227     }
9228     // If other elements are in original order, we record the number of shifts
9229     // we need to get the element we want into element 7. Also record which byte
9230     // in the vector we should insert into.
9231     if (OtherElementsInOrder) {
9232       // If 2nd operand is undefined, we assume no shifts and no swapping.
9233       if (V2.isUndef()) {
9234         ShiftElts = 0;
9235         Swap = false;
9236       } else {
9237         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9238         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9239                          : BigEndianShifts[CurrentElement & 0xF];
9240         Swap = CurrentElement < BytesInVector;
9241       }
9242       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9243       FoundCandidate = true;
9244       break;
9245     }
9246   }
9247 
9248   if (!FoundCandidate)
9249     return SDValue();
9250 
9251   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9252   // optionally with VECSHL if shift is required.
9253   if (Swap)
9254     std::swap(V1, V2);
9255   if (V2.isUndef())
9256     V2 = V1;
9257   if (ShiftElts) {
9258     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9259                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9260     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9261                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9262   }
9263   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9264                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9265 }
9266 
9267 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9268 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9269 /// SDValue.
9270 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9271                                            SelectionDAG &DAG) const {
9272   const unsigned NumHalfWords = 8;
9273   const unsigned BytesInVector = NumHalfWords * 2;
9274   // Check that the shuffle is on half-words.
9275   if (!isNByteElemShuffleMask(N, 2, 1))
9276     return SDValue();
9277 
9278   bool IsLE = Subtarget.isLittleEndian();
9279   SDLoc dl(N);
9280   SDValue V1 = N->getOperand(0);
9281   SDValue V2 = N->getOperand(1);
9282   unsigned ShiftElts = 0, InsertAtByte = 0;
9283   bool Swap = false;
9284 
9285   // Shifts required to get the half-word we want at element 3.
9286   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9287   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9288 
9289   uint32_t Mask = 0;
9290   uint32_t OriginalOrderLow = 0x1234567;
9291   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9292   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9293   // 32-bit space, only need 4-bit nibbles per element.
9294   for (unsigned i = 0; i < NumHalfWords; ++i) {
9295     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9296     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9297   }
9298 
9299   // For each mask element, find out if we're just inserting something
9300   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9301   // from V2 into V1:
9302   //   X, 1, 2, 3, 4, 5, 6, 7
9303   //   0, X, 2, 3, 4, 5, 6, 7
9304   //   0, 1, X, 3, 4, 5, 6, 7
9305   //   0, 1, 2, X, 4, 5, 6, 7
9306   //   0, 1, 2, 3, X, 5, 6, 7
9307   //   0, 1, 2, 3, 4, X, 6, 7
9308   //   0, 1, 2, 3, 4, 5, X, 7
9309   //   0, 1, 2, 3, 4, 5, 6, X
9310   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9311 
9312   bool FoundCandidate = false;
9313   // Go through the mask of half-words to find an element that's being moved
9314   // from one vector to the other.
9315   for (unsigned i = 0; i < NumHalfWords; ++i) {
9316     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9317     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9318     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9319     uint32_t TargetOrder = 0x0;
9320 
9321     // If both vector operands for the shuffle are the same vector, the mask
9322     // will contain only elements from the first one and the second one will be
9323     // undef.
9324     if (V2.isUndef()) {
9325       ShiftElts = 0;
9326       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9327       TargetOrder = OriginalOrderLow;
9328       Swap = false;
9329       // Skip if not the correct element or mask of other elements don't equal
9330       // to our expected order.
9331       if (MaskOneElt == VINSERTHSrcElem &&
9332           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9333         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9334         FoundCandidate = true;
9335         break;
9336       }
9337     } else { // If both operands are defined.
9338       // Target order is [8,15] if the current mask is between [0,7].
9339       TargetOrder =
9340           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9341       // Skip if mask of other elements don't equal our expected order.
9342       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9343         // We only need the last 3 bits for the number of shifts.
9344         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9345                          : BigEndianShifts[MaskOneElt & 0x7];
9346         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9347         Swap = MaskOneElt < NumHalfWords;
9348         FoundCandidate = true;
9349         break;
9350       }
9351     }
9352   }
9353 
9354   if (!FoundCandidate)
9355     return SDValue();
9356 
9357   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9358   // optionally with VECSHL if shift is required.
9359   if (Swap)
9360     std::swap(V1, V2);
9361   if (V2.isUndef())
9362     V2 = V1;
9363   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9364   if (ShiftElts) {
9365     // Double ShiftElts because we're left shifting on v16i8 type.
9366     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9367                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9368     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9369     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9370                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9371     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9372   }
9373   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9374   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9375                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9376   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9377 }
9378 
9379 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9380 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9381 /// return the code it can be lowered into.  Worst case, it can always be
9382 /// lowered into a vperm.
9383 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9384                                                SelectionDAG &DAG) const {
9385   SDLoc dl(Op);
9386   SDValue V1 = Op.getOperand(0);
9387   SDValue V2 = Op.getOperand(1);
9388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9389   EVT VT = Op.getValueType();
9390   bool isLittleEndian = Subtarget.isLittleEndian();
9391 
9392   unsigned ShiftElts, InsertAtByte;
9393   bool Swap = false;
9394 
9395   // If this is a load-and-splat, we can do that with a single instruction
9396   // in some cases. However if the load has multiple uses, we don't want to
9397   // combine it because that will just produce multiple loads.
9398   const SDValue *InputLoad = getNormalLoadInput(V1);
9399   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9400       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9401       InputLoad->hasOneUse()) {
9402     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9403     int SplatIdx =
9404       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9405 
9406     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9407     // For 4-byte load-and-splat, we need Power9.
9408     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9409       uint64_t Offset = 0;
9410       if (IsFourByte)
9411         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9412       else
9413         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9414       SDValue BasePtr = LD->getBasePtr();
9415       if (Offset != 0)
9416         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9417                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9418       SDValue Ops[] = {
9419         LD->getChain(),    // Chain
9420         BasePtr,           // BasePtr
9421         DAG.getValueType(Op.getValueType()) // VT
9422       };
9423       SDVTList VTL =
9424         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9425       SDValue LdSplt =
9426         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9427                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9428       if (LdSplt.getValueType() != SVOp->getValueType(0))
9429         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9430       return LdSplt;
9431     }
9432   }
9433   if (Subtarget.hasP9Vector() &&
9434       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9435                            isLittleEndian)) {
9436     if (Swap)
9437       std::swap(V1, V2);
9438     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9439     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9440     if (ShiftElts) {
9441       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9442                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9443       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9444                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9445       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9446     }
9447     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9448                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9449     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9450   }
9451 
9452   if (Subtarget.hasP9Altivec()) {
9453     SDValue NewISDNode;
9454     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9455       return NewISDNode;
9456 
9457     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9458       return NewISDNode;
9459   }
9460 
9461   if (Subtarget.hasVSX() &&
9462       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9463     if (Swap)
9464       std::swap(V1, V2);
9465     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9466     SDValue Conv2 =
9467         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9468 
9469     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9470                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9471     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9472   }
9473 
9474   if (Subtarget.hasVSX() &&
9475     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9476     if (Swap)
9477       std::swap(V1, V2);
9478     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9479     SDValue Conv2 =
9480         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9481 
9482     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9483                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9484     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9485   }
9486 
9487   if (Subtarget.hasP9Vector()) {
9488      if (PPC::isXXBRHShuffleMask(SVOp)) {
9489       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9490       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9491       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9492     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9493       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9494       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9495       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9496     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9497       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9498       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9499       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9500     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9501       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9502       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9503       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9504     }
9505   }
9506 
9507   if (Subtarget.hasVSX()) {
9508     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9509       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9510 
9511       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9512       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9513                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9514       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9515     }
9516 
9517     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9518     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9519       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9520       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9521       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9522     }
9523   }
9524 
9525   if (Subtarget.hasQPX()) {
9526     if (VT.getVectorNumElements() != 4)
9527       return SDValue();
9528 
9529     if (V2.isUndef()) V2 = V1;
9530 
9531     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9532     if (AlignIdx != -1) {
9533       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9534                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9535     } else if (SVOp->isSplat()) {
9536       int SplatIdx = SVOp->getSplatIndex();
9537       if (SplatIdx >= 4) {
9538         std::swap(V1, V2);
9539         SplatIdx -= 4;
9540       }
9541 
9542       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9543                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9544     }
9545 
9546     // Lower this into a qvgpci/qvfperm pair.
9547 
9548     // Compute the qvgpci literal
9549     unsigned idx = 0;
9550     for (unsigned i = 0; i < 4; ++i) {
9551       int m = SVOp->getMaskElt(i);
9552       unsigned mm = m >= 0 ? (unsigned) m : i;
9553       idx |= mm << (3-i)*3;
9554     }
9555 
9556     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9557                              DAG.getConstant(idx, dl, MVT::i32));
9558     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9559   }
9560 
9561   // Cases that are handled by instructions that take permute immediates
9562   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9563   // selected by the instruction selector.
9564   if (V2.isUndef()) {
9565     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9566         PPC::isSplatShuffleMask(SVOp, 2) ||
9567         PPC::isSplatShuffleMask(SVOp, 4) ||
9568         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9569         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9570         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9571         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9572         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9573         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9574         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9575         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9576         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9577         (Subtarget.hasP8Altivec() && (
9578          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9579          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9580          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9581       return Op;
9582     }
9583   }
9584 
9585   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9586   // and produce a fixed permutation.  If any of these match, do not lower to
9587   // VPERM.
9588   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9589   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9590       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9591       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9592       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9593       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9594       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9595       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9596       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9597       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9598       (Subtarget.hasP8Altivec() && (
9599        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9600        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9601        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9602     return Op;
9603 
9604   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9605   // perfect shuffle table to emit an optimal matching sequence.
9606   ArrayRef<int> PermMask = SVOp->getMask();
9607 
9608   unsigned PFIndexes[4];
9609   bool isFourElementShuffle = true;
9610   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9611     unsigned EltNo = 8;   // Start out undef.
9612     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9613       if (PermMask[i*4+j] < 0)
9614         continue;   // Undef, ignore it.
9615 
9616       unsigned ByteSource = PermMask[i*4+j];
9617       if ((ByteSource & 3) != j) {
9618         isFourElementShuffle = false;
9619         break;
9620       }
9621 
9622       if (EltNo == 8) {
9623         EltNo = ByteSource/4;
9624       } else if (EltNo != ByteSource/4) {
9625         isFourElementShuffle = false;
9626         break;
9627       }
9628     }
9629     PFIndexes[i] = EltNo;
9630   }
9631 
9632   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9633   // perfect shuffle vector to determine if it is cost effective to do this as
9634   // discrete instructions, or whether we should use a vperm.
9635   // For now, we skip this for little endian until such time as we have a
9636   // little-endian perfect shuffle table.
9637   if (isFourElementShuffle && !isLittleEndian) {
9638     // Compute the index in the perfect shuffle table.
9639     unsigned PFTableIndex =
9640       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9641 
9642     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9643     unsigned Cost  = (PFEntry >> 30);
9644 
9645     // Determining when to avoid vperm is tricky.  Many things affect the cost
9646     // of vperm, particularly how many times the perm mask needs to be computed.
9647     // For example, if the perm mask can be hoisted out of a loop or is already
9648     // used (perhaps because there are multiple permutes with the same shuffle
9649     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9650     // the loop requires an extra register.
9651     //
9652     // As a compromise, we only emit discrete instructions if the shuffle can be
9653     // generated in 3 or fewer operations.  When we have loop information
9654     // available, if this block is within a loop, we should avoid using vperm
9655     // for 3-operation perms and use a constant pool load instead.
9656     if (Cost < 3)
9657       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9658   }
9659 
9660   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9661   // vector that will get spilled to the constant pool.
9662   if (V2.isUndef()) V2 = V1;
9663 
9664   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9665   // that it is in input element units, not in bytes.  Convert now.
9666 
9667   // For little endian, the order of the input vectors is reversed, and
9668   // the permutation mask is complemented with respect to 31.  This is
9669   // necessary to produce proper semantics with the big-endian-biased vperm
9670   // instruction.
9671   EVT EltVT = V1.getValueType().getVectorElementType();
9672   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9673 
9674   SmallVector<SDValue, 16> ResultMask;
9675   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9676     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9677 
9678     for (unsigned j = 0; j != BytesPerElement; ++j)
9679       if (isLittleEndian)
9680         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9681                                              dl, MVT::i32));
9682       else
9683         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9684                                              MVT::i32));
9685   }
9686 
9687   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9688   if (isLittleEndian)
9689     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9690                        V2, V1, VPermMask);
9691   else
9692     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9693                        V1, V2, VPermMask);
9694 }
9695 
9696 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9697 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9698 /// information about the intrinsic.
9699 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9700                                  bool &isDot, const PPCSubtarget &Subtarget) {
9701   unsigned IntrinsicID =
9702       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9703   CompareOpc = -1;
9704   isDot = false;
9705   switch (IntrinsicID) {
9706   default:
9707     return false;
9708   // Comparison predicates.
9709   case Intrinsic::ppc_altivec_vcmpbfp_p:
9710     CompareOpc = 966;
9711     isDot = true;
9712     break;
9713   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9714     CompareOpc = 198;
9715     isDot = true;
9716     break;
9717   case Intrinsic::ppc_altivec_vcmpequb_p:
9718     CompareOpc = 6;
9719     isDot = true;
9720     break;
9721   case Intrinsic::ppc_altivec_vcmpequh_p:
9722     CompareOpc = 70;
9723     isDot = true;
9724     break;
9725   case Intrinsic::ppc_altivec_vcmpequw_p:
9726     CompareOpc = 134;
9727     isDot = true;
9728     break;
9729   case Intrinsic::ppc_altivec_vcmpequd_p:
9730     if (Subtarget.hasP8Altivec()) {
9731       CompareOpc = 199;
9732       isDot = true;
9733     } else
9734       return false;
9735     break;
9736   case Intrinsic::ppc_altivec_vcmpneb_p:
9737   case Intrinsic::ppc_altivec_vcmpneh_p:
9738   case Intrinsic::ppc_altivec_vcmpnew_p:
9739   case Intrinsic::ppc_altivec_vcmpnezb_p:
9740   case Intrinsic::ppc_altivec_vcmpnezh_p:
9741   case Intrinsic::ppc_altivec_vcmpnezw_p:
9742     if (Subtarget.hasP9Altivec()) {
9743       switch (IntrinsicID) {
9744       default:
9745         llvm_unreachable("Unknown comparison intrinsic.");
9746       case Intrinsic::ppc_altivec_vcmpneb_p:
9747         CompareOpc = 7;
9748         break;
9749       case Intrinsic::ppc_altivec_vcmpneh_p:
9750         CompareOpc = 71;
9751         break;
9752       case Intrinsic::ppc_altivec_vcmpnew_p:
9753         CompareOpc = 135;
9754         break;
9755       case Intrinsic::ppc_altivec_vcmpnezb_p:
9756         CompareOpc = 263;
9757         break;
9758       case Intrinsic::ppc_altivec_vcmpnezh_p:
9759         CompareOpc = 327;
9760         break;
9761       case Intrinsic::ppc_altivec_vcmpnezw_p:
9762         CompareOpc = 391;
9763         break;
9764       }
9765       isDot = true;
9766     } else
9767       return false;
9768     break;
9769   case Intrinsic::ppc_altivec_vcmpgefp_p:
9770     CompareOpc = 454;
9771     isDot = true;
9772     break;
9773   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9774     CompareOpc = 710;
9775     isDot = true;
9776     break;
9777   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9778     CompareOpc = 774;
9779     isDot = true;
9780     break;
9781   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9782     CompareOpc = 838;
9783     isDot = true;
9784     break;
9785   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9786     CompareOpc = 902;
9787     isDot = true;
9788     break;
9789   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9790     if (Subtarget.hasP8Altivec()) {
9791       CompareOpc = 967;
9792       isDot = true;
9793     } else
9794       return false;
9795     break;
9796   case Intrinsic::ppc_altivec_vcmpgtub_p:
9797     CompareOpc = 518;
9798     isDot = true;
9799     break;
9800   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9801     CompareOpc = 582;
9802     isDot = true;
9803     break;
9804   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9805     CompareOpc = 646;
9806     isDot = true;
9807     break;
9808   case Intrinsic::ppc_altivec_vcmpgtud_p:
9809     if (Subtarget.hasP8Altivec()) {
9810       CompareOpc = 711;
9811       isDot = true;
9812     } else
9813       return false;
9814     break;
9815 
9816   // VSX predicate comparisons use the same infrastructure
9817   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9818   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9819   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9820   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9821   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9822   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9823     if (Subtarget.hasVSX()) {
9824       switch (IntrinsicID) {
9825       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9826         CompareOpc = 99;
9827         break;
9828       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9829         CompareOpc = 115;
9830         break;
9831       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9832         CompareOpc = 107;
9833         break;
9834       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9835         CompareOpc = 67;
9836         break;
9837       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9838         CompareOpc = 83;
9839         break;
9840       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9841         CompareOpc = 75;
9842         break;
9843       }
9844       isDot = true;
9845     } else
9846       return false;
9847     break;
9848 
9849   // Normal Comparisons.
9850   case Intrinsic::ppc_altivec_vcmpbfp:
9851     CompareOpc = 966;
9852     break;
9853   case Intrinsic::ppc_altivec_vcmpeqfp:
9854     CompareOpc = 198;
9855     break;
9856   case Intrinsic::ppc_altivec_vcmpequb:
9857     CompareOpc = 6;
9858     break;
9859   case Intrinsic::ppc_altivec_vcmpequh:
9860     CompareOpc = 70;
9861     break;
9862   case Intrinsic::ppc_altivec_vcmpequw:
9863     CompareOpc = 134;
9864     break;
9865   case Intrinsic::ppc_altivec_vcmpequd:
9866     if (Subtarget.hasP8Altivec())
9867       CompareOpc = 199;
9868     else
9869       return false;
9870     break;
9871   case Intrinsic::ppc_altivec_vcmpneb:
9872   case Intrinsic::ppc_altivec_vcmpneh:
9873   case Intrinsic::ppc_altivec_vcmpnew:
9874   case Intrinsic::ppc_altivec_vcmpnezb:
9875   case Intrinsic::ppc_altivec_vcmpnezh:
9876   case Intrinsic::ppc_altivec_vcmpnezw:
9877     if (Subtarget.hasP9Altivec())
9878       switch (IntrinsicID) {
9879       default:
9880         llvm_unreachable("Unknown comparison intrinsic.");
9881       case Intrinsic::ppc_altivec_vcmpneb:
9882         CompareOpc = 7;
9883         break;
9884       case Intrinsic::ppc_altivec_vcmpneh:
9885         CompareOpc = 71;
9886         break;
9887       case Intrinsic::ppc_altivec_vcmpnew:
9888         CompareOpc = 135;
9889         break;
9890       case Intrinsic::ppc_altivec_vcmpnezb:
9891         CompareOpc = 263;
9892         break;
9893       case Intrinsic::ppc_altivec_vcmpnezh:
9894         CompareOpc = 327;
9895         break;
9896       case Intrinsic::ppc_altivec_vcmpnezw:
9897         CompareOpc = 391;
9898         break;
9899       }
9900     else
9901       return false;
9902     break;
9903   case Intrinsic::ppc_altivec_vcmpgefp:
9904     CompareOpc = 454;
9905     break;
9906   case Intrinsic::ppc_altivec_vcmpgtfp:
9907     CompareOpc = 710;
9908     break;
9909   case Intrinsic::ppc_altivec_vcmpgtsb:
9910     CompareOpc = 774;
9911     break;
9912   case Intrinsic::ppc_altivec_vcmpgtsh:
9913     CompareOpc = 838;
9914     break;
9915   case Intrinsic::ppc_altivec_vcmpgtsw:
9916     CompareOpc = 902;
9917     break;
9918   case Intrinsic::ppc_altivec_vcmpgtsd:
9919     if (Subtarget.hasP8Altivec())
9920       CompareOpc = 967;
9921     else
9922       return false;
9923     break;
9924   case Intrinsic::ppc_altivec_vcmpgtub:
9925     CompareOpc = 518;
9926     break;
9927   case Intrinsic::ppc_altivec_vcmpgtuh:
9928     CompareOpc = 582;
9929     break;
9930   case Intrinsic::ppc_altivec_vcmpgtuw:
9931     CompareOpc = 646;
9932     break;
9933   case Intrinsic::ppc_altivec_vcmpgtud:
9934     if (Subtarget.hasP8Altivec())
9935       CompareOpc = 711;
9936     else
9937       return false;
9938     break;
9939   }
9940   return true;
9941 }
9942 
9943 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9944 /// lower, do it, otherwise return null.
9945 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9946                                                    SelectionDAG &DAG) const {
9947   unsigned IntrinsicID =
9948     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9949 
9950   SDLoc dl(Op);
9951 
9952   if (IntrinsicID == Intrinsic::thread_pointer) {
9953     // Reads the thread pointer register, used for __builtin_thread_pointer.
9954     if (Subtarget.isPPC64())
9955       return DAG.getRegister(PPC::X13, MVT::i64);
9956     return DAG.getRegister(PPC::R2, MVT::i32);
9957   }
9958 
9959   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9960   // opcode number of the comparison.
9961   int CompareOpc;
9962   bool isDot;
9963   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9964     return SDValue();    // Don't custom lower most intrinsics.
9965 
9966   // If this is a non-dot comparison, make the VCMP node and we are done.
9967   if (!isDot) {
9968     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9969                               Op.getOperand(1), Op.getOperand(2),
9970                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9971     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9972   }
9973 
9974   // Create the PPCISD altivec 'dot' comparison node.
9975   SDValue Ops[] = {
9976     Op.getOperand(2),  // LHS
9977     Op.getOperand(3),  // RHS
9978     DAG.getConstant(CompareOpc, dl, MVT::i32)
9979   };
9980   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9981   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9982 
9983   // Now that we have the comparison, emit a copy from the CR to a GPR.
9984   // This is flagged to the above dot comparison.
9985   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9986                                 DAG.getRegister(PPC::CR6, MVT::i32),
9987                                 CompNode.getValue(1));
9988 
9989   // Unpack the result based on how the target uses it.
9990   unsigned BitNo;   // Bit # of CR6.
9991   bool InvertBit;   // Invert result?
9992   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9993   default:  // Can't happen, don't crash on invalid number though.
9994   case 0:   // Return the value of the EQ bit of CR6.
9995     BitNo = 0; InvertBit = false;
9996     break;
9997   case 1:   // Return the inverted value of the EQ bit of CR6.
9998     BitNo = 0; InvertBit = true;
9999     break;
10000   case 2:   // Return the value of the LT bit of CR6.
10001     BitNo = 2; InvertBit = false;
10002     break;
10003   case 3:   // Return the inverted value of the LT bit of CR6.
10004     BitNo = 2; InvertBit = true;
10005     break;
10006   }
10007 
10008   // Shift the bit into the low position.
10009   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10010                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10011   // Isolate the bit.
10012   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10013                       DAG.getConstant(1, dl, MVT::i32));
10014 
10015   // If we are supposed to, toggle the bit.
10016   if (InvertBit)
10017     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10018                         DAG.getConstant(1, dl, MVT::i32));
10019   return Flags;
10020 }
10021 
10022 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10023                                                SelectionDAG &DAG) const {
10024   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10025   // the beginning of the argument list.
10026   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10027   SDLoc DL(Op);
10028   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10029   case Intrinsic::ppc_cfence: {
10030     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10031     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10032     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10033                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10034                                                   Op.getOperand(ArgStart + 1)),
10035                                       Op.getOperand(0)),
10036                    0);
10037   }
10038   default:
10039     break;
10040   }
10041   return SDValue();
10042 }
10043 
10044 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10045   // Check for a DIV with the same operands as this REM.
10046   for (auto UI : Op.getOperand(1)->uses()) {
10047     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10048         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10049       if (UI->getOperand(0) == Op.getOperand(0) &&
10050           UI->getOperand(1) == Op.getOperand(1))
10051         return SDValue();
10052   }
10053   return Op;
10054 }
10055 
10056 // Lower scalar BSWAP64 to xxbrd.
10057 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10058   SDLoc dl(Op);
10059   // MTVSRDD
10060   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10061                    Op.getOperand(0));
10062   // XXBRD
10063   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10064   // MFVSRD
10065   int VectorIndex = 0;
10066   if (Subtarget.isLittleEndian())
10067     VectorIndex = 1;
10068   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10069                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10070   return Op;
10071 }
10072 
10073 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10074 // compared to a value that is atomically loaded (atomic loads zero-extend).
10075 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10076                                                 SelectionDAG &DAG) const {
10077   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10078          "Expecting an atomic compare-and-swap here.");
10079   SDLoc dl(Op);
10080   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10081   EVT MemVT = AtomicNode->getMemoryVT();
10082   if (MemVT.getSizeInBits() >= 32)
10083     return Op;
10084 
10085   SDValue CmpOp = Op.getOperand(2);
10086   // If this is already correctly zero-extended, leave it alone.
10087   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10088   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10089     return Op;
10090 
10091   // Clear the high bits of the compare operand.
10092   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10093   SDValue NewCmpOp =
10094     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10095                 DAG.getConstant(MaskVal, dl, MVT::i32));
10096 
10097   // Replace the existing compare operand with the properly zero-extended one.
10098   SmallVector<SDValue, 4> Ops;
10099   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10100     Ops.push_back(AtomicNode->getOperand(i));
10101   Ops[2] = NewCmpOp;
10102   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10103   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10104   auto NodeTy =
10105     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10106   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10107 }
10108 
10109 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10110                                                  SelectionDAG &DAG) const {
10111   SDLoc dl(Op);
10112   // Create a stack slot that is 16-byte aligned.
10113   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10114   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10115   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10116   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10117 
10118   // Store the input value into Value#0 of the stack slot.
10119   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10120                                MachinePointerInfo());
10121   // Load it out.
10122   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10123 }
10124 
10125 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10126                                                   SelectionDAG &DAG) const {
10127   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10128          "Should only be called for ISD::INSERT_VECTOR_ELT");
10129 
10130   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10131   // We have legal lowering for constant indices but not for variable ones.
10132   if (!C)
10133     return SDValue();
10134 
10135   EVT VT = Op.getValueType();
10136   SDLoc dl(Op);
10137   SDValue V1 = Op.getOperand(0);
10138   SDValue V2 = Op.getOperand(1);
10139   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10140   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10141     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10142     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10143     unsigned InsertAtElement = C->getZExtValue();
10144     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10145     if (Subtarget.isLittleEndian()) {
10146       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10147     }
10148     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10149                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10150   }
10151   return Op;
10152 }
10153 
10154 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10155                                                    SelectionDAG &DAG) const {
10156   SDLoc dl(Op);
10157   SDNode *N = Op.getNode();
10158 
10159   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10160          "Unknown extract_vector_elt type");
10161 
10162   SDValue Value = N->getOperand(0);
10163 
10164   // The first part of this is like the store lowering except that we don't
10165   // need to track the chain.
10166 
10167   // The values are now known to be -1 (false) or 1 (true). To convert this
10168   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10169   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10170   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10171 
10172   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10173   // understand how to form the extending load.
10174   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10175 
10176   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10177 
10178   // Now convert to an integer and store.
10179   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10180     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10181     Value);
10182 
10183   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10184   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10185   MachinePointerInfo PtrInfo =
10186       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10187   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10188   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10189 
10190   SDValue StoreChain = DAG.getEntryNode();
10191   SDValue Ops[] = {StoreChain,
10192                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10193                    Value, FIdx};
10194   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10195 
10196   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10197     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10198 
10199   // Extract the value requested.
10200   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10201   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10202   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10203 
10204   SDValue IntVal =
10205       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10206 
10207   if (!Subtarget.useCRBits())
10208     return IntVal;
10209 
10210   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10211 }
10212 
10213 /// Lowering for QPX v4i1 loads
10214 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10215                                            SelectionDAG &DAG) const {
10216   SDLoc dl(Op);
10217   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10218   SDValue LoadChain = LN->getChain();
10219   SDValue BasePtr = LN->getBasePtr();
10220 
10221   if (Op.getValueType() == MVT::v4f64 ||
10222       Op.getValueType() == MVT::v4f32) {
10223     EVT MemVT = LN->getMemoryVT();
10224     unsigned Alignment = LN->getAlignment();
10225 
10226     // If this load is properly aligned, then it is legal.
10227     if (Alignment >= MemVT.getStoreSize())
10228       return Op;
10229 
10230     EVT ScalarVT = Op.getValueType().getScalarType(),
10231         ScalarMemVT = MemVT.getScalarType();
10232     unsigned Stride = ScalarMemVT.getStoreSize();
10233 
10234     SDValue Vals[4], LoadChains[4];
10235     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10236       SDValue Load;
10237       if (ScalarVT != ScalarMemVT)
10238         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10239                               BasePtr,
10240                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10241                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10242                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10243       else
10244         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10245                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10246                            MinAlign(Alignment, Idx * Stride),
10247                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10248 
10249       if (Idx == 0 && LN->isIndexed()) {
10250         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10251                "Unknown addressing mode on vector load");
10252         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10253                                   LN->getAddressingMode());
10254       }
10255 
10256       Vals[Idx] = Load;
10257       LoadChains[Idx] = Load.getValue(1);
10258 
10259       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10260                             DAG.getConstant(Stride, dl,
10261                                             BasePtr.getValueType()));
10262     }
10263 
10264     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10265     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10266 
10267     if (LN->isIndexed()) {
10268       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10269       return DAG.getMergeValues(RetOps, dl);
10270     }
10271 
10272     SDValue RetOps[] = { Value, TF };
10273     return DAG.getMergeValues(RetOps, dl);
10274   }
10275 
10276   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10277   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10278 
10279   // To lower v4i1 from a byte array, we load the byte elements of the
10280   // vector and then reuse the BUILD_VECTOR logic.
10281 
10282   SDValue VectElmts[4], VectElmtChains[4];
10283   for (unsigned i = 0; i < 4; ++i) {
10284     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10285     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10286 
10287     VectElmts[i] = DAG.getExtLoad(
10288         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10289         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10290         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10291     VectElmtChains[i] = VectElmts[i].getValue(1);
10292   }
10293 
10294   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10295   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10296 
10297   SDValue RVals[] = { Value, LoadChain };
10298   return DAG.getMergeValues(RVals, dl);
10299 }
10300 
10301 /// Lowering for QPX v4i1 stores
10302 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10303                                             SelectionDAG &DAG) const {
10304   SDLoc dl(Op);
10305   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10306   SDValue StoreChain = SN->getChain();
10307   SDValue BasePtr = SN->getBasePtr();
10308   SDValue Value = SN->getValue();
10309 
10310   if (Value.getValueType() == MVT::v4f64 ||
10311       Value.getValueType() == MVT::v4f32) {
10312     EVT MemVT = SN->getMemoryVT();
10313     unsigned Alignment = SN->getAlignment();
10314 
10315     // If this store is properly aligned, then it is legal.
10316     if (Alignment >= MemVT.getStoreSize())
10317       return Op;
10318 
10319     EVT ScalarVT = Value.getValueType().getScalarType(),
10320         ScalarMemVT = MemVT.getScalarType();
10321     unsigned Stride = ScalarMemVT.getStoreSize();
10322 
10323     SDValue Stores[4];
10324     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10325       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10326                                DAG.getVectorIdxConstant(Idx, dl));
10327       SDValue Store;
10328       if (ScalarVT != ScalarMemVT)
10329         Store =
10330             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10331                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10332                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10333                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10334       else
10335         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10336                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10337                              MinAlign(Alignment, Idx * Stride),
10338                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10339 
10340       if (Idx == 0 && SN->isIndexed()) {
10341         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10342                "Unknown addressing mode on vector store");
10343         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10344                                     SN->getAddressingMode());
10345       }
10346 
10347       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10348                             DAG.getConstant(Stride, dl,
10349                                             BasePtr.getValueType()));
10350       Stores[Idx] = Store;
10351     }
10352 
10353     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10354 
10355     if (SN->isIndexed()) {
10356       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10357       return DAG.getMergeValues(RetOps, dl);
10358     }
10359 
10360     return TF;
10361   }
10362 
10363   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10364   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10365 
10366   // The values are now known to be -1 (false) or 1 (true). To convert this
10367   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10368   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10369   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10370 
10371   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10372   // understand how to form the extending load.
10373   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10374 
10375   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10376 
10377   // Now convert to an integer and store.
10378   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10379     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10380     Value);
10381 
10382   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10383   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10384   MachinePointerInfo PtrInfo =
10385       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10386   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10387   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10388 
10389   SDValue Ops[] = {StoreChain,
10390                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10391                    Value, FIdx};
10392   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10393 
10394   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10395     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10396 
10397   // Move data into the byte array.
10398   SDValue Loads[4], LoadChains[4];
10399   for (unsigned i = 0; i < 4; ++i) {
10400     unsigned Offset = 4*i;
10401     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10402     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10403 
10404     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10405                            PtrInfo.getWithOffset(Offset));
10406     LoadChains[i] = Loads[i].getValue(1);
10407   }
10408 
10409   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10410 
10411   SDValue Stores[4];
10412   for (unsigned i = 0; i < 4; ++i) {
10413     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10414     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10415 
10416     Stores[i] = DAG.getTruncStore(
10417         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10418         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10419         SN->getAAInfo());
10420   }
10421 
10422   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10423 
10424   return StoreChain;
10425 }
10426 
10427 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10428   SDLoc dl(Op);
10429   if (Op.getValueType() == MVT::v4i32) {
10430     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10431 
10432     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10433     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10434 
10435     SDValue RHSSwap =   // = vrlw RHS, 16
10436       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10437 
10438     // Shrinkify inputs to v8i16.
10439     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10440     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10441     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10442 
10443     // Low parts multiplied together, generating 32-bit results (we ignore the
10444     // top parts).
10445     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10446                                         LHS, RHS, DAG, dl, MVT::v4i32);
10447 
10448     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10449                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10450     // Shift the high parts up 16 bits.
10451     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10452                               Neg16, DAG, dl);
10453     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10454   } else if (Op.getValueType() == MVT::v16i8) {
10455     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10456     bool isLittleEndian = Subtarget.isLittleEndian();
10457 
10458     // Multiply the even 8-bit parts, producing 16-bit sums.
10459     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10460                                            LHS, RHS, DAG, dl, MVT::v8i16);
10461     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10462 
10463     // Multiply the odd 8-bit parts, producing 16-bit sums.
10464     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10465                                           LHS, RHS, DAG, dl, MVT::v8i16);
10466     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10467 
10468     // Merge the results together.  Because vmuleub and vmuloub are
10469     // instructions with a big-endian bias, we must reverse the
10470     // element numbering and reverse the meaning of "odd" and "even"
10471     // when generating little endian code.
10472     int Ops[16];
10473     for (unsigned i = 0; i != 8; ++i) {
10474       if (isLittleEndian) {
10475         Ops[i*2  ] = 2*i;
10476         Ops[i*2+1] = 2*i+16;
10477       } else {
10478         Ops[i*2  ] = 2*i+1;
10479         Ops[i*2+1] = 2*i+1+16;
10480       }
10481     }
10482     if (isLittleEndian)
10483       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10484     else
10485       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10486   } else {
10487     llvm_unreachable("Unknown mul to lower!");
10488   }
10489 }
10490 
10491 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10492 
10493   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10494 
10495   EVT VT = Op.getValueType();
10496   assert(VT.isVector() &&
10497          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10498   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10499           VT == MVT::v16i8) &&
10500          "Unexpected vector element type!");
10501   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10502          "Current subtarget doesn't support smax v2i64!");
10503 
10504   // For vector abs, it can be lowered to:
10505   // abs x
10506   // ==>
10507   // y = -x
10508   // smax(x, y)
10509 
10510   SDLoc dl(Op);
10511   SDValue X = Op.getOperand(0);
10512   SDValue Zero = DAG.getConstant(0, dl, VT);
10513   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10514 
10515   // SMAX patch https://reviews.llvm.org/D47332
10516   // hasn't landed yet, so use intrinsic first here.
10517   // TODO: Should use SMAX directly once SMAX patch landed
10518   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10519   if (VT == MVT::v2i64)
10520     BifID = Intrinsic::ppc_altivec_vmaxsd;
10521   else if (VT == MVT::v8i16)
10522     BifID = Intrinsic::ppc_altivec_vmaxsh;
10523   else if (VT == MVT::v16i8)
10524     BifID = Intrinsic::ppc_altivec_vmaxsb;
10525 
10526   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10527 }
10528 
10529 // Custom lowering for fpext vf32 to v2f64
10530 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10531 
10532   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10533          "Should only be called for ISD::FP_EXTEND");
10534 
10535   // We only want to custom lower an extend from v2f32 to v2f64.
10536   if (Op.getValueType() != MVT::v2f64 ||
10537       Op.getOperand(0).getValueType() != MVT::v2f32)
10538     return SDValue();
10539 
10540   SDLoc dl(Op);
10541   SDValue Op0 = Op.getOperand(0);
10542 
10543   switch (Op0.getOpcode()) {
10544   default:
10545     return SDValue();
10546   case ISD::EXTRACT_SUBVECTOR: {
10547     assert(Op0.getNumOperands() == 2 &&
10548            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10549            "Node should have 2 operands with second one being a constant!");
10550 
10551     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10552       return SDValue();
10553 
10554     // Custom lower is only done for high or low doubleword.
10555     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10556     if (Idx % 2 != 0)
10557       return SDValue();
10558 
10559     // Since input is v4f32, at this point Idx is either 0 or 2.
10560     // Shift to get the doubleword position we want.
10561     int DWord = Idx >> 1;
10562 
10563     // High and low word positions are different on little endian.
10564     if (Subtarget.isLittleEndian())
10565       DWord ^= 0x1;
10566 
10567     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10568                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10569   }
10570   case ISD::FADD:
10571   case ISD::FMUL:
10572   case ISD::FSUB: {
10573     SDValue NewLoad[2];
10574     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10575       // Ensure both input are loads.
10576       SDValue LdOp = Op0.getOperand(i);
10577       if (LdOp.getOpcode() != ISD::LOAD)
10578         return SDValue();
10579       // Generate new load node.
10580       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10581       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10582       NewLoad[i] = DAG.getMemIntrinsicNode(
10583           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10584           LD->getMemoryVT(), LD->getMemOperand());
10585     }
10586     SDValue NewOp =
10587         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10588                     NewLoad[1], Op0.getNode()->getFlags());
10589     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10590                        DAG.getConstant(0, dl, MVT::i32));
10591   }
10592   case ISD::LOAD: {
10593     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10594     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10595     SDValue NewLd = DAG.getMemIntrinsicNode(
10596         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10597         LD->getMemoryVT(), LD->getMemOperand());
10598     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10599                        DAG.getConstant(0, dl, MVT::i32));
10600   }
10601   }
10602   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10603 }
10604 
10605 /// LowerOperation - Provide custom lowering hooks for some operations.
10606 ///
10607 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10608   switch (Op.getOpcode()) {
10609   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10610   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10611   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10612   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10613   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10614   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10615   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10616   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10617   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10618 
10619   // Variable argument lowering.
10620   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10621   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10622   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10623 
10624   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10625   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10626   case ISD::GET_DYNAMIC_AREA_OFFSET:
10627     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10628 
10629   // Exception handling lowering.
10630   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10631   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10632   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10633 
10634   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10635   case ISD::STORE:              return LowerSTORE(Op, DAG);
10636   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10637   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10638   case ISD::FP_TO_UINT:
10639   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10640   case ISD::UINT_TO_FP:
10641   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10642   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10643 
10644   // Lower 64-bit shifts.
10645   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10646   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10647   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10648 
10649   // Vector-related lowering.
10650   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10651   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10652   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10653   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10654   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10655   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10656   case ISD::MUL:                return LowerMUL(Op, DAG);
10657   case ISD::ABS:                return LowerABS(Op, DAG);
10658   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10659 
10660   // For counter-based loop handling.
10661   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10662 
10663   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10664 
10665   // Frame & Return address.
10666   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10667   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10668 
10669   case ISD::INTRINSIC_VOID:
10670     return LowerINTRINSIC_VOID(Op, DAG);
10671   case ISD::SREM:
10672   case ISD::UREM:
10673     return LowerREM(Op, DAG);
10674   case ISD::BSWAP:
10675     return LowerBSWAP(Op, DAG);
10676   case ISD::ATOMIC_CMP_SWAP:
10677     return LowerATOMIC_CMP_SWAP(Op, DAG);
10678   }
10679 }
10680 
10681 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10682                                            SmallVectorImpl<SDValue>&Results,
10683                                            SelectionDAG &DAG) const {
10684   SDLoc dl(N);
10685   switch (N->getOpcode()) {
10686   default:
10687     llvm_unreachable("Do not know how to custom type legalize this operation!");
10688   case ISD::READCYCLECOUNTER: {
10689     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10690     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10691 
10692     Results.push_back(
10693         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10694     Results.push_back(RTB.getValue(2));
10695     break;
10696   }
10697   case ISD::INTRINSIC_W_CHAIN: {
10698     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10699         Intrinsic::loop_decrement)
10700       break;
10701 
10702     assert(N->getValueType(0) == MVT::i1 &&
10703            "Unexpected result type for CTR decrement intrinsic");
10704     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10705                                  N->getValueType(0));
10706     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10707     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10708                                  N->getOperand(1));
10709 
10710     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10711     Results.push_back(NewInt.getValue(1));
10712     break;
10713   }
10714   case ISD::VAARG: {
10715     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10716       return;
10717 
10718     EVT VT = N->getValueType(0);
10719 
10720     if (VT == MVT::i64) {
10721       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10722 
10723       Results.push_back(NewNode);
10724       Results.push_back(NewNode.getValue(1));
10725     }
10726     return;
10727   }
10728   case ISD::FP_TO_SINT:
10729   case ISD::FP_TO_UINT:
10730     // LowerFP_TO_INT() can only handle f32 and f64.
10731     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10732       return;
10733     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10734     return;
10735   case ISD::TRUNCATE: {
10736     EVT TrgVT = N->getValueType(0);
10737     EVT OpVT = N->getOperand(0).getValueType();
10738     if (TrgVT.isVector() &&
10739         isOperationCustom(N->getOpcode(), TrgVT) &&
10740         OpVT.getSizeInBits() <= 128 &&
10741         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10742       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10743     return;
10744   }
10745   case ISD::BITCAST:
10746     // Don't handle bitcast here.
10747     return;
10748   }
10749 }
10750 
10751 //===----------------------------------------------------------------------===//
10752 //  Other Lowering Code
10753 //===----------------------------------------------------------------------===//
10754 
10755 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10756   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10757   Function *Func = Intrinsic::getDeclaration(M, Id);
10758   return Builder.CreateCall(Func, {});
10759 }
10760 
10761 // The mappings for emitLeading/TrailingFence is taken from
10762 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10763 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10764                                                  Instruction *Inst,
10765                                                  AtomicOrdering Ord) const {
10766   if (Ord == AtomicOrdering::SequentiallyConsistent)
10767     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10768   if (isReleaseOrStronger(Ord))
10769     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10770   return nullptr;
10771 }
10772 
10773 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10774                                                   Instruction *Inst,
10775                                                   AtomicOrdering Ord) const {
10776   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10777     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10778     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10779     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10780     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10781       return Builder.CreateCall(
10782           Intrinsic::getDeclaration(
10783               Builder.GetInsertBlock()->getParent()->getParent(),
10784               Intrinsic::ppc_cfence, {Inst->getType()}),
10785           {Inst});
10786     // FIXME: Can use isync for rmw operation.
10787     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10788   }
10789   return nullptr;
10790 }
10791 
10792 MachineBasicBlock *
10793 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10794                                     unsigned AtomicSize,
10795                                     unsigned BinOpcode,
10796                                     unsigned CmpOpcode,
10797                                     unsigned CmpPred) const {
10798   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10799   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10800 
10801   auto LoadMnemonic = PPC::LDARX;
10802   auto StoreMnemonic = PPC::STDCX;
10803   switch (AtomicSize) {
10804   default:
10805     llvm_unreachable("Unexpected size of atomic entity");
10806   case 1:
10807     LoadMnemonic = PPC::LBARX;
10808     StoreMnemonic = PPC::STBCX;
10809     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10810     break;
10811   case 2:
10812     LoadMnemonic = PPC::LHARX;
10813     StoreMnemonic = PPC::STHCX;
10814     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10815     break;
10816   case 4:
10817     LoadMnemonic = PPC::LWARX;
10818     StoreMnemonic = PPC::STWCX;
10819     break;
10820   case 8:
10821     LoadMnemonic = PPC::LDARX;
10822     StoreMnemonic = PPC::STDCX;
10823     break;
10824   }
10825 
10826   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10827   MachineFunction *F = BB->getParent();
10828   MachineFunction::iterator It = ++BB->getIterator();
10829 
10830   Register dest = MI.getOperand(0).getReg();
10831   Register ptrA = MI.getOperand(1).getReg();
10832   Register ptrB = MI.getOperand(2).getReg();
10833   Register incr = MI.getOperand(3).getReg();
10834   DebugLoc dl = MI.getDebugLoc();
10835 
10836   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10837   MachineBasicBlock *loop2MBB =
10838     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10839   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10840   F->insert(It, loopMBB);
10841   if (CmpOpcode)
10842     F->insert(It, loop2MBB);
10843   F->insert(It, exitMBB);
10844   exitMBB->splice(exitMBB->begin(), BB,
10845                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10846   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10847 
10848   MachineRegisterInfo &RegInfo = F->getRegInfo();
10849   Register TmpReg = (!BinOpcode) ? incr :
10850     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10851                                            : &PPC::GPRCRegClass);
10852 
10853   //  thisMBB:
10854   //   ...
10855   //   fallthrough --> loopMBB
10856   BB->addSuccessor(loopMBB);
10857 
10858   //  loopMBB:
10859   //   l[wd]arx dest, ptr
10860   //   add r0, dest, incr
10861   //   st[wd]cx. r0, ptr
10862   //   bne- loopMBB
10863   //   fallthrough --> exitMBB
10864 
10865   // For max/min...
10866   //  loopMBB:
10867   //   l[wd]arx dest, ptr
10868   //   cmpl?[wd] incr, dest
10869   //   bgt exitMBB
10870   //  loop2MBB:
10871   //   st[wd]cx. dest, ptr
10872   //   bne- loopMBB
10873   //   fallthrough --> exitMBB
10874 
10875   BB = loopMBB;
10876   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10877     .addReg(ptrA).addReg(ptrB);
10878   if (BinOpcode)
10879     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10880   if (CmpOpcode) {
10881     // Signed comparisons of byte or halfword values must be sign-extended.
10882     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10883       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10884       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10885               ExtReg).addReg(dest);
10886       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10887         .addReg(incr).addReg(ExtReg);
10888     } else
10889       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10890         .addReg(incr).addReg(dest);
10891 
10892     BuildMI(BB, dl, TII->get(PPC::BCC))
10893       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10894     BB->addSuccessor(loop2MBB);
10895     BB->addSuccessor(exitMBB);
10896     BB = loop2MBB;
10897   }
10898   BuildMI(BB, dl, TII->get(StoreMnemonic))
10899     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10900   BuildMI(BB, dl, TII->get(PPC::BCC))
10901     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10902   BB->addSuccessor(loopMBB);
10903   BB->addSuccessor(exitMBB);
10904 
10905   //  exitMBB:
10906   //   ...
10907   BB = exitMBB;
10908   return BB;
10909 }
10910 
10911 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10912     MachineInstr &MI, MachineBasicBlock *BB,
10913     bool is8bit, // operation
10914     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10915   // If we support part-word atomic mnemonics, just use them
10916   if (Subtarget.hasPartwordAtomics())
10917     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10918                             CmpPred);
10919 
10920   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10921   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10922   // In 64 bit mode we have to use 64 bits for addresses, even though the
10923   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10924   // registers without caring whether they're 32 or 64, but here we're
10925   // doing actual arithmetic on the addresses.
10926   bool is64bit = Subtarget.isPPC64();
10927   bool isLittleEndian = Subtarget.isLittleEndian();
10928   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10929 
10930   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10931   MachineFunction *F = BB->getParent();
10932   MachineFunction::iterator It = ++BB->getIterator();
10933 
10934   Register dest = MI.getOperand(0).getReg();
10935   Register ptrA = MI.getOperand(1).getReg();
10936   Register ptrB = MI.getOperand(2).getReg();
10937   Register incr = MI.getOperand(3).getReg();
10938   DebugLoc dl = MI.getDebugLoc();
10939 
10940   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10941   MachineBasicBlock *loop2MBB =
10942       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10943   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10944   F->insert(It, loopMBB);
10945   if (CmpOpcode)
10946     F->insert(It, loop2MBB);
10947   F->insert(It, exitMBB);
10948   exitMBB->splice(exitMBB->begin(), BB,
10949                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10950   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10951 
10952   MachineRegisterInfo &RegInfo = F->getRegInfo();
10953   const TargetRegisterClass *RC =
10954       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10955   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10956 
10957   Register PtrReg = RegInfo.createVirtualRegister(RC);
10958   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10959   Register ShiftReg =
10960       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10961   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10962   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10963   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10964   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10965   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10966   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10967   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10968   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10969   Register Ptr1Reg;
10970   Register TmpReg =
10971       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10972 
10973   //  thisMBB:
10974   //   ...
10975   //   fallthrough --> loopMBB
10976   BB->addSuccessor(loopMBB);
10977 
10978   // The 4-byte load must be aligned, while a char or short may be
10979   // anywhere in the word.  Hence all this nasty bookkeeping code.
10980   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10981   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10982   //   xori shift, shift1, 24 [16]
10983   //   rlwinm ptr, ptr1, 0, 0, 29
10984   //   slw incr2, incr, shift
10985   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10986   //   slw mask, mask2, shift
10987   //  loopMBB:
10988   //   lwarx tmpDest, ptr
10989   //   add tmp, tmpDest, incr2
10990   //   andc tmp2, tmpDest, mask
10991   //   and tmp3, tmp, mask
10992   //   or tmp4, tmp3, tmp2
10993   //   stwcx. tmp4, ptr
10994   //   bne- loopMBB
10995   //   fallthrough --> exitMBB
10996   //   srw dest, tmpDest, shift
10997   if (ptrA != ZeroReg) {
10998     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10999     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11000         .addReg(ptrA)
11001         .addReg(ptrB);
11002   } else {
11003     Ptr1Reg = ptrB;
11004   }
11005   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11006   // mode.
11007   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11008       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11009       .addImm(3)
11010       .addImm(27)
11011       .addImm(is8bit ? 28 : 27);
11012   if (!isLittleEndian)
11013     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11014         .addReg(Shift1Reg)
11015         .addImm(is8bit ? 24 : 16);
11016   if (is64bit)
11017     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11018         .addReg(Ptr1Reg)
11019         .addImm(0)
11020         .addImm(61);
11021   else
11022     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11023         .addReg(Ptr1Reg)
11024         .addImm(0)
11025         .addImm(0)
11026         .addImm(29);
11027   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11028   if (is8bit)
11029     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11030   else {
11031     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11032     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11033         .addReg(Mask3Reg)
11034         .addImm(65535);
11035   }
11036   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11037       .addReg(Mask2Reg)
11038       .addReg(ShiftReg);
11039 
11040   BB = loopMBB;
11041   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11042       .addReg(ZeroReg)
11043       .addReg(PtrReg);
11044   if (BinOpcode)
11045     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11046         .addReg(Incr2Reg)
11047         .addReg(TmpDestReg);
11048   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11049       .addReg(TmpDestReg)
11050       .addReg(MaskReg);
11051   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11052   if (CmpOpcode) {
11053     // For unsigned comparisons, we can directly compare the shifted values.
11054     // For signed comparisons we shift and sign extend.
11055     Register SReg = RegInfo.createVirtualRegister(GPRC);
11056     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11057         .addReg(TmpDestReg)
11058         .addReg(MaskReg);
11059     unsigned ValueReg = SReg;
11060     unsigned CmpReg = Incr2Reg;
11061     if (CmpOpcode == PPC::CMPW) {
11062       ValueReg = RegInfo.createVirtualRegister(GPRC);
11063       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11064           .addReg(SReg)
11065           .addReg(ShiftReg);
11066       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11067       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11068           .addReg(ValueReg);
11069       ValueReg = ValueSReg;
11070       CmpReg = incr;
11071     }
11072     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11073         .addReg(CmpReg)
11074         .addReg(ValueReg);
11075     BuildMI(BB, dl, TII->get(PPC::BCC))
11076         .addImm(CmpPred)
11077         .addReg(PPC::CR0)
11078         .addMBB(exitMBB);
11079     BB->addSuccessor(loop2MBB);
11080     BB->addSuccessor(exitMBB);
11081     BB = loop2MBB;
11082   }
11083   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11084   BuildMI(BB, dl, TII->get(PPC::STWCX))
11085       .addReg(Tmp4Reg)
11086       .addReg(ZeroReg)
11087       .addReg(PtrReg);
11088   BuildMI(BB, dl, TII->get(PPC::BCC))
11089       .addImm(PPC::PRED_NE)
11090       .addReg(PPC::CR0)
11091       .addMBB(loopMBB);
11092   BB->addSuccessor(loopMBB);
11093   BB->addSuccessor(exitMBB);
11094 
11095   //  exitMBB:
11096   //   ...
11097   BB = exitMBB;
11098   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11099       .addReg(TmpDestReg)
11100       .addReg(ShiftReg);
11101   return BB;
11102 }
11103 
11104 llvm::MachineBasicBlock *
11105 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11106                                     MachineBasicBlock *MBB) const {
11107   DebugLoc DL = MI.getDebugLoc();
11108   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11109   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11110 
11111   MachineFunction *MF = MBB->getParent();
11112   MachineRegisterInfo &MRI = MF->getRegInfo();
11113 
11114   const BasicBlock *BB = MBB->getBasicBlock();
11115   MachineFunction::iterator I = ++MBB->getIterator();
11116 
11117   Register DstReg = MI.getOperand(0).getReg();
11118   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11119   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11120   Register mainDstReg = MRI.createVirtualRegister(RC);
11121   Register restoreDstReg = MRI.createVirtualRegister(RC);
11122 
11123   MVT PVT = getPointerTy(MF->getDataLayout());
11124   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11125          "Invalid Pointer Size!");
11126   // For v = setjmp(buf), we generate
11127   //
11128   // thisMBB:
11129   //  SjLjSetup mainMBB
11130   //  bl mainMBB
11131   //  v_restore = 1
11132   //  b sinkMBB
11133   //
11134   // mainMBB:
11135   //  buf[LabelOffset] = LR
11136   //  v_main = 0
11137   //
11138   // sinkMBB:
11139   //  v = phi(main, restore)
11140   //
11141 
11142   MachineBasicBlock *thisMBB = MBB;
11143   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11144   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11145   MF->insert(I, mainMBB);
11146   MF->insert(I, sinkMBB);
11147 
11148   MachineInstrBuilder MIB;
11149 
11150   // Transfer the remainder of BB and its successor edges to sinkMBB.
11151   sinkMBB->splice(sinkMBB->begin(), MBB,
11152                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11153   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11154 
11155   // Note that the structure of the jmp_buf used here is not compatible
11156   // with that used by libc, and is not designed to be. Specifically, it
11157   // stores only those 'reserved' registers that LLVM does not otherwise
11158   // understand how to spill. Also, by convention, by the time this
11159   // intrinsic is called, Clang has already stored the frame address in the
11160   // first slot of the buffer and stack address in the third. Following the
11161   // X86 target code, we'll store the jump address in the second slot. We also
11162   // need to save the TOC pointer (R2) to handle jumps between shared
11163   // libraries, and that will be stored in the fourth slot. The thread
11164   // identifier (R13) is not affected.
11165 
11166   // thisMBB:
11167   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11168   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11169   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11170 
11171   // Prepare IP either in reg.
11172   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11173   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11174   Register BufReg = MI.getOperand(1).getReg();
11175 
11176   if (Subtarget.is64BitELFABI()) {
11177     setUsesTOCBasePtr(*MBB->getParent());
11178     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11179               .addReg(PPC::X2)
11180               .addImm(TOCOffset)
11181               .addReg(BufReg)
11182               .cloneMemRefs(MI);
11183   }
11184 
11185   // Naked functions never have a base pointer, and so we use r1. For all
11186   // other functions, this decision must be delayed until during PEI.
11187   unsigned BaseReg;
11188   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11189     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11190   else
11191     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11192 
11193   MIB = BuildMI(*thisMBB, MI, DL,
11194                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11195             .addReg(BaseReg)
11196             .addImm(BPOffset)
11197             .addReg(BufReg)
11198             .cloneMemRefs(MI);
11199 
11200   // Setup
11201   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11202   MIB.addRegMask(TRI->getNoPreservedMask());
11203 
11204   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11205 
11206   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11207           .addMBB(mainMBB);
11208   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11209 
11210   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11211   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11212 
11213   // mainMBB:
11214   //  mainDstReg = 0
11215   MIB =
11216       BuildMI(mainMBB, DL,
11217               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11218 
11219   // Store IP
11220   if (Subtarget.isPPC64()) {
11221     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11222             .addReg(LabelReg)
11223             .addImm(LabelOffset)
11224             .addReg(BufReg);
11225   } else {
11226     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11227             .addReg(LabelReg)
11228             .addImm(LabelOffset)
11229             .addReg(BufReg);
11230   }
11231   MIB.cloneMemRefs(MI);
11232 
11233   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11234   mainMBB->addSuccessor(sinkMBB);
11235 
11236   // sinkMBB:
11237   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11238           TII->get(PPC::PHI), DstReg)
11239     .addReg(mainDstReg).addMBB(mainMBB)
11240     .addReg(restoreDstReg).addMBB(thisMBB);
11241 
11242   MI.eraseFromParent();
11243   return sinkMBB;
11244 }
11245 
11246 MachineBasicBlock *
11247 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11248                                      MachineBasicBlock *MBB) const {
11249   DebugLoc DL = MI.getDebugLoc();
11250   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11251 
11252   MachineFunction *MF = MBB->getParent();
11253   MachineRegisterInfo &MRI = MF->getRegInfo();
11254 
11255   MVT PVT = getPointerTy(MF->getDataLayout());
11256   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11257          "Invalid Pointer Size!");
11258 
11259   const TargetRegisterClass *RC =
11260     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11261   Register Tmp = MRI.createVirtualRegister(RC);
11262   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11263   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11264   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11265   unsigned BP =
11266       (PVT == MVT::i64)
11267           ? PPC::X30
11268           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11269                                                               : PPC::R30);
11270 
11271   MachineInstrBuilder MIB;
11272 
11273   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11274   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11275   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11276   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11277 
11278   Register BufReg = MI.getOperand(0).getReg();
11279 
11280   // Reload FP (the jumped-to function may not have had a
11281   // frame pointer, and if so, then its r31 will be restored
11282   // as necessary).
11283   if (PVT == MVT::i64) {
11284     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11285             .addImm(0)
11286             .addReg(BufReg);
11287   } else {
11288     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11289             .addImm(0)
11290             .addReg(BufReg);
11291   }
11292   MIB.cloneMemRefs(MI);
11293 
11294   // Reload IP
11295   if (PVT == MVT::i64) {
11296     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11297             .addImm(LabelOffset)
11298             .addReg(BufReg);
11299   } else {
11300     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11301             .addImm(LabelOffset)
11302             .addReg(BufReg);
11303   }
11304   MIB.cloneMemRefs(MI);
11305 
11306   // Reload SP
11307   if (PVT == MVT::i64) {
11308     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11309             .addImm(SPOffset)
11310             .addReg(BufReg);
11311   } else {
11312     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11313             .addImm(SPOffset)
11314             .addReg(BufReg);
11315   }
11316   MIB.cloneMemRefs(MI);
11317 
11318   // Reload BP
11319   if (PVT == MVT::i64) {
11320     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11321             .addImm(BPOffset)
11322             .addReg(BufReg);
11323   } else {
11324     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11325             .addImm(BPOffset)
11326             .addReg(BufReg);
11327   }
11328   MIB.cloneMemRefs(MI);
11329 
11330   // Reload TOC
11331   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11332     setUsesTOCBasePtr(*MBB->getParent());
11333     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11334               .addImm(TOCOffset)
11335               .addReg(BufReg)
11336               .cloneMemRefs(MI);
11337   }
11338 
11339   // Jump
11340   BuildMI(*MBB, MI, DL,
11341           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11342   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11343 
11344   MI.eraseFromParent();
11345   return MBB;
11346 }
11347 
11348 MachineBasicBlock *
11349 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11350                                                MachineBasicBlock *BB) const {
11351   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11352       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11353     if (Subtarget.is64BitELFABI() &&
11354         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11355       // Call lowering should have added an r2 operand to indicate a dependence
11356       // on the TOC base pointer value. It can't however, because there is no
11357       // way to mark the dependence as implicit there, and so the stackmap code
11358       // will confuse it with a regular operand. Instead, add the dependence
11359       // here.
11360       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11361     }
11362 
11363     return emitPatchPoint(MI, BB);
11364   }
11365 
11366   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11367       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11368     return emitEHSjLjSetJmp(MI, BB);
11369   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11370              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11371     return emitEHSjLjLongJmp(MI, BB);
11372   }
11373 
11374   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11375 
11376   // To "insert" these instructions we actually have to insert their
11377   // control-flow patterns.
11378   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11379   MachineFunction::iterator It = ++BB->getIterator();
11380 
11381   MachineFunction *F = BB->getParent();
11382 
11383   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11384       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11385       MI.getOpcode() == PPC::SELECT_I8) {
11386     SmallVector<MachineOperand, 2> Cond;
11387     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11388         MI.getOpcode() == PPC::SELECT_CC_I8)
11389       Cond.push_back(MI.getOperand(4));
11390     else
11391       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11392     Cond.push_back(MI.getOperand(1));
11393 
11394     DebugLoc dl = MI.getDebugLoc();
11395     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11396                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11397   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11398              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11399              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11400              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11401              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11402              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11403              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11404              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11405              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11406              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11407              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11408              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11409              MI.getOpcode() == PPC::SELECT_F4 ||
11410              MI.getOpcode() == PPC::SELECT_F8 ||
11411              MI.getOpcode() == PPC::SELECT_F16 ||
11412              MI.getOpcode() == PPC::SELECT_QFRC ||
11413              MI.getOpcode() == PPC::SELECT_QSRC ||
11414              MI.getOpcode() == PPC::SELECT_QBRC ||
11415              MI.getOpcode() == PPC::SELECT_SPE ||
11416              MI.getOpcode() == PPC::SELECT_SPE4 ||
11417              MI.getOpcode() == PPC::SELECT_VRRC ||
11418              MI.getOpcode() == PPC::SELECT_VSFRC ||
11419              MI.getOpcode() == PPC::SELECT_VSSRC ||
11420              MI.getOpcode() == PPC::SELECT_VSRC) {
11421     // The incoming instruction knows the destination vreg to set, the
11422     // condition code register to branch on, the true/false values to
11423     // select between, and a branch opcode to use.
11424 
11425     //  thisMBB:
11426     //  ...
11427     //   TrueVal = ...
11428     //   cmpTY ccX, r1, r2
11429     //   bCC copy1MBB
11430     //   fallthrough --> copy0MBB
11431     MachineBasicBlock *thisMBB = BB;
11432     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11433     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11434     DebugLoc dl = MI.getDebugLoc();
11435     F->insert(It, copy0MBB);
11436     F->insert(It, sinkMBB);
11437 
11438     // Transfer the remainder of BB and its successor edges to sinkMBB.
11439     sinkMBB->splice(sinkMBB->begin(), BB,
11440                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11441     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11442 
11443     // Next, add the true and fallthrough blocks as its successors.
11444     BB->addSuccessor(copy0MBB);
11445     BB->addSuccessor(sinkMBB);
11446 
11447     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11448         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11449         MI.getOpcode() == PPC::SELECT_F16 ||
11450         MI.getOpcode() == PPC::SELECT_SPE4 ||
11451         MI.getOpcode() == PPC::SELECT_SPE ||
11452         MI.getOpcode() == PPC::SELECT_QFRC ||
11453         MI.getOpcode() == PPC::SELECT_QSRC ||
11454         MI.getOpcode() == PPC::SELECT_QBRC ||
11455         MI.getOpcode() == PPC::SELECT_VRRC ||
11456         MI.getOpcode() == PPC::SELECT_VSFRC ||
11457         MI.getOpcode() == PPC::SELECT_VSSRC ||
11458         MI.getOpcode() == PPC::SELECT_VSRC) {
11459       BuildMI(BB, dl, TII->get(PPC::BC))
11460           .addReg(MI.getOperand(1).getReg())
11461           .addMBB(sinkMBB);
11462     } else {
11463       unsigned SelectPred = MI.getOperand(4).getImm();
11464       BuildMI(BB, dl, TII->get(PPC::BCC))
11465           .addImm(SelectPred)
11466           .addReg(MI.getOperand(1).getReg())
11467           .addMBB(sinkMBB);
11468     }
11469 
11470     //  copy0MBB:
11471     //   %FalseValue = ...
11472     //   # fallthrough to sinkMBB
11473     BB = copy0MBB;
11474 
11475     // Update machine-CFG edges
11476     BB->addSuccessor(sinkMBB);
11477 
11478     //  sinkMBB:
11479     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11480     //  ...
11481     BB = sinkMBB;
11482     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11483         .addReg(MI.getOperand(3).getReg())
11484         .addMBB(copy0MBB)
11485         .addReg(MI.getOperand(2).getReg())
11486         .addMBB(thisMBB);
11487   } else if (MI.getOpcode() == PPC::ReadTB) {
11488     // To read the 64-bit time-base register on a 32-bit target, we read the
11489     // two halves. Should the counter have wrapped while it was being read, we
11490     // need to try again.
11491     // ...
11492     // readLoop:
11493     // mfspr Rx,TBU # load from TBU
11494     // mfspr Ry,TB  # load from TB
11495     // mfspr Rz,TBU # load from TBU
11496     // cmpw crX,Rx,Rz # check if 'old'='new'
11497     // bne readLoop   # branch if they're not equal
11498     // ...
11499 
11500     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11501     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11502     DebugLoc dl = MI.getDebugLoc();
11503     F->insert(It, readMBB);
11504     F->insert(It, sinkMBB);
11505 
11506     // Transfer the remainder of BB and its successor edges to sinkMBB.
11507     sinkMBB->splice(sinkMBB->begin(), BB,
11508                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11509     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11510 
11511     BB->addSuccessor(readMBB);
11512     BB = readMBB;
11513 
11514     MachineRegisterInfo &RegInfo = F->getRegInfo();
11515     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11516     Register LoReg = MI.getOperand(0).getReg();
11517     Register HiReg = MI.getOperand(1).getReg();
11518 
11519     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11520     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11521     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11522 
11523     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11524 
11525     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11526         .addReg(HiReg)
11527         .addReg(ReadAgainReg);
11528     BuildMI(BB, dl, TII->get(PPC::BCC))
11529         .addImm(PPC::PRED_NE)
11530         .addReg(CmpReg)
11531         .addMBB(readMBB);
11532 
11533     BB->addSuccessor(readMBB);
11534     BB->addSuccessor(sinkMBB);
11535   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11536     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11537   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11538     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11539   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11540     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11541   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11542     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11543 
11544   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11545     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11546   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11547     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11548   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11549     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11550   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11551     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11552 
11553   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11554     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11555   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11556     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11557   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11558     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11559   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11560     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11561 
11562   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11563     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11564   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11565     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11566   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11567     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11568   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11569     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11570 
11571   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11572     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11573   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11574     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11575   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11576     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11577   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11578     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11579 
11580   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11581     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11582   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11583     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11584   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11585     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11586   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11587     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11588 
11589   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11590     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11591   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11592     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11593   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11594     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11595   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11596     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11597 
11598   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11599     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11600   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11601     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11602   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11603     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11604   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11605     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11606 
11607   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11608     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11609   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11610     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11611   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11612     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11613   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11614     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11615 
11616   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11617     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11618   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11619     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11620   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11621     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11622   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11623     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11624 
11625   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11626     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11627   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11628     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11629   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11630     BB = EmitAtomicBinary(MI, BB, 4, 0);
11631   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11632     BB = EmitAtomicBinary(MI, BB, 8, 0);
11633   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11634            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11635            (Subtarget.hasPartwordAtomics() &&
11636             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11637            (Subtarget.hasPartwordAtomics() &&
11638             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11639     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11640 
11641     auto LoadMnemonic = PPC::LDARX;
11642     auto StoreMnemonic = PPC::STDCX;
11643     switch (MI.getOpcode()) {
11644     default:
11645       llvm_unreachable("Compare and swap of unknown size");
11646     case PPC::ATOMIC_CMP_SWAP_I8:
11647       LoadMnemonic = PPC::LBARX;
11648       StoreMnemonic = PPC::STBCX;
11649       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11650       break;
11651     case PPC::ATOMIC_CMP_SWAP_I16:
11652       LoadMnemonic = PPC::LHARX;
11653       StoreMnemonic = PPC::STHCX;
11654       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11655       break;
11656     case PPC::ATOMIC_CMP_SWAP_I32:
11657       LoadMnemonic = PPC::LWARX;
11658       StoreMnemonic = PPC::STWCX;
11659       break;
11660     case PPC::ATOMIC_CMP_SWAP_I64:
11661       LoadMnemonic = PPC::LDARX;
11662       StoreMnemonic = PPC::STDCX;
11663       break;
11664     }
11665     Register dest = MI.getOperand(0).getReg();
11666     Register ptrA = MI.getOperand(1).getReg();
11667     Register ptrB = MI.getOperand(2).getReg();
11668     Register oldval = MI.getOperand(3).getReg();
11669     Register newval = MI.getOperand(4).getReg();
11670     DebugLoc dl = MI.getDebugLoc();
11671 
11672     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11673     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11674     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11675     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11676     F->insert(It, loop1MBB);
11677     F->insert(It, loop2MBB);
11678     F->insert(It, midMBB);
11679     F->insert(It, exitMBB);
11680     exitMBB->splice(exitMBB->begin(), BB,
11681                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11682     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11683 
11684     //  thisMBB:
11685     //   ...
11686     //   fallthrough --> loopMBB
11687     BB->addSuccessor(loop1MBB);
11688 
11689     // loop1MBB:
11690     //   l[bhwd]arx dest, ptr
11691     //   cmp[wd] dest, oldval
11692     //   bne- midMBB
11693     // loop2MBB:
11694     //   st[bhwd]cx. newval, ptr
11695     //   bne- loopMBB
11696     //   b exitBB
11697     // midMBB:
11698     //   st[bhwd]cx. dest, ptr
11699     // exitBB:
11700     BB = loop1MBB;
11701     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11702     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11703         .addReg(oldval)
11704         .addReg(dest);
11705     BuildMI(BB, dl, TII->get(PPC::BCC))
11706         .addImm(PPC::PRED_NE)
11707         .addReg(PPC::CR0)
11708         .addMBB(midMBB);
11709     BB->addSuccessor(loop2MBB);
11710     BB->addSuccessor(midMBB);
11711 
11712     BB = loop2MBB;
11713     BuildMI(BB, dl, TII->get(StoreMnemonic))
11714         .addReg(newval)
11715         .addReg(ptrA)
11716         .addReg(ptrB);
11717     BuildMI(BB, dl, TII->get(PPC::BCC))
11718         .addImm(PPC::PRED_NE)
11719         .addReg(PPC::CR0)
11720         .addMBB(loop1MBB);
11721     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11722     BB->addSuccessor(loop1MBB);
11723     BB->addSuccessor(exitMBB);
11724 
11725     BB = midMBB;
11726     BuildMI(BB, dl, TII->get(StoreMnemonic))
11727         .addReg(dest)
11728         .addReg(ptrA)
11729         .addReg(ptrB);
11730     BB->addSuccessor(exitMBB);
11731 
11732     //  exitMBB:
11733     //   ...
11734     BB = exitMBB;
11735   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11736              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11737     // We must use 64-bit registers for addresses when targeting 64-bit,
11738     // since we're actually doing arithmetic on them.  Other registers
11739     // can be 32-bit.
11740     bool is64bit = Subtarget.isPPC64();
11741     bool isLittleEndian = Subtarget.isLittleEndian();
11742     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11743 
11744     Register dest = MI.getOperand(0).getReg();
11745     Register ptrA = MI.getOperand(1).getReg();
11746     Register ptrB = MI.getOperand(2).getReg();
11747     Register oldval = MI.getOperand(3).getReg();
11748     Register newval = MI.getOperand(4).getReg();
11749     DebugLoc dl = MI.getDebugLoc();
11750 
11751     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11752     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11753     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11754     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11755     F->insert(It, loop1MBB);
11756     F->insert(It, loop2MBB);
11757     F->insert(It, midMBB);
11758     F->insert(It, exitMBB);
11759     exitMBB->splice(exitMBB->begin(), BB,
11760                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11761     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11762 
11763     MachineRegisterInfo &RegInfo = F->getRegInfo();
11764     const TargetRegisterClass *RC =
11765         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11766     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11767 
11768     Register PtrReg = RegInfo.createVirtualRegister(RC);
11769     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11770     Register ShiftReg =
11771         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11772     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11773     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11774     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11775     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11776     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11777     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11778     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11779     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11780     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11781     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11782     Register Ptr1Reg;
11783     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11784     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11785     //  thisMBB:
11786     //   ...
11787     //   fallthrough --> loopMBB
11788     BB->addSuccessor(loop1MBB);
11789 
11790     // The 4-byte load must be aligned, while a char or short may be
11791     // anywhere in the word.  Hence all this nasty bookkeeping code.
11792     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11793     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11794     //   xori shift, shift1, 24 [16]
11795     //   rlwinm ptr, ptr1, 0, 0, 29
11796     //   slw newval2, newval, shift
11797     //   slw oldval2, oldval,shift
11798     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11799     //   slw mask, mask2, shift
11800     //   and newval3, newval2, mask
11801     //   and oldval3, oldval2, mask
11802     // loop1MBB:
11803     //   lwarx tmpDest, ptr
11804     //   and tmp, tmpDest, mask
11805     //   cmpw tmp, oldval3
11806     //   bne- midMBB
11807     // loop2MBB:
11808     //   andc tmp2, tmpDest, mask
11809     //   or tmp4, tmp2, newval3
11810     //   stwcx. tmp4, ptr
11811     //   bne- loop1MBB
11812     //   b exitBB
11813     // midMBB:
11814     //   stwcx. tmpDest, ptr
11815     // exitBB:
11816     //   srw dest, tmpDest, shift
11817     if (ptrA != ZeroReg) {
11818       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11819       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11820           .addReg(ptrA)
11821           .addReg(ptrB);
11822     } else {
11823       Ptr1Reg = ptrB;
11824     }
11825 
11826     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11827     // mode.
11828     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11829         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11830         .addImm(3)
11831         .addImm(27)
11832         .addImm(is8bit ? 28 : 27);
11833     if (!isLittleEndian)
11834       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11835           .addReg(Shift1Reg)
11836           .addImm(is8bit ? 24 : 16);
11837     if (is64bit)
11838       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11839           .addReg(Ptr1Reg)
11840           .addImm(0)
11841           .addImm(61);
11842     else
11843       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11844           .addReg(Ptr1Reg)
11845           .addImm(0)
11846           .addImm(0)
11847           .addImm(29);
11848     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11849         .addReg(newval)
11850         .addReg(ShiftReg);
11851     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11852         .addReg(oldval)
11853         .addReg(ShiftReg);
11854     if (is8bit)
11855       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11856     else {
11857       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11858       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11859           .addReg(Mask3Reg)
11860           .addImm(65535);
11861     }
11862     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11863         .addReg(Mask2Reg)
11864         .addReg(ShiftReg);
11865     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11866         .addReg(NewVal2Reg)
11867         .addReg(MaskReg);
11868     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11869         .addReg(OldVal2Reg)
11870         .addReg(MaskReg);
11871 
11872     BB = loop1MBB;
11873     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11874         .addReg(ZeroReg)
11875         .addReg(PtrReg);
11876     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11877         .addReg(TmpDestReg)
11878         .addReg(MaskReg);
11879     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11880         .addReg(TmpReg)
11881         .addReg(OldVal3Reg);
11882     BuildMI(BB, dl, TII->get(PPC::BCC))
11883         .addImm(PPC::PRED_NE)
11884         .addReg(PPC::CR0)
11885         .addMBB(midMBB);
11886     BB->addSuccessor(loop2MBB);
11887     BB->addSuccessor(midMBB);
11888 
11889     BB = loop2MBB;
11890     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11891         .addReg(TmpDestReg)
11892         .addReg(MaskReg);
11893     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11894         .addReg(Tmp2Reg)
11895         .addReg(NewVal3Reg);
11896     BuildMI(BB, dl, TII->get(PPC::STWCX))
11897         .addReg(Tmp4Reg)
11898         .addReg(ZeroReg)
11899         .addReg(PtrReg);
11900     BuildMI(BB, dl, TII->get(PPC::BCC))
11901         .addImm(PPC::PRED_NE)
11902         .addReg(PPC::CR0)
11903         .addMBB(loop1MBB);
11904     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11905     BB->addSuccessor(loop1MBB);
11906     BB->addSuccessor(exitMBB);
11907 
11908     BB = midMBB;
11909     BuildMI(BB, dl, TII->get(PPC::STWCX))
11910         .addReg(TmpDestReg)
11911         .addReg(ZeroReg)
11912         .addReg(PtrReg);
11913     BB->addSuccessor(exitMBB);
11914 
11915     //  exitMBB:
11916     //   ...
11917     BB = exitMBB;
11918     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11919         .addReg(TmpReg)
11920         .addReg(ShiftReg);
11921   } else if (MI.getOpcode() == PPC::FADDrtz) {
11922     // This pseudo performs an FADD with rounding mode temporarily forced
11923     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11924     // is not modeled at the SelectionDAG level.
11925     Register Dest = MI.getOperand(0).getReg();
11926     Register Src1 = MI.getOperand(1).getReg();
11927     Register Src2 = MI.getOperand(2).getReg();
11928     DebugLoc dl = MI.getDebugLoc();
11929 
11930     MachineRegisterInfo &RegInfo = F->getRegInfo();
11931     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11932 
11933     // Save FPSCR value.
11934     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11935 
11936     // Set rounding mode to round-to-zero.
11937     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11938     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11939 
11940     // Perform addition.
11941     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11942 
11943     // Restore FPSCR value.
11944     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11945   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11946              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11947              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11948              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11949     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11950                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11951                           ? PPC::ANDI8_rec
11952                           : PPC::ANDI_rec;
11953     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11954                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11955 
11956     MachineRegisterInfo &RegInfo = F->getRegInfo();
11957     Register Dest = RegInfo.createVirtualRegister(
11958         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11959 
11960     DebugLoc Dl = MI.getDebugLoc();
11961     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11962         .addReg(MI.getOperand(1).getReg())
11963         .addImm(1);
11964     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11965             MI.getOperand(0).getReg())
11966         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11967   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11968     DebugLoc Dl = MI.getDebugLoc();
11969     MachineRegisterInfo &RegInfo = F->getRegInfo();
11970     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11971     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11972     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11973             MI.getOperand(0).getReg())
11974         .addReg(CRReg);
11975   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11976     DebugLoc Dl = MI.getDebugLoc();
11977     unsigned Imm = MI.getOperand(1).getImm();
11978     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11979     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11980             MI.getOperand(0).getReg())
11981         .addReg(PPC::CR0EQ);
11982   } else if (MI.getOpcode() == PPC::SETRNDi) {
11983     DebugLoc dl = MI.getDebugLoc();
11984     Register OldFPSCRReg = MI.getOperand(0).getReg();
11985 
11986     // Save FPSCR value.
11987     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11988 
11989     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11990     // the following settings:
11991     //   00 Round to nearest
11992     //   01 Round to 0
11993     //   10 Round to +inf
11994     //   11 Round to -inf
11995 
11996     // When the operand is immediate, using the two least significant bits of
11997     // the immediate to set the bits 62:63 of FPSCR.
11998     unsigned Mode = MI.getOperand(1).getImm();
11999     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12000       .addImm(31);
12001 
12002     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12003       .addImm(30);
12004   } else if (MI.getOpcode() == PPC::SETRND) {
12005     DebugLoc dl = MI.getDebugLoc();
12006 
12007     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12008     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12009     // If the target doesn't have DirectMove, we should use stack to do the
12010     // conversion, because the target doesn't have the instructions like mtvsrd
12011     // or mfvsrd to do this conversion directly.
12012     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12013       if (Subtarget.hasDirectMove()) {
12014         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12015           .addReg(SrcReg);
12016       } else {
12017         // Use stack to do the register copy.
12018         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12019         MachineRegisterInfo &RegInfo = F->getRegInfo();
12020         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12021         if (RC == &PPC::F8RCRegClass) {
12022           // Copy register from F8RCRegClass to G8RCRegclass.
12023           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12024                  "Unsupported RegClass.");
12025 
12026           StoreOp = PPC::STFD;
12027           LoadOp = PPC::LD;
12028         } else {
12029           // Copy register from G8RCRegClass to F8RCRegclass.
12030           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12031                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12032                  "Unsupported RegClass.");
12033         }
12034 
12035         MachineFrameInfo &MFI = F->getFrameInfo();
12036         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12037 
12038         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12039             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12040             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12041             MFI.getObjectAlign(FrameIdx));
12042 
12043         // Store the SrcReg into the stack.
12044         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12045           .addReg(SrcReg)
12046           .addImm(0)
12047           .addFrameIndex(FrameIdx)
12048           .addMemOperand(MMOStore);
12049 
12050         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12051             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12052             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12053             MFI.getObjectAlign(FrameIdx));
12054 
12055         // Load from the stack where SrcReg is stored, and save to DestReg,
12056         // so we have done the RegClass conversion from RegClass::SrcReg to
12057         // RegClass::DestReg.
12058         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12059           .addImm(0)
12060           .addFrameIndex(FrameIdx)
12061           .addMemOperand(MMOLoad);
12062       }
12063     };
12064 
12065     Register OldFPSCRReg = MI.getOperand(0).getReg();
12066 
12067     // Save FPSCR value.
12068     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12069 
12070     // When the operand is gprc register, use two least significant bits of the
12071     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12072     //
12073     // copy OldFPSCRTmpReg, OldFPSCRReg
12074     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12075     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12076     // copy NewFPSCRReg, NewFPSCRTmpReg
12077     // mtfsf 255, NewFPSCRReg
12078     MachineOperand SrcOp = MI.getOperand(1);
12079     MachineRegisterInfo &RegInfo = F->getRegInfo();
12080     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12081 
12082     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12083 
12084     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12085     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12086 
12087     // The first operand of INSERT_SUBREG should be a register which has
12088     // subregisters, we only care about its RegClass, so we should use an
12089     // IMPLICIT_DEF register.
12090     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12091     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12092       .addReg(ImDefReg)
12093       .add(SrcOp)
12094       .addImm(1);
12095 
12096     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12097     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12098       .addReg(OldFPSCRTmpReg)
12099       .addReg(ExtSrcReg)
12100       .addImm(0)
12101       .addImm(62);
12102 
12103     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12104     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12105 
12106     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12107     // bits of FPSCR.
12108     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12109       .addImm(255)
12110       .addReg(NewFPSCRReg)
12111       .addImm(0)
12112       .addImm(0);
12113   } else {
12114     llvm_unreachable("Unexpected instr type to insert");
12115   }
12116 
12117   MI.eraseFromParent(); // The pseudo instruction is gone now.
12118   return BB;
12119 }
12120 
12121 //===----------------------------------------------------------------------===//
12122 // Target Optimization Hooks
12123 //===----------------------------------------------------------------------===//
12124 
12125 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12126   // For the estimates, convergence is quadratic, so we essentially double the
12127   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12128   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12129   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12130   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12131   if (VT.getScalarType() == MVT::f64)
12132     RefinementSteps++;
12133   return RefinementSteps;
12134 }
12135 
12136 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12137                                            int Enabled, int &RefinementSteps,
12138                                            bool &UseOneConstNR,
12139                                            bool Reciprocal) const {
12140   EVT VT = Operand.getValueType();
12141   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12142       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12143       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12144       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12145       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12146       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12147     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12148       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12149 
12150     // The Newton-Raphson computation with a single constant does not provide
12151     // enough accuracy on some CPUs.
12152     UseOneConstNR = !Subtarget.needsTwoConstNR();
12153     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12154   }
12155   return SDValue();
12156 }
12157 
12158 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12159                                             int Enabled,
12160                                             int &RefinementSteps) const {
12161   EVT VT = Operand.getValueType();
12162   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12163       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12164       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12165       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12166       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12167       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12168     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12169       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12170     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12171   }
12172   return SDValue();
12173 }
12174 
12175 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12176   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12177   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12178   // enabled for division), this functionality is redundant with the default
12179   // combiner logic (once the division -> reciprocal/multiply transformation
12180   // has taken place). As a result, this matters more for older cores than for
12181   // newer ones.
12182 
12183   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12184   // reciprocal if there are two or more FDIVs (for embedded cores with only
12185   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12186   switch (Subtarget.getCPUDirective()) {
12187   default:
12188     return 3;
12189   case PPC::DIR_440:
12190   case PPC::DIR_A2:
12191   case PPC::DIR_E500:
12192   case PPC::DIR_E500mc:
12193   case PPC::DIR_E5500:
12194     return 2;
12195   }
12196 }
12197 
12198 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12199 // collapsed, and so we need to look through chains of them.
12200 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12201                                      int64_t& Offset, SelectionDAG &DAG) {
12202   if (DAG.isBaseWithConstantOffset(Loc)) {
12203     Base = Loc.getOperand(0);
12204     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12205 
12206     // The base might itself be a base plus an offset, and if so, accumulate
12207     // that as well.
12208     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12209   }
12210 }
12211 
12212 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12213                             unsigned Bytes, int Dist,
12214                             SelectionDAG &DAG) {
12215   if (VT.getSizeInBits() / 8 != Bytes)
12216     return false;
12217 
12218   SDValue BaseLoc = Base->getBasePtr();
12219   if (Loc.getOpcode() == ISD::FrameIndex) {
12220     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12221       return false;
12222     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12223     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12224     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12225     int FS  = MFI.getObjectSize(FI);
12226     int BFS = MFI.getObjectSize(BFI);
12227     if (FS != BFS || FS != (int)Bytes) return false;
12228     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12229   }
12230 
12231   SDValue Base1 = Loc, Base2 = BaseLoc;
12232   int64_t Offset1 = 0, Offset2 = 0;
12233   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12234   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12235   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12236     return true;
12237 
12238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12239   const GlobalValue *GV1 = nullptr;
12240   const GlobalValue *GV2 = nullptr;
12241   Offset1 = 0;
12242   Offset2 = 0;
12243   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12244   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12245   if (isGA1 && isGA2 && GV1 == GV2)
12246     return Offset1 == (Offset2 + Dist*Bytes);
12247   return false;
12248 }
12249 
12250 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12251 // not enforce equality of the chain operands.
12252 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12253                             unsigned Bytes, int Dist,
12254                             SelectionDAG &DAG) {
12255   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12256     EVT VT = LS->getMemoryVT();
12257     SDValue Loc = LS->getBasePtr();
12258     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12259   }
12260 
12261   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12262     EVT VT;
12263     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12264     default: return false;
12265     case Intrinsic::ppc_qpx_qvlfd:
12266     case Intrinsic::ppc_qpx_qvlfda:
12267       VT = MVT::v4f64;
12268       break;
12269     case Intrinsic::ppc_qpx_qvlfs:
12270     case Intrinsic::ppc_qpx_qvlfsa:
12271       VT = MVT::v4f32;
12272       break;
12273     case Intrinsic::ppc_qpx_qvlfcd:
12274     case Intrinsic::ppc_qpx_qvlfcda:
12275       VT = MVT::v2f64;
12276       break;
12277     case Intrinsic::ppc_qpx_qvlfcs:
12278     case Intrinsic::ppc_qpx_qvlfcsa:
12279       VT = MVT::v2f32;
12280       break;
12281     case Intrinsic::ppc_qpx_qvlfiwa:
12282     case Intrinsic::ppc_qpx_qvlfiwz:
12283     case Intrinsic::ppc_altivec_lvx:
12284     case Intrinsic::ppc_altivec_lvxl:
12285     case Intrinsic::ppc_vsx_lxvw4x:
12286     case Intrinsic::ppc_vsx_lxvw4x_be:
12287       VT = MVT::v4i32;
12288       break;
12289     case Intrinsic::ppc_vsx_lxvd2x:
12290     case Intrinsic::ppc_vsx_lxvd2x_be:
12291       VT = MVT::v2f64;
12292       break;
12293     case Intrinsic::ppc_altivec_lvebx:
12294       VT = MVT::i8;
12295       break;
12296     case Intrinsic::ppc_altivec_lvehx:
12297       VT = MVT::i16;
12298       break;
12299     case Intrinsic::ppc_altivec_lvewx:
12300       VT = MVT::i32;
12301       break;
12302     }
12303 
12304     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12305   }
12306 
12307   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12308     EVT VT;
12309     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12310     default: return false;
12311     case Intrinsic::ppc_qpx_qvstfd:
12312     case Intrinsic::ppc_qpx_qvstfda:
12313       VT = MVT::v4f64;
12314       break;
12315     case Intrinsic::ppc_qpx_qvstfs:
12316     case Intrinsic::ppc_qpx_qvstfsa:
12317       VT = MVT::v4f32;
12318       break;
12319     case Intrinsic::ppc_qpx_qvstfcd:
12320     case Intrinsic::ppc_qpx_qvstfcda:
12321       VT = MVT::v2f64;
12322       break;
12323     case Intrinsic::ppc_qpx_qvstfcs:
12324     case Intrinsic::ppc_qpx_qvstfcsa:
12325       VT = MVT::v2f32;
12326       break;
12327     case Intrinsic::ppc_qpx_qvstfiw:
12328     case Intrinsic::ppc_qpx_qvstfiwa:
12329     case Intrinsic::ppc_altivec_stvx:
12330     case Intrinsic::ppc_altivec_stvxl:
12331     case Intrinsic::ppc_vsx_stxvw4x:
12332       VT = MVT::v4i32;
12333       break;
12334     case Intrinsic::ppc_vsx_stxvd2x:
12335       VT = MVT::v2f64;
12336       break;
12337     case Intrinsic::ppc_vsx_stxvw4x_be:
12338       VT = MVT::v4i32;
12339       break;
12340     case Intrinsic::ppc_vsx_stxvd2x_be:
12341       VT = MVT::v2f64;
12342       break;
12343     case Intrinsic::ppc_altivec_stvebx:
12344       VT = MVT::i8;
12345       break;
12346     case Intrinsic::ppc_altivec_stvehx:
12347       VT = MVT::i16;
12348       break;
12349     case Intrinsic::ppc_altivec_stvewx:
12350       VT = MVT::i32;
12351       break;
12352     }
12353 
12354     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12355   }
12356 
12357   return false;
12358 }
12359 
12360 // Return true is there is a nearyby consecutive load to the one provided
12361 // (regardless of alignment). We search up and down the chain, looking though
12362 // token factors and other loads (but nothing else). As a result, a true result
12363 // indicates that it is safe to create a new consecutive load adjacent to the
12364 // load provided.
12365 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12366   SDValue Chain = LD->getChain();
12367   EVT VT = LD->getMemoryVT();
12368 
12369   SmallSet<SDNode *, 16> LoadRoots;
12370   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12371   SmallSet<SDNode *, 16> Visited;
12372 
12373   // First, search up the chain, branching to follow all token-factor operands.
12374   // If we find a consecutive load, then we're done, otherwise, record all
12375   // nodes just above the top-level loads and token factors.
12376   while (!Queue.empty()) {
12377     SDNode *ChainNext = Queue.pop_back_val();
12378     if (!Visited.insert(ChainNext).second)
12379       continue;
12380 
12381     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12382       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12383         return true;
12384 
12385       if (!Visited.count(ChainLD->getChain().getNode()))
12386         Queue.push_back(ChainLD->getChain().getNode());
12387     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12388       for (const SDUse &O : ChainNext->ops())
12389         if (!Visited.count(O.getNode()))
12390           Queue.push_back(O.getNode());
12391     } else
12392       LoadRoots.insert(ChainNext);
12393   }
12394 
12395   // Second, search down the chain, starting from the top-level nodes recorded
12396   // in the first phase. These top-level nodes are the nodes just above all
12397   // loads and token factors. Starting with their uses, recursively look though
12398   // all loads (just the chain uses) and token factors to find a consecutive
12399   // load.
12400   Visited.clear();
12401   Queue.clear();
12402 
12403   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12404        IE = LoadRoots.end(); I != IE; ++I) {
12405     Queue.push_back(*I);
12406 
12407     while (!Queue.empty()) {
12408       SDNode *LoadRoot = Queue.pop_back_val();
12409       if (!Visited.insert(LoadRoot).second)
12410         continue;
12411 
12412       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12413         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12414           return true;
12415 
12416       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12417            UE = LoadRoot->use_end(); UI != UE; ++UI)
12418         if (((isa<MemSDNode>(*UI) &&
12419             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12420             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12421           Queue.push_back(*UI);
12422     }
12423   }
12424 
12425   return false;
12426 }
12427 
12428 /// This function is called when we have proved that a SETCC node can be replaced
12429 /// by subtraction (and other supporting instructions) so that the result of
12430 /// comparison is kept in a GPR instead of CR. This function is purely for
12431 /// codegen purposes and has some flags to guide the codegen process.
12432 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12433                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12434   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12435 
12436   // Zero extend the operands to the largest legal integer. Originally, they
12437   // must be of a strictly smaller size.
12438   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12439                          DAG.getConstant(Size, DL, MVT::i32));
12440   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12441                          DAG.getConstant(Size, DL, MVT::i32));
12442 
12443   // Swap if needed. Depends on the condition code.
12444   if (Swap)
12445     std::swap(Op0, Op1);
12446 
12447   // Subtract extended integers.
12448   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12449 
12450   // Move the sign bit to the least significant position and zero out the rest.
12451   // Now the least significant bit carries the result of original comparison.
12452   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12453                              DAG.getConstant(Size - 1, DL, MVT::i32));
12454   auto Final = Shifted;
12455 
12456   // Complement the result if needed. Based on the condition code.
12457   if (Complement)
12458     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12459                         DAG.getConstant(1, DL, MVT::i64));
12460 
12461   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12462 }
12463 
12464 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12465                                                   DAGCombinerInfo &DCI) const {
12466   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12467 
12468   SelectionDAG &DAG = DCI.DAG;
12469   SDLoc DL(N);
12470 
12471   // Size of integers being compared has a critical role in the following
12472   // analysis, so we prefer to do this when all types are legal.
12473   if (!DCI.isAfterLegalizeDAG())
12474     return SDValue();
12475 
12476   // If all users of SETCC extend its value to a legal integer type
12477   // then we replace SETCC with a subtraction
12478   for (SDNode::use_iterator UI = N->use_begin(),
12479        UE = N->use_end(); UI != UE; ++UI) {
12480     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12481       return SDValue();
12482   }
12483 
12484   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12485   auto OpSize = N->getOperand(0).getValueSizeInBits();
12486 
12487   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12488 
12489   if (OpSize < Size) {
12490     switch (CC) {
12491     default: break;
12492     case ISD::SETULT:
12493       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12494     case ISD::SETULE:
12495       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12496     case ISD::SETUGT:
12497       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12498     case ISD::SETUGE:
12499       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12500     }
12501   }
12502 
12503   return SDValue();
12504 }
12505 
12506 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12507                                                   DAGCombinerInfo &DCI) const {
12508   SelectionDAG &DAG = DCI.DAG;
12509   SDLoc dl(N);
12510 
12511   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12512   // If we're tracking CR bits, we need to be careful that we don't have:
12513   //   trunc(binary-ops(zext(x), zext(y)))
12514   // or
12515   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12516   // such that we're unnecessarily moving things into GPRs when it would be
12517   // better to keep them in CR bits.
12518 
12519   // Note that trunc here can be an actual i1 trunc, or can be the effective
12520   // truncation that comes from a setcc or select_cc.
12521   if (N->getOpcode() == ISD::TRUNCATE &&
12522       N->getValueType(0) != MVT::i1)
12523     return SDValue();
12524 
12525   if (N->getOperand(0).getValueType() != MVT::i32 &&
12526       N->getOperand(0).getValueType() != MVT::i64)
12527     return SDValue();
12528 
12529   if (N->getOpcode() == ISD::SETCC ||
12530       N->getOpcode() == ISD::SELECT_CC) {
12531     // If we're looking at a comparison, then we need to make sure that the
12532     // high bits (all except for the first) don't matter the result.
12533     ISD::CondCode CC =
12534       cast<CondCodeSDNode>(N->getOperand(
12535         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12536     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12537 
12538     if (ISD::isSignedIntSetCC(CC)) {
12539       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12540           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12541         return SDValue();
12542     } else if (ISD::isUnsignedIntSetCC(CC)) {
12543       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12544                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12545           !DAG.MaskedValueIsZero(N->getOperand(1),
12546                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12547         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12548                                              : SDValue());
12549     } else {
12550       // This is neither a signed nor an unsigned comparison, just make sure
12551       // that the high bits are equal.
12552       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12553       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12554 
12555       // We don't really care about what is known about the first bit (if
12556       // anything), so clear it in all masks prior to comparing them.
12557       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12558       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12559 
12560       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12561         return SDValue();
12562     }
12563   }
12564 
12565   // We now know that the higher-order bits are irrelevant, we just need to
12566   // make sure that all of the intermediate operations are bit operations, and
12567   // all inputs are extensions.
12568   if (N->getOperand(0).getOpcode() != ISD::AND &&
12569       N->getOperand(0).getOpcode() != ISD::OR  &&
12570       N->getOperand(0).getOpcode() != ISD::XOR &&
12571       N->getOperand(0).getOpcode() != ISD::SELECT &&
12572       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12573       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12574       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12575       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12576       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12577     return SDValue();
12578 
12579   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12580       N->getOperand(1).getOpcode() != ISD::AND &&
12581       N->getOperand(1).getOpcode() != ISD::OR  &&
12582       N->getOperand(1).getOpcode() != ISD::XOR &&
12583       N->getOperand(1).getOpcode() != ISD::SELECT &&
12584       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12585       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12586       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12587       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12588       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12589     return SDValue();
12590 
12591   SmallVector<SDValue, 4> Inputs;
12592   SmallVector<SDValue, 8> BinOps, PromOps;
12593   SmallPtrSet<SDNode *, 16> Visited;
12594 
12595   for (unsigned i = 0; i < 2; ++i) {
12596     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12597           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12598           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12599           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12600         isa<ConstantSDNode>(N->getOperand(i)))
12601       Inputs.push_back(N->getOperand(i));
12602     else
12603       BinOps.push_back(N->getOperand(i));
12604 
12605     if (N->getOpcode() == ISD::TRUNCATE)
12606       break;
12607   }
12608 
12609   // Visit all inputs, collect all binary operations (and, or, xor and
12610   // select) that are all fed by extensions.
12611   while (!BinOps.empty()) {
12612     SDValue BinOp = BinOps.back();
12613     BinOps.pop_back();
12614 
12615     if (!Visited.insert(BinOp.getNode()).second)
12616       continue;
12617 
12618     PromOps.push_back(BinOp);
12619 
12620     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12621       // The condition of the select is not promoted.
12622       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12623         continue;
12624       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12625         continue;
12626 
12627       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12628             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12629             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12630            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12631           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12632         Inputs.push_back(BinOp.getOperand(i));
12633       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12634                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12635                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12636                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12637                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12638                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12639                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12640                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12641                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12642         BinOps.push_back(BinOp.getOperand(i));
12643       } else {
12644         // We have an input that is not an extension or another binary
12645         // operation; we'll abort this transformation.
12646         return SDValue();
12647       }
12648     }
12649   }
12650 
12651   // Make sure that this is a self-contained cluster of operations (which
12652   // is not quite the same thing as saying that everything has only one
12653   // use).
12654   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12655     if (isa<ConstantSDNode>(Inputs[i]))
12656       continue;
12657 
12658     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12659                               UE = Inputs[i].getNode()->use_end();
12660          UI != UE; ++UI) {
12661       SDNode *User = *UI;
12662       if (User != N && !Visited.count(User))
12663         return SDValue();
12664 
12665       // Make sure that we're not going to promote the non-output-value
12666       // operand(s) or SELECT or SELECT_CC.
12667       // FIXME: Although we could sometimes handle this, and it does occur in
12668       // practice that one of the condition inputs to the select is also one of
12669       // the outputs, we currently can't deal with this.
12670       if (User->getOpcode() == ISD::SELECT) {
12671         if (User->getOperand(0) == Inputs[i])
12672           return SDValue();
12673       } else if (User->getOpcode() == ISD::SELECT_CC) {
12674         if (User->getOperand(0) == Inputs[i] ||
12675             User->getOperand(1) == Inputs[i])
12676           return SDValue();
12677       }
12678     }
12679   }
12680 
12681   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12682     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12683                               UE = PromOps[i].getNode()->use_end();
12684          UI != UE; ++UI) {
12685       SDNode *User = *UI;
12686       if (User != N && !Visited.count(User))
12687         return SDValue();
12688 
12689       // Make sure that we're not going to promote the non-output-value
12690       // operand(s) or SELECT or SELECT_CC.
12691       // FIXME: Although we could sometimes handle this, and it does occur in
12692       // practice that one of the condition inputs to the select is also one of
12693       // the outputs, we currently can't deal with this.
12694       if (User->getOpcode() == ISD::SELECT) {
12695         if (User->getOperand(0) == PromOps[i])
12696           return SDValue();
12697       } else if (User->getOpcode() == ISD::SELECT_CC) {
12698         if (User->getOperand(0) == PromOps[i] ||
12699             User->getOperand(1) == PromOps[i])
12700           return SDValue();
12701       }
12702     }
12703   }
12704 
12705   // Replace all inputs with the extension operand.
12706   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12707     // Constants may have users outside the cluster of to-be-promoted nodes,
12708     // and so we need to replace those as we do the promotions.
12709     if (isa<ConstantSDNode>(Inputs[i]))
12710       continue;
12711     else
12712       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12713   }
12714 
12715   std::list<HandleSDNode> PromOpHandles;
12716   for (auto &PromOp : PromOps)
12717     PromOpHandles.emplace_back(PromOp);
12718 
12719   // Replace all operations (these are all the same, but have a different
12720   // (i1) return type). DAG.getNode will validate that the types of
12721   // a binary operator match, so go through the list in reverse so that
12722   // we've likely promoted both operands first. Any intermediate truncations or
12723   // extensions disappear.
12724   while (!PromOpHandles.empty()) {
12725     SDValue PromOp = PromOpHandles.back().getValue();
12726     PromOpHandles.pop_back();
12727 
12728     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12729         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12730         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12731         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12732       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12733           PromOp.getOperand(0).getValueType() != MVT::i1) {
12734         // The operand is not yet ready (see comment below).
12735         PromOpHandles.emplace_front(PromOp);
12736         continue;
12737       }
12738 
12739       SDValue RepValue = PromOp.getOperand(0);
12740       if (isa<ConstantSDNode>(RepValue))
12741         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12742 
12743       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12744       continue;
12745     }
12746 
12747     unsigned C;
12748     switch (PromOp.getOpcode()) {
12749     default:             C = 0; break;
12750     case ISD::SELECT:    C = 1; break;
12751     case ISD::SELECT_CC: C = 2; break;
12752     }
12753 
12754     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12755          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12756         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12757          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12758       // The to-be-promoted operands of this node have not yet been
12759       // promoted (this should be rare because we're going through the
12760       // list backward, but if one of the operands has several users in
12761       // this cluster of to-be-promoted nodes, it is possible).
12762       PromOpHandles.emplace_front(PromOp);
12763       continue;
12764     }
12765 
12766     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12767                                 PromOp.getNode()->op_end());
12768 
12769     // If there are any constant inputs, make sure they're replaced now.
12770     for (unsigned i = 0; i < 2; ++i)
12771       if (isa<ConstantSDNode>(Ops[C+i]))
12772         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12773 
12774     DAG.ReplaceAllUsesOfValueWith(PromOp,
12775       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12776   }
12777 
12778   // Now we're left with the initial truncation itself.
12779   if (N->getOpcode() == ISD::TRUNCATE)
12780     return N->getOperand(0);
12781 
12782   // Otherwise, this is a comparison. The operands to be compared have just
12783   // changed type (to i1), but everything else is the same.
12784   return SDValue(N, 0);
12785 }
12786 
12787 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12788                                                   DAGCombinerInfo &DCI) const {
12789   SelectionDAG &DAG = DCI.DAG;
12790   SDLoc dl(N);
12791 
12792   // If we're tracking CR bits, we need to be careful that we don't have:
12793   //   zext(binary-ops(trunc(x), trunc(y)))
12794   // or
12795   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12796   // such that we're unnecessarily moving things into CR bits that can more
12797   // efficiently stay in GPRs. Note that if we're not certain that the high
12798   // bits are set as required by the final extension, we still may need to do
12799   // some masking to get the proper behavior.
12800 
12801   // This same functionality is important on PPC64 when dealing with
12802   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12803   // the return values of functions. Because it is so similar, it is handled
12804   // here as well.
12805 
12806   if (N->getValueType(0) != MVT::i32 &&
12807       N->getValueType(0) != MVT::i64)
12808     return SDValue();
12809 
12810   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12811         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12812     return SDValue();
12813 
12814   if (N->getOperand(0).getOpcode() != ISD::AND &&
12815       N->getOperand(0).getOpcode() != ISD::OR  &&
12816       N->getOperand(0).getOpcode() != ISD::XOR &&
12817       N->getOperand(0).getOpcode() != ISD::SELECT &&
12818       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12819     return SDValue();
12820 
12821   SmallVector<SDValue, 4> Inputs;
12822   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12823   SmallPtrSet<SDNode *, 16> Visited;
12824 
12825   // Visit all inputs, collect all binary operations (and, or, xor and
12826   // select) that are all fed by truncations.
12827   while (!BinOps.empty()) {
12828     SDValue BinOp = BinOps.back();
12829     BinOps.pop_back();
12830 
12831     if (!Visited.insert(BinOp.getNode()).second)
12832       continue;
12833 
12834     PromOps.push_back(BinOp);
12835 
12836     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12837       // The condition of the select is not promoted.
12838       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12839         continue;
12840       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12841         continue;
12842 
12843       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12844           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12845         Inputs.push_back(BinOp.getOperand(i));
12846       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12847                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12848                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12849                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12850                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12851         BinOps.push_back(BinOp.getOperand(i));
12852       } else {
12853         // We have an input that is not a truncation or another binary
12854         // operation; we'll abort this transformation.
12855         return SDValue();
12856       }
12857     }
12858   }
12859 
12860   // The operands of a select that must be truncated when the select is
12861   // promoted because the operand is actually part of the to-be-promoted set.
12862   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12863 
12864   // Make sure that this is a self-contained cluster of operations (which
12865   // is not quite the same thing as saying that everything has only one
12866   // use).
12867   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12868     if (isa<ConstantSDNode>(Inputs[i]))
12869       continue;
12870 
12871     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12872                               UE = Inputs[i].getNode()->use_end();
12873          UI != UE; ++UI) {
12874       SDNode *User = *UI;
12875       if (User != N && !Visited.count(User))
12876         return SDValue();
12877 
12878       // If we're going to promote the non-output-value operand(s) or SELECT or
12879       // SELECT_CC, record them for truncation.
12880       if (User->getOpcode() == ISD::SELECT) {
12881         if (User->getOperand(0) == Inputs[i])
12882           SelectTruncOp[0].insert(std::make_pair(User,
12883                                     User->getOperand(0).getValueType()));
12884       } else if (User->getOpcode() == ISD::SELECT_CC) {
12885         if (User->getOperand(0) == Inputs[i])
12886           SelectTruncOp[0].insert(std::make_pair(User,
12887                                     User->getOperand(0).getValueType()));
12888         if (User->getOperand(1) == Inputs[i])
12889           SelectTruncOp[1].insert(std::make_pair(User,
12890                                     User->getOperand(1).getValueType()));
12891       }
12892     }
12893   }
12894 
12895   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12896     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12897                               UE = PromOps[i].getNode()->use_end();
12898          UI != UE; ++UI) {
12899       SDNode *User = *UI;
12900       if (User != N && !Visited.count(User))
12901         return SDValue();
12902 
12903       // If we're going to promote the non-output-value operand(s) or SELECT or
12904       // SELECT_CC, record them for truncation.
12905       if (User->getOpcode() == ISD::SELECT) {
12906         if (User->getOperand(0) == PromOps[i])
12907           SelectTruncOp[0].insert(std::make_pair(User,
12908                                     User->getOperand(0).getValueType()));
12909       } else if (User->getOpcode() == ISD::SELECT_CC) {
12910         if (User->getOperand(0) == PromOps[i])
12911           SelectTruncOp[0].insert(std::make_pair(User,
12912                                     User->getOperand(0).getValueType()));
12913         if (User->getOperand(1) == PromOps[i])
12914           SelectTruncOp[1].insert(std::make_pair(User,
12915                                     User->getOperand(1).getValueType()));
12916       }
12917     }
12918   }
12919 
12920   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12921   bool ReallyNeedsExt = false;
12922   if (N->getOpcode() != ISD::ANY_EXTEND) {
12923     // If all of the inputs are not already sign/zero extended, then
12924     // we'll still need to do that at the end.
12925     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12926       if (isa<ConstantSDNode>(Inputs[i]))
12927         continue;
12928 
12929       unsigned OpBits =
12930         Inputs[i].getOperand(0).getValueSizeInBits();
12931       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12932 
12933       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12934            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12935                                   APInt::getHighBitsSet(OpBits,
12936                                                         OpBits-PromBits))) ||
12937           (N->getOpcode() == ISD::SIGN_EXTEND &&
12938            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12939              (OpBits-(PromBits-1)))) {
12940         ReallyNeedsExt = true;
12941         break;
12942       }
12943     }
12944   }
12945 
12946   // Replace all inputs, either with the truncation operand, or a
12947   // truncation or extension to the final output type.
12948   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12949     // Constant inputs need to be replaced with the to-be-promoted nodes that
12950     // use them because they might have users outside of the cluster of
12951     // promoted nodes.
12952     if (isa<ConstantSDNode>(Inputs[i]))
12953       continue;
12954 
12955     SDValue InSrc = Inputs[i].getOperand(0);
12956     if (Inputs[i].getValueType() == N->getValueType(0))
12957       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12958     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12959       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12960         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12961     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12962       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12963         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12964     else
12965       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12966         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12967   }
12968 
12969   std::list<HandleSDNode> PromOpHandles;
12970   for (auto &PromOp : PromOps)
12971     PromOpHandles.emplace_back(PromOp);
12972 
12973   // Replace all operations (these are all the same, but have a different
12974   // (promoted) return type). DAG.getNode will validate that the types of
12975   // a binary operator match, so go through the list in reverse so that
12976   // we've likely promoted both operands first.
12977   while (!PromOpHandles.empty()) {
12978     SDValue PromOp = PromOpHandles.back().getValue();
12979     PromOpHandles.pop_back();
12980 
12981     unsigned C;
12982     switch (PromOp.getOpcode()) {
12983     default:             C = 0; break;
12984     case ISD::SELECT:    C = 1; break;
12985     case ISD::SELECT_CC: C = 2; break;
12986     }
12987 
12988     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12989          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12990         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12991          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12992       // The to-be-promoted operands of this node have not yet been
12993       // promoted (this should be rare because we're going through the
12994       // list backward, but if one of the operands has several users in
12995       // this cluster of to-be-promoted nodes, it is possible).
12996       PromOpHandles.emplace_front(PromOp);
12997       continue;
12998     }
12999 
13000     // For SELECT and SELECT_CC nodes, we do a similar check for any
13001     // to-be-promoted comparison inputs.
13002     if (PromOp.getOpcode() == ISD::SELECT ||
13003         PromOp.getOpcode() == ISD::SELECT_CC) {
13004       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13005            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13006           (SelectTruncOp[1].count(PromOp.getNode()) &&
13007            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13008         PromOpHandles.emplace_front(PromOp);
13009         continue;
13010       }
13011     }
13012 
13013     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13014                                 PromOp.getNode()->op_end());
13015 
13016     // If this node has constant inputs, then they'll need to be promoted here.
13017     for (unsigned i = 0; i < 2; ++i) {
13018       if (!isa<ConstantSDNode>(Ops[C+i]))
13019         continue;
13020       if (Ops[C+i].getValueType() == N->getValueType(0))
13021         continue;
13022 
13023       if (N->getOpcode() == ISD::SIGN_EXTEND)
13024         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13025       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13026         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13027       else
13028         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13029     }
13030 
13031     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13032     // truncate them again to the original value type.
13033     if (PromOp.getOpcode() == ISD::SELECT ||
13034         PromOp.getOpcode() == ISD::SELECT_CC) {
13035       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13036       if (SI0 != SelectTruncOp[0].end())
13037         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13038       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13039       if (SI1 != SelectTruncOp[1].end())
13040         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13041     }
13042 
13043     DAG.ReplaceAllUsesOfValueWith(PromOp,
13044       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13045   }
13046 
13047   // Now we're left with the initial extension itself.
13048   if (!ReallyNeedsExt)
13049     return N->getOperand(0);
13050 
13051   // To zero extend, just mask off everything except for the first bit (in the
13052   // i1 case).
13053   if (N->getOpcode() == ISD::ZERO_EXTEND)
13054     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13055                        DAG.getConstant(APInt::getLowBitsSet(
13056                                          N->getValueSizeInBits(0), PromBits),
13057                                        dl, N->getValueType(0)));
13058 
13059   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13060          "Invalid extension type");
13061   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13062   SDValue ShiftCst =
13063       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13064   return DAG.getNode(
13065       ISD::SRA, dl, N->getValueType(0),
13066       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13067       ShiftCst);
13068 }
13069 
13070 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13071                                         DAGCombinerInfo &DCI) const {
13072   assert(N->getOpcode() == ISD::SETCC &&
13073          "Should be called with a SETCC node");
13074 
13075   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13076   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13077     SDValue LHS = N->getOperand(0);
13078     SDValue RHS = N->getOperand(1);
13079 
13080     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13081     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13082         LHS.hasOneUse())
13083       std::swap(LHS, RHS);
13084 
13085     // x == 0-y --> x+y == 0
13086     // x != 0-y --> x+y != 0
13087     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13088         RHS.hasOneUse()) {
13089       SDLoc DL(N);
13090       SelectionDAG &DAG = DCI.DAG;
13091       EVT VT = N->getValueType(0);
13092       EVT OpVT = LHS.getValueType();
13093       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13094       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13095     }
13096   }
13097 
13098   return DAGCombineTruncBoolExt(N, DCI);
13099 }
13100 
13101 // Is this an extending load from an f32 to an f64?
13102 static bool isFPExtLoad(SDValue Op) {
13103   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13104     return LD->getExtensionType() == ISD::EXTLOAD &&
13105       Op.getValueType() == MVT::f64;
13106   return false;
13107 }
13108 
13109 /// Reduces the number of fp-to-int conversion when building a vector.
13110 ///
13111 /// If this vector is built out of floating to integer conversions,
13112 /// transform it to a vector built out of floating point values followed by a
13113 /// single floating to integer conversion of the vector.
13114 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13115 /// becomes (fptosi (build_vector ($A, $B, ...)))
13116 SDValue PPCTargetLowering::
13117 combineElementTruncationToVectorTruncation(SDNode *N,
13118                                            DAGCombinerInfo &DCI) const {
13119   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13120          "Should be called with a BUILD_VECTOR node");
13121 
13122   SelectionDAG &DAG = DCI.DAG;
13123   SDLoc dl(N);
13124 
13125   SDValue FirstInput = N->getOperand(0);
13126   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13127          "The input operand must be an fp-to-int conversion.");
13128 
13129   // This combine happens after legalization so the fp_to_[su]i nodes are
13130   // already converted to PPCSISD nodes.
13131   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13132   if (FirstConversion == PPCISD::FCTIDZ ||
13133       FirstConversion == PPCISD::FCTIDUZ ||
13134       FirstConversion == PPCISD::FCTIWZ ||
13135       FirstConversion == PPCISD::FCTIWUZ) {
13136     bool IsSplat = true;
13137     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13138       FirstConversion == PPCISD::FCTIWUZ;
13139     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13140     SmallVector<SDValue, 4> Ops;
13141     EVT TargetVT = N->getValueType(0);
13142     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13143       SDValue NextOp = N->getOperand(i);
13144       if (NextOp.getOpcode() != PPCISD::MFVSR)
13145         return SDValue();
13146       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13147       if (NextConversion != FirstConversion)
13148         return SDValue();
13149       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13150       // This is not valid if the input was originally double precision. It is
13151       // also not profitable to do unless this is an extending load in which
13152       // case doing this combine will allow us to combine consecutive loads.
13153       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13154         return SDValue();
13155       if (N->getOperand(i) != FirstInput)
13156         IsSplat = false;
13157     }
13158 
13159     // If this is a splat, we leave it as-is since there will be only a single
13160     // fp-to-int conversion followed by a splat of the integer. This is better
13161     // for 32-bit and smaller ints and neutral for 64-bit ints.
13162     if (IsSplat)
13163       return SDValue();
13164 
13165     // Now that we know we have the right type of node, get its operands
13166     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13167       SDValue In = N->getOperand(i).getOperand(0);
13168       if (Is32Bit) {
13169         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13170         // here, we know that all inputs are extending loads so this is safe).
13171         if (In.isUndef())
13172           Ops.push_back(DAG.getUNDEF(SrcVT));
13173         else {
13174           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13175                                       MVT::f32, In.getOperand(0),
13176                                       DAG.getIntPtrConstant(1, dl));
13177           Ops.push_back(Trunc);
13178         }
13179       } else
13180         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13181     }
13182 
13183     unsigned Opcode;
13184     if (FirstConversion == PPCISD::FCTIDZ ||
13185         FirstConversion == PPCISD::FCTIWZ)
13186       Opcode = ISD::FP_TO_SINT;
13187     else
13188       Opcode = ISD::FP_TO_UINT;
13189 
13190     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13191     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13192     return DAG.getNode(Opcode, dl, TargetVT, BV);
13193   }
13194   return SDValue();
13195 }
13196 
13197 /// Reduce the number of loads when building a vector.
13198 ///
13199 /// Building a vector out of multiple loads can be converted to a load
13200 /// of the vector type if the loads are consecutive. If the loads are
13201 /// consecutive but in descending order, a shuffle is added at the end
13202 /// to reorder the vector.
13203 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13204   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13205          "Should be called with a BUILD_VECTOR node");
13206 
13207   SDLoc dl(N);
13208 
13209   // Return early for non byte-sized type, as they can't be consecutive.
13210   if (!N->getValueType(0).getVectorElementType().isByteSized())
13211     return SDValue();
13212 
13213   bool InputsAreConsecutiveLoads = true;
13214   bool InputsAreReverseConsecutive = true;
13215   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13216   SDValue FirstInput = N->getOperand(0);
13217   bool IsRoundOfExtLoad = false;
13218 
13219   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13220       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13221     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13222     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13223   }
13224   // Not a build vector of (possibly fp_rounded) loads.
13225   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13226       N->getNumOperands() == 1)
13227     return SDValue();
13228 
13229   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13230     // If any inputs are fp_round(extload), they all must be.
13231     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13232       return SDValue();
13233 
13234     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13235       N->getOperand(i);
13236     if (NextInput.getOpcode() != ISD::LOAD)
13237       return SDValue();
13238 
13239     SDValue PreviousInput =
13240       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13241     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13242     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13243 
13244     // If any inputs are fp_round(extload), they all must be.
13245     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13246       return SDValue();
13247 
13248     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13249       InputsAreConsecutiveLoads = false;
13250     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13251       InputsAreReverseConsecutive = false;
13252 
13253     // Exit early if the loads are neither consecutive nor reverse consecutive.
13254     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13255       return SDValue();
13256   }
13257 
13258   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13259          "The loads cannot be both consecutive and reverse consecutive.");
13260 
13261   SDValue FirstLoadOp =
13262     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13263   SDValue LastLoadOp =
13264     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13265                        N->getOperand(N->getNumOperands()-1);
13266 
13267   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13268   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13269   if (InputsAreConsecutiveLoads) {
13270     assert(LD1 && "Input needs to be a LoadSDNode.");
13271     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13272                        LD1->getBasePtr(), LD1->getPointerInfo(),
13273                        LD1->getAlignment());
13274   }
13275   if (InputsAreReverseConsecutive) {
13276     assert(LDL && "Input needs to be a LoadSDNode.");
13277     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13278                                LDL->getBasePtr(), LDL->getPointerInfo(),
13279                                LDL->getAlignment());
13280     SmallVector<int, 16> Ops;
13281     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13282       Ops.push_back(i);
13283 
13284     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13285                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13286   }
13287   return SDValue();
13288 }
13289 
13290 // This function adds the required vector_shuffle needed to get
13291 // the elements of the vector extract in the correct position
13292 // as specified by the CorrectElems encoding.
13293 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13294                                       SDValue Input, uint64_t Elems,
13295                                       uint64_t CorrectElems) {
13296   SDLoc dl(N);
13297 
13298   unsigned NumElems = Input.getValueType().getVectorNumElements();
13299   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13300 
13301   // Knowing the element indices being extracted from the original
13302   // vector and the order in which they're being inserted, just put
13303   // them at element indices required for the instruction.
13304   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13305     if (DAG.getDataLayout().isLittleEndian())
13306       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13307     else
13308       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13309     CorrectElems = CorrectElems >> 8;
13310     Elems = Elems >> 8;
13311   }
13312 
13313   SDValue Shuffle =
13314       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13315                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13316 
13317   EVT VT = N->getValueType(0);
13318   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13319 
13320   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13321                                Input.getValueType().getVectorElementType(),
13322                                VT.getVectorNumElements());
13323   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13324                      DAG.getValueType(ExtVT));
13325 }
13326 
13327 // Look for build vector patterns where input operands come from sign
13328 // extended vector_extract elements of specific indices. If the correct indices
13329 // aren't used, add a vector shuffle to fix up the indices and create
13330 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13331 // during instruction selection.
13332 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13333   // This array encodes the indices that the vector sign extend instructions
13334   // extract from when extending from one type to another for both BE and LE.
13335   // The right nibble of each byte corresponds to the LE incides.
13336   // and the left nibble of each byte corresponds to the BE incides.
13337   // For example: 0x3074B8FC  byte->word
13338   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13339   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13340   // For example: 0x000070F8  byte->double word
13341   // For LE: the allowed indices are: 0x0,0x8
13342   // For BE: the allowed indices are: 0x7,0xF
13343   uint64_t TargetElems[] = {
13344       0x3074B8FC, // b->w
13345       0x000070F8, // b->d
13346       0x10325476, // h->w
13347       0x00003074, // h->d
13348       0x00001032, // w->d
13349   };
13350 
13351   uint64_t Elems = 0;
13352   int Index;
13353   SDValue Input;
13354 
13355   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13356     if (!Op)
13357       return false;
13358     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13359         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13360       return false;
13361 
13362     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13363     // of the right width.
13364     SDValue Extract = Op.getOperand(0);
13365     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13366       Extract = Extract.getOperand(0);
13367     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13368       return false;
13369 
13370     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13371     if (!ExtOp)
13372       return false;
13373 
13374     Index = ExtOp->getZExtValue();
13375     if (Input && Input != Extract.getOperand(0))
13376       return false;
13377 
13378     if (!Input)
13379       Input = Extract.getOperand(0);
13380 
13381     Elems = Elems << 8;
13382     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13383     Elems |= Index;
13384 
13385     return true;
13386   };
13387 
13388   // If the build vector operands aren't sign extended vector extracts,
13389   // of the same input vector, then return.
13390   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13391     if (!isSExtOfVecExtract(N->getOperand(i))) {
13392       return SDValue();
13393     }
13394   }
13395 
13396   // If the vector extract indicies are not correct, add the appropriate
13397   // vector_shuffle.
13398   int TgtElemArrayIdx;
13399   int InputSize = Input.getValueType().getScalarSizeInBits();
13400   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13401   if (InputSize + OutputSize == 40)
13402     TgtElemArrayIdx = 0;
13403   else if (InputSize + OutputSize == 72)
13404     TgtElemArrayIdx = 1;
13405   else if (InputSize + OutputSize == 48)
13406     TgtElemArrayIdx = 2;
13407   else if (InputSize + OutputSize == 80)
13408     TgtElemArrayIdx = 3;
13409   else if (InputSize + OutputSize == 96)
13410     TgtElemArrayIdx = 4;
13411   else
13412     return SDValue();
13413 
13414   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13415   CorrectElems = DAG.getDataLayout().isLittleEndian()
13416                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13417                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13418   if (Elems != CorrectElems) {
13419     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13420   }
13421 
13422   // Regular lowering will catch cases where a shuffle is not needed.
13423   return SDValue();
13424 }
13425 
13426 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13427                                                  DAGCombinerInfo &DCI) const {
13428   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13429          "Should be called with a BUILD_VECTOR node");
13430 
13431   SelectionDAG &DAG = DCI.DAG;
13432   SDLoc dl(N);
13433 
13434   if (!Subtarget.hasVSX())
13435     return SDValue();
13436 
13437   // The target independent DAG combiner will leave a build_vector of
13438   // float-to-int conversions intact. We can generate MUCH better code for
13439   // a float-to-int conversion of a vector of floats.
13440   SDValue FirstInput = N->getOperand(0);
13441   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13442     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13443     if (Reduced)
13444       return Reduced;
13445   }
13446 
13447   // If we're building a vector out of consecutive loads, just load that
13448   // vector type.
13449   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13450   if (Reduced)
13451     return Reduced;
13452 
13453   // If we're building a vector out of extended elements from another vector
13454   // we have P9 vector integer extend instructions. The code assumes legal
13455   // input types (i.e. it can't handle things like v4i16) so do not run before
13456   // legalization.
13457   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13458     Reduced = combineBVOfVecSExt(N, DAG);
13459     if (Reduced)
13460       return Reduced;
13461   }
13462 
13463 
13464   if (N->getValueType(0) != MVT::v2f64)
13465     return SDValue();
13466 
13467   // Looking for:
13468   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13469   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13470       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13471     return SDValue();
13472   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13473       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13474     return SDValue();
13475   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13476     return SDValue();
13477 
13478   SDValue Ext1 = FirstInput.getOperand(0);
13479   SDValue Ext2 = N->getOperand(1).getOperand(0);
13480   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13481      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13482     return SDValue();
13483 
13484   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13485   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13486   if (!Ext1Op || !Ext2Op)
13487     return SDValue();
13488   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13489       Ext1.getOperand(0) != Ext2.getOperand(0))
13490     return SDValue();
13491 
13492   int FirstElem = Ext1Op->getZExtValue();
13493   int SecondElem = Ext2Op->getZExtValue();
13494   int SubvecIdx;
13495   if (FirstElem == 0 && SecondElem == 1)
13496     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13497   else if (FirstElem == 2 && SecondElem == 3)
13498     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13499   else
13500     return SDValue();
13501 
13502   SDValue SrcVec = Ext1.getOperand(0);
13503   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13504     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13505   return DAG.getNode(NodeType, dl, MVT::v2f64,
13506                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13507 }
13508 
13509 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13510                                               DAGCombinerInfo &DCI) const {
13511   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13512           N->getOpcode() == ISD::UINT_TO_FP) &&
13513          "Need an int -> FP conversion node here");
13514 
13515   if (useSoftFloat() || !Subtarget.has64BitSupport())
13516     return SDValue();
13517 
13518   SelectionDAG &DAG = DCI.DAG;
13519   SDLoc dl(N);
13520   SDValue Op(N, 0);
13521 
13522   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13523   // from the hardware.
13524   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13525     return SDValue();
13526   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13527       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13528     return SDValue();
13529 
13530   SDValue FirstOperand(Op.getOperand(0));
13531   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13532     (FirstOperand.getValueType() == MVT::i8 ||
13533      FirstOperand.getValueType() == MVT::i16);
13534   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13535     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13536     bool DstDouble = Op.getValueType() == MVT::f64;
13537     unsigned ConvOp = Signed ?
13538       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13539       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13540     SDValue WidthConst =
13541       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13542                             dl, false);
13543     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13544     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13545     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13546                                          DAG.getVTList(MVT::f64, MVT::Other),
13547                                          Ops, MVT::i8, LDN->getMemOperand());
13548 
13549     // For signed conversion, we need to sign-extend the value in the VSR
13550     if (Signed) {
13551       SDValue ExtOps[] = { Ld, WidthConst };
13552       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13553       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13554     } else
13555       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13556   }
13557 
13558 
13559   // For i32 intermediate values, unfortunately, the conversion functions
13560   // leave the upper 32 bits of the value are undefined. Within the set of
13561   // scalar instructions, we have no method for zero- or sign-extending the
13562   // value. Thus, we cannot handle i32 intermediate values here.
13563   if (Op.getOperand(0).getValueType() == MVT::i32)
13564     return SDValue();
13565 
13566   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13567          "UINT_TO_FP is supported only with FPCVT");
13568 
13569   // If we have FCFIDS, then use it when converting to single-precision.
13570   // Otherwise, convert to double-precision and then round.
13571   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13572                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13573                                                             : PPCISD::FCFIDS)
13574                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13575                                                             : PPCISD::FCFID);
13576   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13577                   ? MVT::f32
13578                   : MVT::f64;
13579 
13580   // If we're converting from a float, to an int, and back to a float again,
13581   // then we don't need the store/load pair at all.
13582   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13583        Subtarget.hasFPCVT()) ||
13584       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13585     SDValue Src = Op.getOperand(0).getOperand(0);
13586     if (Src.getValueType() == MVT::f32) {
13587       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13588       DCI.AddToWorklist(Src.getNode());
13589     } else if (Src.getValueType() != MVT::f64) {
13590       // Make sure that we don't pick up a ppc_fp128 source value.
13591       return SDValue();
13592     }
13593 
13594     unsigned FCTOp =
13595       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13596                                                         PPCISD::FCTIDUZ;
13597 
13598     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13599     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13600 
13601     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13602       FP = DAG.getNode(ISD::FP_ROUND, dl,
13603                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13604       DCI.AddToWorklist(FP.getNode());
13605     }
13606 
13607     return FP;
13608   }
13609 
13610   return SDValue();
13611 }
13612 
13613 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13614 // builtins) into loads with swaps.
13615 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13616                                               DAGCombinerInfo &DCI) const {
13617   SelectionDAG &DAG = DCI.DAG;
13618   SDLoc dl(N);
13619   SDValue Chain;
13620   SDValue Base;
13621   MachineMemOperand *MMO;
13622 
13623   switch (N->getOpcode()) {
13624   default:
13625     llvm_unreachable("Unexpected opcode for little endian VSX load");
13626   case ISD::LOAD: {
13627     LoadSDNode *LD = cast<LoadSDNode>(N);
13628     Chain = LD->getChain();
13629     Base = LD->getBasePtr();
13630     MMO = LD->getMemOperand();
13631     // If the MMO suggests this isn't a load of a full vector, leave
13632     // things alone.  For a built-in, we have to make the change for
13633     // correctness, so if there is a size problem that will be a bug.
13634     if (MMO->getSize() < 16)
13635       return SDValue();
13636     break;
13637   }
13638   case ISD::INTRINSIC_W_CHAIN: {
13639     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13640     Chain = Intrin->getChain();
13641     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13642     // us what we want. Get operand 2 instead.
13643     Base = Intrin->getOperand(2);
13644     MMO = Intrin->getMemOperand();
13645     break;
13646   }
13647   }
13648 
13649   MVT VecTy = N->getValueType(0).getSimpleVT();
13650 
13651   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13652   // aligned and the type is a vector with elements up to 4 bytes
13653   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13654       VecTy.getScalarSizeInBits() <= 32) {
13655     return SDValue();
13656   }
13657 
13658   SDValue LoadOps[] = { Chain, Base };
13659   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13660                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13661                                          LoadOps, MVT::v2f64, MMO);
13662 
13663   DCI.AddToWorklist(Load.getNode());
13664   Chain = Load.getValue(1);
13665   SDValue Swap = DAG.getNode(
13666       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13667   DCI.AddToWorklist(Swap.getNode());
13668 
13669   // Add a bitcast if the resulting load type doesn't match v2f64.
13670   if (VecTy != MVT::v2f64) {
13671     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13672     DCI.AddToWorklist(N.getNode());
13673     // Package {bitcast value, swap's chain} to match Load's shape.
13674     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13675                        N, Swap.getValue(1));
13676   }
13677 
13678   return Swap;
13679 }
13680 
13681 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13682 // builtins) into stores with swaps.
13683 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13684                                                DAGCombinerInfo &DCI) const {
13685   SelectionDAG &DAG = DCI.DAG;
13686   SDLoc dl(N);
13687   SDValue Chain;
13688   SDValue Base;
13689   unsigned SrcOpnd;
13690   MachineMemOperand *MMO;
13691 
13692   switch (N->getOpcode()) {
13693   default:
13694     llvm_unreachable("Unexpected opcode for little endian VSX store");
13695   case ISD::STORE: {
13696     StoreSDNode *ST = cast<StoreSDNode>(N);
13697     Chain = ST->getChain();
13698     Base = ST->getBasePtr();
13699     MMO = ST->getMemOperand();
13700     SrcOpnd = 1;
13701     // If the MMO suggests this isn't a store of a full vector, leave
13702     // things alone.  For a built-in, we have to make the change for
13703     // correctness, so if there is a size problem that will be a bug.
13704     if (MMO->getSize() < 16)
13705       return SDValue();
13706     break;
13707   }
13708   case ISD::INTRINSIC_VOID: {
13709     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13710     Chain = Intrin->getChain();
13711     // Intrin->getBasePtr() oddly does not get what we want.
13712     Base = Intrin->getOperand(3);
13713     MMO = Intrin->getMemOperand();
13714     SrcOpnd = 2;
13715     break;
13716   }
13717   }
13718 
13719   SDValue Src = N->getOperand(SrcOpnd);
13720   MVT VecTy = Src.getValueType().getSimpleVT();
13721 
13722   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13723   // aligned and the type is a vector with elements up to 4 bytes
13724   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13725       VecTy.getScalarSizeInBits() <= 32) {
13726     return SDValue();
13727   }
13728 
13729   // All stores are done as v2f64 and possible bit cast.
13730   if (VecTy != MVT::v2f64) {
13731     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13732     DCI.AddToWorklist(Src.getNode());
13733   }
13734 
13735   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13736                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13737   DCI.AddToWorklist(Swap.getNode());
13738   Chain = Swap.getValue(1);
13739   SDValue StoreOps[] = { Chain, Swap, Base };
13740   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13741                                           DAG.getVTList(MVT::Other),
13742                                           StoreOps, VecTy, MMO);
13743   DCI.AddToWorklist(Store.getNode());
13744   return Store;
13745 }
13746 
13747 // Handle DAG combine for STORE (FP_TO_INT F).
13748 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13749                                                DAGCombinerInfo &DCI) const {
13750 
13751   SelectionDAG &DAG = DCI.DAG;
13752   SDLoc dl(N);
13753   unsigned Opcode = N->getOperand(1).getOpcode();
13754 
13755   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13756          && "Not a FP_TO_INT Instruction!");
13757 
13758   SDValue Val = N->getOperand(1).getOperand(0);
13759   EVT Op1VT = N->getOperand(1).getValueType();
13760   EVT ResVT = Val.getValueType();
13761 
13762   // Floating point types smaller than 32 bits are not legal on Power.
13763   if (ResVT.getScalarSizeInBits() < 32)
13764     return SDValue();
13765 
13766   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13767   bool ValidTypeForStoreFltAsInt =
13768         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13769          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13770 
13771   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13772       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13773     return SDValue();
13774 
13775   // Extend f32 values to f64
13776   if (ResVT.getScalarSizeInBits() == 32) {
13777     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13778     DCI.AddToWorklist(Val.getNode());
13779   }
13780 
13781   // Set signed or unsigned conversion opcode.
13782   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13783                           PPCISD::FP_TO_SINT_IN_VSR :
13784                           PPCISD::FP_TO_UINT_IN_VSR;
13785 
13786   Val = DAG.getNode(ConvOpcode,
13787                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13788   DCI.AddToWorklist(Val.getNode());
13789 
13790   // Set number of bytes being converted.
13791   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13792   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13793                     DAG.getIntPtrConstant(ByteSize, dl, false),
13794                     DAG.getValueType(Op1VT) };
13795 
13796   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13797           DAG.getVTList(MVT::Other), Ops,
13798           cast<StoreSDNode>(N)->getMemoryVT(),
13799           cast<StoreSDNode>(N)->getMemOperand());
13800 
13801   DCI.AddToWorklist(Val.getNode());
13802   return Val;
13803 }
13804 
13805 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13806                                                 LSBaseSDNode *LSBase,
13807                                                 DAGCombinerInfo &DCI) const {
13808   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13809         "Not a reverse memop pattern!");
13810 
13811   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13812     auto Mask = SVN->getMask();
13813     int i = 0;
13814     auto I = Mask.rbegin();
13815     auto E = Mask.rend();
13816 
13817     for (; I != E; ++I) {
13818       if (*I != i)
13819         return false;
13820       i++;
13821     }
13822     return true;
13823   };
13824 
13825   SelectionDAG &DAG = DCI.DAG;
13826   EVT VT = SVN->getValueType(0);
13827 
13828   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13829     return SDValue();
13830 
13831   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13832   // See comment in PPCVSXSwapRemoval.cpp.
13833   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13834   if (!Subtarget.hasP9Vector())
13835     return SDValue();
13836 
13837   if(!IsElementReverse(SVN))
13838     return SDValue();
13839 
13840   if (LSBase->getOpcode() == ISD::LOAD) {
13841     SDLoc dl(SVN);
13842     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13843     return DAG.getMemIntrinsicNode(
13844         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13845         LSBase->getMemoryVT(), LSBase->getMemOperand());
13846   }
13847 
13848   if (LSBase->getOpcode() == ISD::STORE) {
13849     SDLoc dl(LSBase);
13850     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13851                           LSBase->getBasePtr()};
13852     return DAG.getMemIntrinsicNode(
13853         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13854         LSBase->getMemoryVT(), LSBase->getMemOperand());
13855   }
13856 
13857   llvm_unreachable("Expected a load or store node here");
13858 }
13859 
13860 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13861                                              DAGCombinerInfo &DCI) const {
13862   SelectionDAG &DAG = DCI.DAG;
13863   SDLoc dl(N);
13864   switch (N->getOpcode()) {
13865   default: break;
13866   case ISD::ADD:
13867     return combineADD(N, DCI);
13868   case ISD::SHL:
13869     return combineSHL(N, DCI);
13870   case ISD::SRA:
13871     return combineSRA(N, DCI);
13872   case ISD::SRL:
13873     return combineSRL(N, DCI);
13874   case ISD::MUL:
13875     return combineMUL(N, DCI);
13876   case PPCISD::SHL:
13877     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13878         return N->getOperand(0);
13879     break;
13880   case PPCISD::SRL:
13881     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13882         return N->getOperand(0);
13883     break;
13884   case PPCISD::SRA:
13885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13886       if (C->isNullValue() ||   //  0 >>s V -> 0.
13887           C->isAllOnesValue())    // -1 >>s V -> -1.
13888         return N->getOperand(0);
13889     }
13890     break;
13891   case ISD::SIGN_EXTEND:
13892   case ISD::ZERO_EXTEND:
13893   case ISD::ANY_EXTEND:
13894     return DAGCombineExtBoolTrunc(N, DCI);
13895   case ISD::TRUNCATE:
13896     return combineTRUNCATE(N, DCI);
13897   case ISD::SETCC:
13898     if (SDValue CSCC = combineSetCC(N, DCI))
13899       return CSCC;
13900     LLVM_FALLTHROUGH;
13901   case ISD::SELECT_CC:
13902     return DAGCombineTruncBoolExt(N, DCI);
13903   case ISD::SINT_TO_FP:
13904   case ISD::UINT_TO_FP:
13905     return combineFPToIntToFP(N, DCI);
13906   case ISD::VECTOR_SHUFFLE:
13907     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13908       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13909       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13910     }
13911     break;
13912   case ISD::STORE: {
13913 
13914     EVT Op1VT = N->getOperand(1).getValueType();
13915     unsigned Opcode = N->getOperand(1).getOpcode();
13916 
13917     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13918       SDValue Val= combineStoreFPToInt(N, DCI);
13919       if (Val)
13920         return Val;
13921     }
13922 
13923     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13924       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13925       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13926       if (Val)
13927         return Val;
13928     }
13929 
13930     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13931     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13932         N->getOperand(1).getNode()->hasOneUse() &&
13933         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13934          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13935 
13936       // STBRX can only handle simple types and it makes no sense to store less
13937       // two bytes in byte-reversed order.
13938       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13939       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13940         break;
13941 
13942       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13943       // Do an any-extend to 32-bits if this is a half-word input.
13944       if (BSwapOp.getValueType() == MVT::i16)
13945         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13946 
13947       // If the type of BSWAP operand is wider than stored memory width
13948       // it need to be shifted to the right side before STBRX.
13949       if (Op1VT.bitsGT(mVT)) {
13950         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13951         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13952                               DAG.getConstant(Shift, dl, MVT::i32));
13953         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13954         if (Op1VT == MVT::i64)
13955           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13956       }
13957 
13958       SDValue Ops[] = {
13959         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13960       };
13961       return
13962         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13963                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13964                                 cast<StoreSDNode>(N)->getMemOperand());
13965     }
13966 
13967     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13968     // So it can increase the chance of CSE constant construction.
13969     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13970         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13971       // Need to sign-extended to 64-bits to handle negative values.
13972       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13973       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13974                                     MemVT.getSizeInBits());
13975       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13976 
13977       // DAG.getTruncStore() can't be used here because it doesn't accept
13978       // the general (base + offset) addressing mode.
13979       // So we use UpdateNodeOperands and setTruncatingStore instead.
13980       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13981                              N->getOperand(3));
13982       cast<StoreSDNode>(N)->setTruncatingStore(true);
13983       return SDValue(N, 0);
13984     }
13985 
13986     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13987     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13988     if (Op1VT.isSimple()) {
13989       MVT StoreVT = Op1VT.getSimpleVT();
13990       if (Subtarget.needsSwapsForVSXMemOps() &&
13991           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13992            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13993         return expandVSXStoreForLE(N, DCI);
13994     }
13995     break;
13996   }
13997   case ISD::LOAD: {
13998     LoadSDNode *LD = cast<LoadSDNode>(N);
13999     EVT VT = LD->getValueType(0);
14000 
14001     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14002     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14003     if (VT.isSimple()) {
14004       MVT LoadVT = VT.getSimpleVT();
14005       if (Subtarget.needsSwapsForVSXMemOps() &&
14006           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14007            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14008         return expandVSXLoadForLE(N, DCI);
14009     }
14010 
14011     // We sometimes end up with a 64-bit integer load, from which we extract
14012     // two single-precision floating-point numbers. This happens with
14013     // std::complex<float>, and other similar structures, because of the way we
14014     // canonicalize structure copies. However, if we lack direct moves,
14015     // then the final bitcasts from the extracted integer values to the
14016     // floating-point numbers turn into store/load pairs. Even with direct moves,
14017     // just loading the two floating-point numbers is likely better.
14018     auto ReplaceTwoFloatLoad = [&]() {
14019       if (VT != MVT::i64)
14020         return false;
14021 
14022       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14023           LD->isVolatile())
14024         return false;
14025 
14026       //  We're looking for a sequence like this:
14027       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14028       //      t16: i64 = srl t13, Constant:i32<32>
14029       //    t17: i32 = truncate t16
14030       //  t18: f32 = bitcast t17
14031       //    t19: i32 = truncate t13
14032       //  t20: f32 = bitcast t19
14033 
14034       if (!LD->hasNUsesOfValue(2, 0))
14035         return false;
14036 
14037       auto UI = LD->use_begin();
14038       while (UI.getUse().getResNo() != 0) ++UI;
14039       SDNode *Trunc = *UI++;
14040       while (UI.getUse().getResNo() != 0) ++UI;
14041       SDNode *RightShift = *UI;
14042       if (Trunc->getOpcode() != ISD::TRUNCATE)
14043         std::swap(Trunc, RightShift);
14044 
14045       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14046           Trunc->getValueType(0) != MVT::i32 ||
14047           !Trunc->hasOneUse())
14048         return false;
14049       if (RightShift->getOpcode() != ISD::SRL ||
14050           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14051           RightShift->getConstantOperandVal(1) != 32 ||
14052           !RightShift->hasOneUse())
14053         return false;
14054 
14055       SDNode *Trunc2 = *RightShift->use_begin();
14056       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14057           Trunc2->getValueType(0) != MVT::i32 ||
14058           !Trunc2->hasOneUse())
14059         return false;
14060 
14061       SDNode *Bitcast = *Trunc->use_begin();
14062       SDNode *Bitcast2 = *Trunc2->use_begin();
14063 
14064       if (Bitcast->getOpcode() != ISD::BITCAST ||
14065           Bitcast->getValueType(0) != MVT::f32)
14066         return false;
14067       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14068           Bitcast2->getValueType(0) != MVT::f32)
14069         return false;
14070 
14071       if (Subtarget.isLittleEndian())
14072         std::swap(Bitcast, Bitcast2);
14073 
14074       // Bitcast has the second float (in memory-layout order) and Bitcast2
14075       // has the first one.
14076 
14077       SDValue BasePtr = LD->getBasePtr();
14078       if (LD->isIndexed()) {
14079         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14080                "Non-pre-inc AM on PPC?");
14081         BasePtr =
14082           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14083                       LD->getOffset());
14084       }
14085 
14086       auto MMOFlags =
14087           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14088       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14089                                       LD->getPointerInfo(), LD->getAlignment(),
14090                                       MMOFlags, LD->getAAInfo());
14091       SDValue AddPtr =
14092         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14093                     BasePtr, DAG.getIntPtrConstant(4, dl));
14094       SDValue FloatLoad2 = DAG.getLoad(
14095           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14096           LD->getPointerInfo().getWithOffset(4),
14097           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14098 
14099       if (LD->isIndexed()) {
14100         // Note that DAGCombine should re-form any pre-increment load(s) from
14101         // what is produced here if that makes sense.
14102         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14103       }
14104 
14105       DCI.CombineTo(Bitcast2, FloatLoad);
14106       DCI.CombineTo(Bitcast, FloatLoad2);
14107 
14108       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14109                                     SDValue(FloatLoad2.getNode(), 1));
14110       return true;
14111     };
14112 
14113     if (ReplaceTwoFloatLoad())
14114       return SDValue(N, 0);
14115 
14116     EVT MemVT = LD->getMemoryVT();
14117     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14118     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14119     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14120     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14121     if (LD->isUnindexed() && VT.isVector() &&
14122         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14123           // P8 and later hardware should just use LOAD.
14124           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14125                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14126          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14127           LD->getAlignment() >= ScalarABIAlignment)) &&
14128         LD->getAlignment() < ABIAlignment) {
14129       // This is a type-legal unaligned Altivec or QPX load.
14130       SDValue Chain = LD->getChain();
14131       SDValue Ptr = LD->getBasePtr();
14132       bool isLittleEndian = Subtarget.isLittleEndian();
14133 
14134       // This implements the loading of unaligned vectors as described in
14135       // the venerable Apple Velocity Engine overview. Specifically:
14136       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14137       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14138       //
14139       // The general idea is to expand a sequence of one or more unaligned
14140       // loads into an alignment-based permutation-control instruction (lvsl
14141       // or lvsr), a series of regular vector loads (which always truncate
14142       // their input address to an aligned address), and a series of
14143       // permutations.  The results of these permutations are the requested
14144       // loaded values.  The trick is that the last "extra" load is not taken
14145       // from the address you might suspect (sizeof(vector) bytes after the
14146       // last requested load), but rather sizeof(vector) - 1 bytes after the
14147       // last requested vector. The point of this is to avoid a page fault if
14148       // the base address happened to be aligned. This works because if the
14149       // base address is aligned, then adding less than a full vector length
14150       // will cause the last vector in the sequence to be (re)loaded.
14151       // Otherwise, the next vector will be fetched as you might suspect was
14152       // necessary.
14153 
14154       // We might be able to reuse the permutation generation from
14155       // a different base address offset from this one by an aligned amount.
14156       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14157       // optimization later.
14158       Intrinsic::ID Intr, IntrLD, IntrPerm;
14159       MVT PermCntlTy, PermTy, LDTy;
14160       if (Subtarget.hasAltivec()) {
14161         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14162                                  Intrinsic::ppc_altivec_lvsl;
14163         IntrLD = Intrinsic::ppc_altivec_lvx;
14164         IntrPerm = Intrinsic::ppc_altivec_vperm;
14165         PermCntlTy = MVT::v16i8;
14166         PermTy = MVT::v4i32;
14167         LDTy = MVT::v4i32;
14168       } else {
14169         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14170                                        Intrinsic::ppc_qpx_qvlpcls;
14171         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14172                                        Intrinsic::ppc_qpx_qvlfs;
14173         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14174         PermCntlTy = MVT::v4f64;
14175         PermTy = MVT::v4f64;
14176         LDTy = MemVT.getSimpleVT();
14177       }
14178 
14179       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14180 
14181       // Create the new MMO for the new base load. It is like the original MMO,
14182       // but represents an area in memory almost twice the vector size centered
14183       // on the original address. If the address is unaligned, we might start
14184       // reading up to (sizeof(vector)-1) bytes below the address of the
14185       // original unaligned load.
14186       MachineFunction &MF = DAG.getMachineFunction();
14187       MachineMemOperand *BaseMMO =
14188         MF.getMachineMemOperand(LD->getMemOperand(),
14189                                 -(long)MemVT.getStoreSize()+1,
14190                                 2*MemVT.getStoreSize()-1);
14191 
14192       // Create the new base load.
14193       SDValue LDXIntID =
14194           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14195       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14196       SDValue BaseLoad =
14197         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14198                                 DAG.getVTList(PermTy, MVT::Other),
14199                                 BaseLoadOps, LDTy, BaseMMO);
14200 
14201       // Note that the value of IncOffset (which is provided to the next
14202       // load's pointer info offset value, and thus used to calculate the
14203       // alignment), and the value of IncValue (which is actually used to
14204       // increment the pointer value) are different! This is because we
14205       // require the next load to appear to be aligned, even though it
14206       // is actually offset from the base pointer by a lesser amount.
14207       int IncOffset = VT.getSizeInBits() / 8;
14208       int IncValue = IncOffset;
14209 
14210       // Walk (both up and down) the chain looking for another load at the real
14211       // (aligned) offset (the alignment of the other load does not matter in
14212       // this case). If found, then do not use the offset reduction trick, as
14213       // that will prevent the loads from being later combined (as they would
14214       // otherwise be duplicates).
14215       if (!findConsecutiveLoad(LD, DAG))
14216         --IncValue;
14217 
14218       SDValue Increment =
14219           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14220       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14221 
14222       MachineMemOperand *ExtraMMO =
14223         MF.getMachineMemOperand(LD->getMemOperand(),
14224                                 1, 2*MemVT.getStoreSize()-1);
14225       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14226       SDValue ExtraLoad =
14227         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14228                                 DAG.getVTList(PermTy, MVT::Other),
14229                                 ExtraLoadOps, LDTy, ExtraMMO);
14230 
14231       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14232         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14233 
14234       // Because vperm has a big-endian bias, we must reverse the order
14235       // of the input vectors and complement the permute control vector
14236       // when generating little endian code.  We have already handled the
14237       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14238       // and ExtraLoad here.
14239       SDValue Perm;
14240       if (isLittleEndian)
14241         Perm = BuildIntrinsicOp(IntrPerm,
14242                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14243       else
14244         Perm = BuildIntrinsicOp(IntrPerm,
14245                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14246 
14247       if (VT != PermTy)
14248         Perm = Subtarget.hasAltivec() ?
14249                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14250                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14251                                DAG.getTargetConstant(1, dl, MVT::i64));
14252                                // second argument is 1 because this rounding
14253                                // is always exact.
14254 
14255       // The output of the permutation is our loaded result, the TokenFactor is
14256       // our new chain.
14257       DCI.CombineTo(N, Perm, TF);
14258       return SDValue(N, 0);
14259     }
14260     }
14261     break;
14262     case ISD::INTRINSIC_WO_CHAIN: {
14263       bool isLittleEndian = Subtarget.isLittleEndian();
14264       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14265       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14266                                            : Intrinsic::ppc_altivec_lvsl);
14267       if ((IID == Intr ||
14268            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14269            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14270         N->getOperand(1)->getOpcode() == ISD::ADD) {
14271         SDValue Add = N->getOperand(1);
14272 
14273         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14274                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14275 
14276         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14277                                   APInt::getAllOnesValue(Bits /* alignment */)
14278                                       .zext(Add.getScalarValueSizeInBits()))) {
14279           SDNode *BasePtr = Add->getOperand(0).getNode();
14280           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14281                                     UE = BasePtr->use_end();
14282                UI != UE; ++UI) {
14283             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14284                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14285               // We've found another LVSL/LVSR, and this address is an aligned
14286               // multiple of that one. The results will be the same, so use the
14287               // one we've just found instead.
14288 
14289               return SDValue(*UI, 0);
14290             }
14291           }
14292         }
14293 
14294         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14295           SDNode *BasePtr = Add->getOperand(0).getNode();
14296           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14297                UE = BasePtr->use_end(); UI != UE; ++UI) {
14298             if (UI->getOpcode() == ISD::ADD &&
14299                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14300                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14301                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14302                 (1ULL << Bits) == 0) {
14303               SDNode *OtherAdd = *UI;
14304               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14305                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14306                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14307                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14308                   return SDValue(*VI, 0);
14309                 }
14310               }
14311             }
14312           }
14313         }
14314       }
14315 
14316       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14317       // Expose the vabsduw/h/b opportunity for down stream
14318       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14319           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14320            IID == Intrinsic::ppc_altivec_vmaxsh ||
14321            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14322         SDValue V1 = N->getOperand(1);
14323         SDValue V2 = N->getOperand(2);
14324         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14325              V1.getSimpleValueType() == MVT::v8i16 ||
14326              V1.getSimpleValueType() == MVT::v16i8) &&
14327             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14328           // (0-a, a)
14329           if (V1.getOpcode() == ISD::SUB &&
14330               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14331               V1.getOperand(1) == V2) {
14332             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14333           }
14334           // (a, 0-a)
14335           if (V2.getOpcode() == ISD::SUB &&
14336               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14337               V2.getOperand(1) == V1) {
14338             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14339           }
14340           // (x-y, y-x)
14341           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14342               V1.getOperand(0) == V2.getOperand(1) &&
14343               V1.getOperand(1) == V2.getOperand(0)) {
14344             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14345           }
14346         }
14347       }
14348     }
14349 
14350     break;
14351   case ISD::INTRINSIC_W_CHAIN:
14352     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14353     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14354     if (Subtarget.needsSwapsForVSXMemOps()) {
14355       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14356       default:
14357         break;
14358       case Intrinsic::ppc_vsx_lxvw4x:
14359       case Intrinsic::ppc_vsx_lxvd2x:
14360         return expandVSXLoadForLE(N, DCI);
14361       }
14362     }
14363     break;
14364   case ISD::INTRINSIC_VOID:
14365     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14366     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14367     if (Subtarget.needsSwapsForVSXMemOps()) {
14368       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14369       default:
14370         break;
14371       case Intrinsic::ppc_vsx_stxvw4x:
14372       case Intrinsic::ppc_vsx_stxvd2x:
14373         return expandVSXStoreForLE(N, DCI);
14374       }
14375     }
14376     break;
14377   case ISD::BSWAP:
14378     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14379     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14380         N->getOperand(0).hasOneUse() &&
14381         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14382          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14383           N->getValueType(0) == MVT::i64))) {
14384       SDValue Load = N->getOperand(0);
14385       LoadSDNode *LD = cast<LoadSDNode>(Load);
14386       // Create the byte-swapping load.
14387       SDValue Ops[] = {
14388         LD->getChain(),    // Chain
14389         LD->getBasePtr(),  // Ptr
14390         DAG.getValueType(N->getValueType(0)) // VT
14391       };
14392       SDValue BSLoad =
14393         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14394                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14395                                               MVT::i64 : MVT::i32, MVT::Other),
14396                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14397 
14398       // If this is an i16 load, insert the truncate.
14399       SDValue ResVal = BSLoad;
14400       if (N->getValueType(0) == MVT::i16)
14401         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14402 
14403       // First, combine the bswap away.  This makes the value produced by the
14404       // load dead.
14405       DCI.CombineTo(N, ResVal);
14406 
14407       // Next, combine the load away, we give it a bogus result value but a real
14408       // chain result.  The result value is dead because the bswap is dead.
14409       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14410 
14411       // Return N so it doesn't get rechecked!
14412       return SDValue(N, 0);
14413     }
14414     break;
14415   case PPCISD::VCMP:
14416     // If a VCMPo node already exists with exactly the same operands as this
14417     // node, use its result instead of this node (VCMPo computes both a CR6 and
14418     // a normal output).
14419     //
14420     if (!N->getOperand(0).hasOneUse() &&
14421         !N->getOperand(1).hasOneUse() &&
14422         !N->getOperand(2).hasOneUse()) {
14423 
14424       // Scan all of the users of the LHS, looking for VCMPo's that match.
14425       SDNode *VCMPoNode = nullptr;
14426 
14427       SDNode *LHSN = N->getOperand(0).getNode();
14428       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14429            UI != E; ++UI)
14430         if (UI->getOpcode() == PPCISD::VCMPo &&
14431             UI->getOperand(1) == N->getOperand(1) &&
14432             UI->getOperand(2) == N->getOperand(2) &&
14433             UI->getOperand(0) == N->getOperand(0)) {
14434           VCMPoNode = *UI;
14435           break;
14436         }
14437 
14438       // If there is no VCMPo node, or if the flag value has a single use, don't
14439       // transform this.
14440       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14441         break;
14442 
14443       // Look at the (necessarily single) use of the flag value.  If it has a
14444       // chain, this transformation is more complex.  Note that multiple things
14445       // could use the value result, which we should ignore.
14446       SDNode *FlagUser = nullptr;
14447       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14448            FlagUser == nullptr; ++UI) {
14449         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14450         SDNode *User = *UI;
14451         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14452           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14453             FlagUser = User;
14454             break;
14455           }
14456         }
14457       }
14458 
14459       // If the user is a MFOCRF instruction, we know this is safe.
14460       // Otherwise we give up for right now.
14461       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14462         return SDValue(VCMPoNode, 0);
14463     }
14464     break;
14465   case ISD::BRCOND: {
14466     SDValue Cond = N->getOperand(1);
14467     SDValue Target = N->getOperand(2);
14468 
14469     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14470         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14471           Intrinsic::loop_decrement) {
14472 
14473       // We now need to make the intrinsic dead (it cannot be instruction
14474       // selected).
14475       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14476       assert(Cond.getNode()->hasOneUse() &&
14477              "Counter decrement has more than one use");
14478 
14479       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14480                          N->getOperand(0), Target);
14481     }
14482   }
14483   break;
14484   case ISD::BR_CC: {
14485     // If this is a branch on an altivec predicate comparison, lower this so
14486     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14487     // lowering is done pre-legalize, because the legalizer lowers the predicate
14488     // compare down to code that is difficult to reassemble.
14489     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14490     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14491 
14492     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14493     // value. If so, pass-through the AND to get to the intrinsic.
14494     if (LHS.getOpcode() == ISD::AND &&
14495         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14496         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14497           Intrinsic::loop_decrement &&
14498         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14499         !isNullConstant(LHS.getOperand(1)))
14500       LHS = LHS.getOperand(0);
14501 
14502     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14503         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14504           Intrinsic::loop_decrement &&
14505         isa<ConstantSDNode>(RHS)) {
14506       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14507              "Counter decrement comparison is not EQ or NE");
14508 
14509       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14510       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14511                     (CC == ISD::SETNE && !Val);
14512 
14513       // We now need to make the intrinsic dead (it cannot be instruction
14514       // selected).
14515       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14516       assert(LHS.getNode()->hasOneUse() &&
14517              "Counter decrement has more than one use");
14518 
14519       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14520                          N->getOperand(0), N->getOperand(4));
14521     }
14522 
14523     int CompareOpc;
14524     bool isDot;
14525 
14526     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14527         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14528         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14529       assert(isDot && "Can't compare against a vector result!");
14530 
14531       // If this is a comparison against something other than 0/1, then we know
14532       // that the condition is never/always true.
14533       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14534       if (Val != 0 && Val != 1) {
14535         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14536           return N->getOperand(0);
14537         // Always !=, turn it into an unconditional branch.
14538         return DAG.getNode(ISD::BR, dl, MVT::Other,
14539                            N->getOperand(0), N->getOperand(4));
14540       }
14541 
14542       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14543 
14544       // Create the PPCISD altivec 'dot' comparison node.
14545       SDValue Ops[] = {
14546         LHS.getOperand(2),  // LHS of compare
14547         LHS.getOperand(3),  // RHS of compare
14548         DAG.getConstant(CompareOpc, dl, MVT::i32)
14549       };
14550       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14551       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14552 
14553       // Unpack the result based on how the target uses it.
14554       PPC::Predicate CompOpc;
14555       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14556       default:  // Can't happen, don't crash on invalid number though.
14557       case 0:   // Branch on the value of the EQ bit of CR6.
14558         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14559         break;
14560       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14561         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14562         break;
14563       case 2:   // Branch on the value of the LT bit of CR6.
14564         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14565         break;
14566       case 3:   // Branch on the inverted value of the LT bit of CR6.
14567         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14568         break;
14569       }
14570 
14571       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14572                          DAG.getConstant(CompOpc, dl, MVT::i32),
14573                          DAG.getRegister(PPC::CR6, MVT::i32),
14574                          N->getOperand(4), CompNode.getValue(1));
14575     }
14576     break;
14577   }
14578   case ISD::BUILD_VECTOR:
14579     return DAGCombineBuildVector(N, DCI);
14580   case ISD::ABS:
14581     return combineABS(N, DCI);
14582   case ISD::VSELECT:
14583     return combineVSelect(N, DCI);
14584   }
14585 
14586   return SDValue();
14587 }
14588 
14589 SDValue
14590 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14591                                  SelectionDAG &DAG,
14592                                  SmallVectorImpl<SDNode *> &Created) const {
14593   // fold (sdiv X, pow2)
14594   EVT VT = N->getValueType(0);
14595   if (VT == MVT::i64 && !Subtarget.isPPC64())
14596     return SDValue();
14597   if ((VT != MVT::i32 && VT != MVT::i64) ||
14598       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14599     return SDValue();
14600 
14601   SDLoc DL(N);
14602   SDValue N0 = N->getOperand(0);
14603 
14604   bool IsNegPow2 = (-Divisor).isPowerOf2();
14605   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14606   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14607 
14608   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14609   Created.push_back(Op.getNode());
14610 
14611   if (IsNegPow2) {
14612     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14613     Created.push_back(Op.getNode());
14614   }
14615 
14616   return Op;
14617 }
14618 
14619 //===----------------------------------------------------------------------===//
14620 // Inline Assembly Support
14621 //===----------------------------------------------------------------------===//
14622 
14623 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14624                                                       KnownBits &Known,
14625                                                       const APInt &DemandedElts,
14626                                                       const SelectionDAG &DAG,
14627                                                       unsigned Depth) const {
14628   Known.resetAll();
14629   switch (Op.getOpcode()) {
14630   default: break;
14631   case PPCISD::LBRX: {
14632     // lhbrx is known to have the top bits cleared out.
14633     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14634       Known.Zero = 0xFFFF0000;
14635     break;
14636   }
14637   case ISD::INTRINSIC_WO_CHAIN: {
14638     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14639     default: break;
14640     case Intrinsic::ppc_altivec_vcmpbfp_p:
14641     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14642     case Intrinsic::ppc_altivec_vcmpequb_p:
14643     case Intrinsic::ppc_altivec_vcmpequh_p:
14644     case Intrinsic::ppc_altivec_vcmpequw_p:
14645     case Intrinsic::ppc_altivec_vcmpequd_p:
14646     case Intrinsic::ppc_altivec_vcmpgefp_p:
14647     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14648     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14649     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14650     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14651     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14652     case Intrinsic::ppc_altivec_vcmpgtub_p:
14653     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14654     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14655     case Intrinsic::ppc_altivec_vcmpgtud_p:
14656       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14657       break;
14658     }
14659   }
14660   }
14661 }
14662 
14663 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14664   switch (Subtarget.getCPUDirective()) {
14665   default: break;
14666   case PPC::DIR_970:
14667   case PPC::DIR_PWR4:
14668   case PPC::DIR_PWR5:
14669   case PPC::DIR_PWR5X:
14670   case PPC::DIR_PWR6:
14671   case PPC::DIR_PWR6X:
14672   case PPC::DIR_PWR7:
14673   case PPC::DIR_PWR8:
14674   case PPC::DIR_PWR9:
14675   case PPC::DIR_PWR_FUTURE: {
14676     if (!ML)
14677       break;
14678 
14679     if (!DisableInnermostLoopAlign32) {
14680       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14681       // so that we can decrease cache misses and branch-prediction misses.
14682       // Actual alignment of the loop will depend on the hotness check and other
14683       // logic in alignBlocks.
14684       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14685         return Align(32);
14686     }
14687 
14688     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14689 
14690     // For small loops (between 5 and 8 instructions), align to a 32-byte
14691     // boundary so that the entire loop fits in one instruction-cache line.
14692     uint64_t LoopSize = 0;
14693     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14694       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14695         LoopSize += TII->getInstSizeInBytes(*J);
14696         if (LoopSize > 32)
14697           break;
14698       }
14699 
14700     if (LoopSize > 16 && LoopSize <= 32)
14701       return Align(32);
14702 
14703     break;
14704   }
14705   }
14706 
14707   return TargetLowering::getPrefLoopAlignment(ML);
14708 }
14709 
14710 /// getConstraintType - Given a constraint, return the type of
14711 /// constraint it is for this target.
14712 PPCTargetLowering::ConstraintType
14713 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14714   if (Constraint.size() == 1) {
14715     switch (Constraint[0]) {
14716     default: break;
14717     case 'b':
14718     case 'r':
14719     case 'f':
14720     case 'd':
14721     case 'v':
14722     case 'y':
14723       return C_RegisterClass;
14724     case 'Z':
14725       // FIXME: While Z does indicate a memory constraint, it specifically
14726       // indicates an r+r address (used in conjunction with the 'y' modifier
14727       // in the replacement string). Currently, we're forcing the base
14728       // register to be r0 in the asm printer (which is interpreted as zero)
14729       // and forming the complete address in the second register. This is
14730       // suboptimal.
14731       return C_Memory;
14732     }
14733   } else if (Constraint == "wc") { // individual CR bits.
14734     return C_RegisterClass;
14735   } else if (Constraint == "wa" || Constraint == "wd" ||
14736              Constraint == "wf" || Constraint == "ws" ||
14737              Constraint == "wi" || Constraint == "ww") {
14738     return C_RegisterClass; // VSX registers.
14739   }
14740   return TargetLowering::getConstraintType(Constraint);
14741 }
14742 
14743 /// Examine constraint type and operand type and determine a weight value.
14744 /// This object must already have been set up with the operand type
14745 /// and the current alternative constraint selected.
14746 TargetLowering::ConstraintWeight
14747 PPCTargetLowering::getSingleConstraintMatchWeight(
14748     AsmOperandInfo &info, const char *constraint) const {
14749   ConstraintWeight weight = CW_Invalid;
14750   Value *CallOperandVal = info.CallOperandVal;
14751     // If we don't have a value, we can't do a match,
14752     // but allow it at the lowest weight.
14753   if (!CallOperandVal)
14754     return CW_Default;
14755   Type *type = CallOperandVal->getType();
14756 
14757   // Look at the constraint type.
14758   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14759     return CW_Register; // an individual CR bit.
14760   else if ((StringRef(constraint) == "wa" ||
14761             StringRef(constraint) == "wd" ||
14762             StringRef(constraint) == "wf") &&
14763            type->isVectorTy())
14764     return CW_Register;
14765   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14766     return CW_Register; // just hold 64-bit integers data.
14767   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14768     return CW_Register;
14769   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14770     return CW_Register;
14771 
14772   switch (*constraint) {
14773   default:
14774     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14775     break;
14776   case 'b':
14777     if (type->isIntegerTy())
14778       weight = CW_Register;
14779     break;
14780   case 'f':
14781     if (type->isFloatTy())
14782       weight = CW_Register;
14783     break;
14784   case 'd':
14785     if (type->isDoubleTy())
14786       weight = CW_Register;
14787     break;
14788   case 'v':
14789     if (type->isVectorTy())
14790       weight = CW_Register;
14791     break;
14792   case 'y':
14793     weight = CW_Register;
14794     break;
14795   case 'Z':
14796     weight = CW_Memory;
14797     break;
14798   }
14799   return weight;
14800 }
14801 
14802 std::pair<unsigned, const TargetRegisterClass *>
14803 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14804                                                 StringRef Constraint,
14805                                                 MVT VT) const {
14806   if (Constraint.size() == 1) {
14807     // GCC RS6000 Constraint Letters
14808     switch (Constraint[0]) {
14809     case 'b':   // R1-R31
14810       if (VT == MVT::i64 && Subtarget.isPPC64())
14811         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14812       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14813     case 'r':   // R0-R31
14814       if (VT == MVT::i64 && Subtarget.isPPC64())
14815         return std::make_pair(0U, &PPC::G8RCRegClass);
14816       return std::make_pair(0U, &PPC::GPRCRegClass);
14817     // 'd' and 'f' constraints are both defined to be "the floating point
14818     // registers", where one is for 32-bit and the other for 64-bit. We don't
14819     // really care overly much here so just give them all the same reg classes.
14820     case 'd':
14821     case 'f':
14822       if (Subtarget.hasSPE()) {
14823         if (VT == MVT::f32 || VT == MVT::i32)
14824           return std::make_pair(0U, &PPC::GPRCRegClass);
14825         if (VT == MVT::f64 || VT == MVT::i64)
14826           return std::make_pair(0U, &PPC::SPERCRegClass);
14827       } else {
14828         if (VT == MVT::f32 || VT == MVT::i32)
14829           return std::make_pair(0U, &PPC::F4RCRegClass);
14830         if (VT == MVT::f64 || VT == MVT::i64)
14831           return std::make_pair(0U, &PPC::F8RCRegClass);
14832         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14833           return std::make_pair(0U, &PPC::QFRCRegClass);
14834         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14835           return std::make_pair(0U, &PPC::QSRCRegClass);
14836       }
14837       break;
14838     case 'v':
14839       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14840         return std::make_pair(0U, &PPC::QFRCRegClass);
14841       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14842         return std::make_pair(0U, &PPC::QSRCRegClass);
14843       if (Subtarget.hasAltivec())
14844         return std::make_pair(0U, &PPC::VRRCRegClass);
14845       break;
14846     case 'y':   // crrc
14847       return std::make_pair(0U, &PPC::CRRCRegClass);
14848     }
14849   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14850     // An individual CR bit.
14851     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14852   } else if ((Constraint == "wa" || Constraint == "wd" ||
14853              Constraint == "wf" || Constraint == "wi") &&
14854              Subtarget.hasVSX()) {
14855     return std::make_pair(0U, &PPC::VSRCRegClass);
14856   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14857     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14858       return std::make_pair(0U, &PPC::VSSRCRegClass);
14859     else
14860       return std::make_pair(0U, &PPC::VSFRCRegClass);
14861   }
14862 
14863   // If we name a VSX register, we can't defer to the base class because it
14864   // will not recognize the correct register (their names will be VSL{0-31}
14865   // and V{0-31} so they won't match). So we match them here.
14866   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14867     int VSNum = atoi(Constraint.data() + 3);
14868     assert(VSNum >= 0 && VSNum <= 63 &&
14869            "Attempted to access a vsr out of range");
14870     if (VSNum < 32)
14871       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14872     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14873   }
14874   std::pair<unsigned, const TargetRegisterClass *> R =
14875       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14876 
14877   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14878   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14879   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14880   // register.
14881   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14882   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14883   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14884       PPC::GPRCRegClass.contains(R.first))
14885     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14886                             PPC::sub_32, &PPC::G8RCRegClass),
14887                           &PPC::G8RCRegClass);
14888 
14889   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14890   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14891     R.first = PPC::CR0;
14892     R.second = &PPC::CRRCRegClass;
14893   }
14894 
14895   return R;
14896 }
14897 
14898 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14899 /// vector.  If it is invalid, don't add anything to Ops.
14900 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14901                                                      std::string &Constraint,
14902                                                      std::vector<SDValue>&Ops,
14903                                                      SelectionDAG &DAG) const {
14904   SDValue Result;
14905 
14906   // Only support length 1 constraints.
14907   if (Constraint.length() > 1) return;
14908 
14909   char Letter = Constraint[0];
14910   switch (Letter) {
14911   default: break;
14912   case 'I':
14913   case 'J':
14914   case 'K':
14915   case 'L':
14916   case 'M':
14917   case 'N':
14918   case 'O':
14919   case 'P': {
14920     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14921     if (!CST) return; // Must be an immediate to match.
14922     SDLoc dl(Op);
14923     int64_t Value = CST->getSExtValue();
14924     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14925                          // numbers are printed as such.
14926     switch (Letter) {
14927     default: llvm_unreachable("Unknown constraint letter!");
14928     case 'I':  // "I" is a signed 16-bit constant.
14929       if (isInt<16>(Value))
14930         Result = DAG.getTargetConstant(Value, dl, TCVT);
14931       break;
14932     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14933       if (isShiftedUInt<16, 16>(Value))
14934         Result = DAG.getTargetConstant(Value, dl, TCVT);
14935       break;
14936     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14937       if (isShiftedInt<16, 16>(Value))
14938         Result = DAG.getTargetConstant(Value, dl, TCVT);
14939       break;
14940     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14941       if (isUInt<16>(Value))
14942         Result = DAG.getTargetConstant(Value, dl, TCVT);
14943       break;
14944     case 'M':  // "M" is a constant that is greater than 31.
14945       if (Value > 31)
14946         Result = DAG.getTargetConstant(Value, dl, TCVT);
14947       break;
14948     case 'N':  // "N" is a positive constant that is an exact power of two.
14949       if (Value > 0 && isPowerOf2_64(Value))
14950         Result = DAG.getTargetConstant(Value, dl, TCVT);
14951       break;
14952     case 'O':  // "O" is the constant zero.
14953       if (Value == 0)
14954         Result = DAG.getTargetConstant(Value, dl, TCVT);
14955       break;
14956     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14957       if (isInt<16>(-Value))
14958         Result = DAG.getTargetConstant(Value, dl, TCVT);
14959       break;
14960     }
14961     break;
14962   }
14963   }
14964 
14965   if (Result.getNode()) {
14966     Ops.push_back(Result);
14967     return;
14968   }
14969 
14970   // Handle standard constraint letters.
14971   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14972 }
14973 
14974 // isLegalAddressingMode - Return true if the addressing mode represented
14975 // by AM is legal for this target, for a load/store of the specified type.
14976 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14977                                               const AddrMode &AM, Type *Ty,
14978                                               unsigned AS, Instruction *I) const {
14979   // PPC does not allow r+i addressing modes for vectors!
14980   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14981     return false;
14982 
14983   // PPC allows a sign-extended 16-bit immediate field.
14984   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14985     return false;
14986 
14987   // No global is ever allowed as a base.
14988   if (AM.BaseGV)
14989     return false;
14990 
14991   // PPC only support r+r,
14992   switch (AM.Scale) {
14993   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14994     break;
14995   case 1:
14996     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14997       return false;
14998     // Otherwise we have r+r or r+i.
14999     break;
15000   case 2:
15001     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15002       return false;
15003     // Allow 2*r as r+r.
15004     break;
15005   default:
15006     // No other scales are supported.
15007     return false;
15008   }
15009 
15010   return true;
15011 }
15012 
15013 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15014                                            SelectionDAG &DAG) const {
15015   MachineFunction &MF = DAG.getMachineFunction();
15016   MachineFrameInfo &MFI = MF.getFrameInfo();
15017   MFI.setReturnAddressIsTaken(true);
15018 
15019   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15020     return SDValue();
15021 
15022   SDLoc dl(Op);
15023   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15024 
15025   // Make sure the function does not optimize away the store of the RA to
15026   // the stack.
15027   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15028   FuncInfo->setLRStoreRequired();
15029   bool isPPC64 = Subtarget.isPPC64();
15030   auto PtrVT = getPointerTy(MF.getDataLayout());
15031 
15032   if (Depth > 0) {
15033     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15034     SDValue Offset =
15035         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15036                         isPPC64 ? MVT::i64 : MVT::i32);
15037     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15038                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15039                        MachinePointerInfo());
15040   }
15041 
15042   // Just load the return address off the stack.
15043   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15044   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15045                      MachinePointerInfo());
15046 }
15047 
15048 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15049                                           SelectionDAG &DAG) const {
15050   SDLoc dl(Op);
15051   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15052 
15053   MachineFunction &MF = DAG.getMachineFunction();
15054   MachineFrameInfo &MFI = MF.getFrameInfo();
15055   MFI.setFrameAddressIsTaken(true);
15056 
15057   EVT PtrVT = getPointerTy(MF.getDataLayout());
15058   bool isPPC64 = PtrVT == MVT::i64;
15059 
15060   // Naked functions never have a frame pointer, and so we use r1. For all
15061   // other functions, this decision must be delayed until during PEI.
15062   unsigned FrameReg;
15063   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15064     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15065   else
15066     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15067 
15068   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15069                                          PtrVT);
15070   while (Depth--)
15071     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15072                             FrameAddr, MachinePointerInfo());
15073   return FrameAddr;
15074 }
15075 
15076 // FIXME? Maybe this could be a TableGen attribute on some registers and
15077 // this table could be generated automatically from RegInfo.
15078 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15079                                               const MachineFunction &MF) const {
15080   bool isPPC64 = Subtarget.isPPC64();
15081 
15082   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15083   if (!is64Bit && VT != LLT::scalar(32))
15084     report_fatal_error("Invalid register global variable type");
15085 
15086   Register Reg = StringSwitch<Register>(RegName)
15087                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15088                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15089                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15090                      .Default(Register());
15091 
15092   if (Reg)
15093     return Reg;
15094   report_fatal_error("Invalid register name global variable");
15095 }
15096 
15097 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15098   // 32-bit SVR4 ABI access everything as got-indirect.
15099   if (Subtarget.is32BitELFABI())
15100     return true;
15101 
15102   // AIX accesses everything indirectly through the TOC, which is similar to
15103   // the GOT.
15104   if (Subtarget.isAIXABI())
15105     return true;
15106 
15107   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15108   // If it is small or large code model, module locals are accessed
15109   // indirectly by loading their address from .toc/.got.
15110   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15111     return true;
15112 
15113   // JumpTable and BlockAddress are accessed as got-indirect.
15114   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15115     return true;
15116 
15117   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15118     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15119 
15120   return false;
15121 }
15122 
15123 bool
15124 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15125   // The PowerPC target isn't yet aware of offsets.
15126   return false;
15127 }
15128 
15129 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15130                                            const CallInst &I,
15131                                            MachineFunction &MF,
15132                                            unsigned Intrinsic) const {
15133   switch (Intrinsic) {
15134   case Intrinsic::ppc_qpx_qvlfd:
15135   case Intrinsic::ppc_qpx_qvlfs:
15136   case Intrinsic::ppc_qpx_qvlfcd:
15137   case Intrinsic::ppc_qpx_qvlfcs:
15138   case Intrinsic::ppc_qpx_qvlfiwa:
15139   case Intrinsic::ppc_qpx_qvlfiwz:
15140   case Intrinsic::ppc_altivec_lvx:
15141   case Intrinsic::ppc_altivec_lvxl:
15142   case Intrinsic::ppc_altivec_lvebx:
15143   case Intrinsic::ppc_altivec_lvehx:
15144   case Intrinsic::ppc_altivec_lvewx:
15145   case Intrinsic::ppc_vsx_lxvd2x:
15146   case Intrinsic::ppc_vsx_lxvw4x: {
15147     EVT VT;
15148     switch (Intrinsic) {
15149     case Intrinsic::ppc_altivec_lvebx:
15150       VT = MVT::i8;
15151       break;
15152     case Intrinsic::ppc_altivec_lvehx:
15153       VT = MVT::i16;
15154       break;
15155     case Intrinsic::ppc_altivec_lvewx:
15156       VT = MVT::i32;
15157       break;
15158     case Intrinsic::ppc_vsx_lxvd2x:
15159       VT = MVT::v2f64;
15160       break;
15161     case Intrinsic::ppc_qpx_qvlfd:
15162       VT = MVT::v4f64;
15163       break;
15164     case Intrinsic::ppc_qpx_qvlfs:
15165       VT = MVT::v4f32;
15166       break;
15167     case Intrinsic::ppc_qpx_qvlfcd:
15168       VT = MVT::v2f64;
15169       break;
15170     case Intrinsic::ppc_qpx_qvlfcs:
15171       VT = MVT::v2f32;
15172       break;
15173     default:
15174       VT = MVT::v4i32;
15175       break;
15176     }
15177 
15178     Info.opc = ISD::INTRINSIC_W_CHAIN;
15179     Info.memVT = VT;
15180     Info.ptrVal = I.getArgOperand(0);
15181     Info.offset = -VT.getStoreSize()+1;
15182     Info.size = 2*VT.getStoreSize()-1;
15183     Info.align = Align(1);
15184     Info.flags = MachineMemOperand::MOLoad;
15185     return true;
15186   }
15187   case Intrinsic::ppc_qpx_qvlfda:
15188   case Intrinsic::ppc_qpx_qvlfsa:
15189   case Intrinsic::ppc_qpx_qvlfcda:
15190   case Intrinsic::ppc_qpx_qvlfcsa:
15191   case Intrinsic::ppc_qpx_qvlfiwaa:
15192   case Intrinsic::ppc_qpx_qvlfiwza: {
15193     EVT VT;
15194     switch (Intrinsic) {
15195     case Intrinsic::ppc_qpx_qvlfda:
15196       VT = MVT::v4f64;
15197       break;
15198     case Intrinsic::ppc_qpx_qvlfsa:
15199       VT = MVT::v4f32;
15200       break;
15201     case Intrinsic::ppc_qpx_qvlfcda:
15202       VT = MVT::v2f64;
15203       break;
15204     case Intrinsic::ppc_qpx_qvlfcsa:
15205       VT = MVT::v2f32;
15206       break;
15207     default:
15208       VT = MVT::v4i32;
15209       break;
15210     }
15211 
15212     Info.opc = ISD::INTRINSIC_W_CHAIN;
15213     Info.memVT = VT;
15214     Info.ptrVal = I.getArgOperand(0);
15215     Info.offset = 0;
15216     Info.size = VT.getStoreSize();
15217     Info.align = Align(1);
15218     Info.flags = MachineMemOperand::MOLoad;
15219     return true;
15220   }
15221   case Intrinsic::ppc_qpx_qvstfd:
15222   case Intrinsic::ppc_qpx_qvstfs:
15223   case Intrinsic::ppc_qpx_qvstfcd:
15224   case Intrinsic::ppc_qpx_qvstfcs:
15225   case Intrinsic::ppc_qpx_qvstfiw:
15226   case Intrinsic::ppc_altivec_stvx:
15227   case Intrinsic::ppc_altivec_stvxl:
15228   case Intrinsic::ppc_altivec_stvebx:
15229   case Intrinsic::ppc_altivec_stvehx:
15230   case Intrinsic::ppc_altivec_stvewx:
15231   case Intrinsic::ppc_vsx_stxvd2x:
15232   case Intrinsic::ppc_vsx_stxvw4x: {
15233     EVT VT;
15234     switch (Intrinsic) {
15235     case Intrinsic::ppc_altivec_stvebx:
15236       VT = MVT::i8;
15237       break;
15238     case Intrinsic::ppc_altivec_stvehx:
15239       VT = MVT::i16;
15240       break;
15241     case Intrinsic::ppc_altivec_stvewx:
15242       VT = MVT::i32;
15243       break;
15244     case Intrinsic::ppc_vsx_stxvd2x:
15245       VT = MVT::v2f64;
15246       break;
15247     case Intrinsic::ppc_qpx_qvstfd:
15248       VT = MVT::v4f64;
15249       break;
15250     case Intrinsic::ppc_qpx_qvstfs:
15251       VT = MVT::v4f32;
15252       break;
15253     case Intrinsic::ppc_qpx_qvstfcd:
15254       VT = MVT::v2f64;
15255       break;
15256     case Intrinsic::ppc_qpx_qvstfcs:
15257       VT = MVT::v2f32;
15258       break;
15259     default:
15260       VT = MVT::v4i32;
15261       break;
15262     }
15263 
15264     Info.opc = ISD::INTRINSIC_VOID;
15265     Info.memVT = VT;
15266     Info.ptrVal = I.getArgOperand(1);
15267     Info.offset = -VT.getStoreSize()+1;
15268     Info.size = 2*VT.getStoreSize()-1;
15269     Info.align = Align(1);
15270     Info.flags = MachineMemOperand::MOStore;
15271     return true;
15272   }
15273   case Intrinsic::ppc_qpx_qvstfda:
15274   case Intrinsic::ppc_qpx_qvstfsa:
15275   case Intrinsic::ppc_qpx_qvstfcda:
15276   case Intrinsic::ppc_qpx_qvstfcsa:
15277   case Intrinsic::ppc_qpx_qvstfiwa: {
15278     EVT VT;
15279     switch (Intrinsic) {
15280     case Intrinsic::ppc_qpx_qvstfda:
15281       VT = MVT::v4f64;
15282       break;
15283     case Intrinsic::ppc_qpx_qvstfsa:
15284       VT = MVT::v4f32;
15285       break;
15286     case Intrinsic::ppc_qpx_qvstfcda:
15287       VT = MVT::v2f64;
15288       break;
15289     case Intrinsic::ppc_qpx_qvstfcsa:
15290       VT = MVT::v2f32;
15291       break;
15292     default:
15293       VT = MVT::v4i32;
15294       break;
15295     }
15296 
15297     Info.opc = ISD::INTRINSIC_VOID;
15298     Info.memVT = VT;
15299     Info.ptrVal = I.getArgOperand(1);
15300     Info.offset = 0;
15301     Info.size = VT.getStoreSize();
15302     Info.align = Align(1);
15303     Info.flags = MachineMemOperand::MOStore;
15304     return true;
15305   }
15306   default:
15307     break;
15308   }
15309 
15310   return false;
15311 }
15312 
15313 /// It returns EVT::Other if the type should be determined using generic
15314 /// target-independent logic.
15315 EVT PPCTargetLowering::getOptimalMemOpType(
15316     const MemOp &Op, const AttributeList &FuncAttributes) const {
15317   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15318     // When expanding a memset, require at least two QPX instructions to cover
15319     // the cost of loading the value to be stored from the constant pool.
15320     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15321         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15322         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15323       return MVT::v4f64;
15324     }
15325 
15326     // We should use Altivec/VSX loads and stores when available. For unaligned
15327     // addresses, unaligned VSX loads are only fast starting with the P8.
15328     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15329         (Op.isAligned(Align(16)) ||
15330          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15331       return MVT::v4i32;
15332   }
15333 
15334   if (Subtarget.isPPC64()) {
15335     return MVT::i64;
15336   }
15337 
15338   return MVT::i32;
15339 }
15340 
15341 /// Returns true if it is beneficial to convert a load of a constant
15342 /// to just the constant itself.
15343 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15344                                                           Type *Ty) const {
15345   assert(Ty->isIntegerTy());
15346 
15347   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15348   return !(BitSize == 0 || BitSize > 64);
15349 }
15350 
15351 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15352   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15353     return false;
15354   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15355   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15356   return NumBits1 == 64 && NumBits2 == 32;
15357 }
15358 
15359 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15360   if (!VT1.isInteger() || !VT2.isInteger())
15361     return false;
15362   unsigned NumBits1 = VT1.getSizeInBits();
15363   unsigned NumBits2 = VT2.getSizeInBits();
15364   return NumBits1 == 64 && NumBits2 == 32;
15365 }
15366 
15367 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15368   // Generally speaking, zexts are not free, but they are free when they can be
15369   // folded with other operations.
15370   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15371     EVT MemVT = LD->getMemoryVT();
15372     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15373          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15374         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15375          LD->getExtensionType() == ISD::ZEXTLOAD))
15376       return true;
15377   }
15378 
15379   // FIXME: Add other cases...
15380   //  - 32-bit shifts with a zext to i64
15381   //  - zext after ctlz, bswap, etc.
15382   //  - zext after and by a constant mask
15383 
15384   return TargetLowering::isZExtFree(Val, VT2);
15385 }
15386 
15387 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15388   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15389          "invalid fpext types");
15390   // Extending to float128 is not free.
15391   if (DestVT == MVT::f128)
15392     return false;
15393   return true;
15394 }
15395 
15396 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15397   return isInt<16>(Imm) || isUInt<16>(Imm);
15398 }
15399 
15400 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15401   return isInt<16>(Imm) || isUInt<16>(Imm);
15402 }
15403 
15404 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15405                                                        unsigned,
15406                                                        unsigned,
15407                                                        MachineMemOperand::Flags,
15408                                                        bool *Fast) const {
15409   if (DisablePPCUnaligned)
15410     return false;
15411 
15412   // PowerPC supports unaligned memory access for simple non-vector types.
15413   // Although accessing unaligned addresses is not as efficient as accessing
15414   // aligned addresses, it is generally more efficient than manual expansion,
15415   // and generally only traps for software emulation when crossing page
15416   // boundaries.
15417 
15418   if (!VT.isSimple())
15419     return false;
15420 
15421   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15422     return false;
15423 
15424   if (VT.getSimpleVT().isVector()) {
15425     if (Subtarget.hasVSX()) {
15426       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15427           VT != MVT::v4f32 && VT != MVT::v4i32)
15428         return false;
15429     } else {
15430       return false;
15431     }
15432   }
15433 
15434   if (VT == MVT::ppcf128)
15435     return false;
15436 
15437   if (Fast)
15438     *Fast = true;
15439 
15440   return true;
15441 }
15442 
15443 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15444                                                    EVT VT) const {
15445   return isFMAFasterThanFMulAndFAdd(
15446       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15447 }
15448 
15449 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15450                                                    Type *Ty) const {
15451   switch (Ty->getScalarType()->getTypeID()) {
15452   case Type::FloatTyID:
15453   case Type::DoubleTyID:
15454     return true;
15455   case Type::FP128TyID:
15456     return EnableQuadPrecision && Subtarget.hasP9Vector();
15457   default:
15458     return false;
15459   }
15460 }
15461 
15462 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15463 // FIXME: add more patterns which are profitable to hoist.
15464 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15465   if (I->getOpcode() != Instruction::FMul)
15466     return true;
15467 
15468   if (!I->hasOneUse())
15469     return true;
15470 
15471   Instruction *User = I->user_back();
15472   assert(User && "A single use instruction with no uses.");
15473 
15474   if (User->getOpcode() != Instruction::FSub &&
15475       User->getOpcode() != Instruction::FAdd)
15476     return true;
15477 
15478   const TargetOptions &Options = getTargetMachine().Options;
15479   const Function *F = I->getFunction();
15480   const DataLayout &DL = F->getParent()->getDataLayout();
15481   Type *Ty = User->getOperand(0)->getType();
15482 
15483   return !(
15484       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15485       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15486       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15487 }
15488 
15489 const MCPhysReg *
15490 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15491   // LR is a callee-save register, but we must treat it as clobbered by any call
15492   // site. Hence we include LR in the scratch registers, which are in turn added
15493   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15494   // to CTR, which is used by any indirect call.
15495   static const MCPhysReg ScratchRegs[] = {
15496     PPC::X12, PPC::LR8, PPC::CTR8, 0
15497   };
15498 
15499   return ScratchRegs;
15500 }
15501 
15502 unsigned PPCTargetLowering::getExceptionPointerRegister(
15503     const Constant *PersonalityFn) const {
15504   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15505 }
15506 
15507 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15508     const Constant *PersonalityFn) const {
15509   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15510 }
15511 
15512 bool
15513 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15514                      EVT VT , unsigned DefinedValues) const {
15515   if (VT == MVT::v2i64)
15516     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15517 
15518   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15519     return true;
15520 
15521   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15522 }
15523 
15524 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15525   if (DisableILPPref || Subtarget.enableMachineScheduler())
15526     return TargetLowering::getSchedulingPreference(N);
15527 
15528   return Sched::ILP;
15529 }
15530 
15531 // Create a fast isel object.
15532 FastISel *
15533 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15534                                   const TargetLibraryInfo *LibInfo) const {
15535   return PPC::createFastISel(FuncInfo, LibInfo);
15536 }
15537 
15538 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15539   if (!Subtarget.isPPC64()) return;
15540 
15541   // Update IsSplitCSR in PPCFunctionInfo
15542   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15543   PFI->setIsSplitCSR(true);
15544 }
15545 
15546 void PPCTargetLowering::insertCopiesSplitCSR(
15547   MachineBasicBlock *Entry,
15548   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15549   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15550   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15551   if (!IStart)
15552     return;
15553 
15554   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15555   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15556   MachineBasicBlock::iterator MBBI = Entry->begin();
15557   for (const MCPhysReg *I = IStart; *I; ++I) {
15558     const TargetRegisterClass *RC = nullptr;
15559     if (PPC::G8RCRegClass.contains(*I))
15560       RC = &PPC::G8RCRegClass;
15561     else if (PPC::F8RCRegClass.contains(*I))
15562       RC = &PPC::F8RCRegClass;
15563     else if (PPC::CRRCRegClass.contains(*I))
15564       RC = &PPC::CRRCRegClass;
15565     else if (PPC::VRRCRegClass.contains(*I))
15566       RC = &PPC::VRRCRegClass;
15567     else
15568       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15569 
15570     Register NewVR = MRI->createVirtualRegister(RC);
15571     // Create copy from CSR to a virtual register.
15572     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15573     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15574     // nounwind. If we want to generalize this later, we may need to emit
15575     // CFI pseudo-instructions.
15576     assert(Entry->getParent()->getFunction().hasFnAttribute(
15577              Attribute::NoUnwind) &&
15578            "Function should be nounwind in insertCopiesSplitCSR!");
15579     Entry->addLiveIn(*I);
15580     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15581       .addReg(*I);
15582 
15583     // Insert the copy-back instructions right before the terminator.
15584     for (auto *Exit : Exits)
15585       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15586               TII->get(TargetOpcode::COPY), *I)
15587         .addReg(NewVR);
15588   }
15589 }
15590 
15591 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15592 bool PPCTargetLowering::useLoadStackGuardNode() const {
15593   if (!Subtarget.isTargetLinux())
15594     return TargetLowering::useLoadStackGuardNode();
15595   return true;
15596 }
15597 
15598 // Override to disable global variable loading on Linux.
15599 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15600   if (!Subtarget.isTargetLinux())
15601     return TargetLowering::insertSSPDeclarations(M);
15602 }
15603 
15604 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15605                                      bool ForCodeSize) const {
15606   if (!VT.isSimple() || !Subtarget.hasVSX())
15607     return false;
15608 
15609   switch(VT.getSimpleVT().SimpleTy) {
15610   default:
15611     // For FP types that are currently not supported by PPC backend, return
15612     // false. Examples: f16, f80.
15613     return false;
15614   case MVT::f32:
15615   case MVT::f64:
15616   case MVT::ppcf128:
15617     return Imm.isPosZero();
15618   }
15619 }
15620 
15621 // For vector shift operation op, fold
15622 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15623 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15624                                   SelectionDAG &DAG) {
15625   SDValue N0 = N->getOperand(0);
15626   SDValue N1 = N->getOperand(1);
15627   EVT VT = N0.getValueType();
15628   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15629   unsigned Opcode = N->getOpcode();
15630   unsigned TargetOpcode;
15631 
15632   switch (Opcode) {
15633   default:
15634     llvm_unreachable("Unexpected shift operation");
15635   case ISD::SHL:
15636     TargetOpcode = PPCISD::SHL;
15637     break;
15638   case ISD::SRL:
15639     TargetOpcode = PPCISD::SRL;
15640     break;
15641   case ISD::SRA:
15642     TargetOpcode = PPCISD::SRA;
15643     break;
15644   }
15645 
15646   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15647       N1->getOpcode() == ISD::AND)
15648     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15649       if (Mask->getZExtValue() == OpSizeInBits - 1)
15650         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15651 
15652   return SDValue();
15653 }
15654 
15655 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15656   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15657     return Value;
15658 
15659   SDValue N0 = N->getOperand(0);
15660   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15661   if (!Subtarget.isISA3_0() ||
15662       N0.getOpcode() != ISD::SIGN_EXTEND ||
15663       N0.getOperand(0).getValueType() != MVT::i32 ||
15664       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15665     return SDValue();
15666 
15667   // We can't save an operation here if the value is already extended, and
15668   // the existing shift is easier to combine.
15669   SDValue ExtsSrc = N0.getOperand(0);
15670   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15671       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15672     return SDValue();
15673 
15674   SDLoc DL(N0);
15675   SDValue ShiftBy = SDValue(CN1, 0);
15676   // We want the shift amount to be i32 on the extswli, but the shift could
15677   // have an i64.
15678   if (ShiftBy.getValueType() == MVT::i64)
15679     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15680 
15681   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15682                          ShiftBy);
15683 }
15684 
15685 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15686   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15687     return Value;
15688 
15689   return SDValue();
15690 }
15691 
15692 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15693   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15694     return Value;
15695 
15696   return SDValue();
15697 }
15698 
15699 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15700 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15701 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15702 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15703 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15704                                  const PPCSubtarget &Subtarget) {
15705   if (!Subtarget.isPPC64())
15706     return SDValue();
15707 
15708   SDValue LHS = N->getOperand(0);
15709   SDValue RHS = N->getOperand(1);
15710 
15711   auto isZextOfCompareWithConstant = [](SDValue Op) {
15712     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15713         Op.getValueType() != MVT::i64)
15714       return false;
15715 
15716     SDValue Cmp = Op.getOperand(0);
15717     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15718         Cmp.getOperand(0).getValueType() != MVT::i64)
15719       return false;
15720 
15721     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15722       int64_t NegConstant = 0 - Constant->getSExtValue();
15723       // Due to the limitations of the addi instruction,
15724       // -C is required to be [-32768, 32767].
15725       return isInt<16>(NegConstant);
15726     }
15727 
15728     return false;
15729   };
15730 
15731   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15732   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15733 
15734   // If there is a pattern, canonicalize a zext operand to the RHS.
15735   if (LHSHasPattern && !RHSHasPattern)
15736     std::swap(LHS, RHS);
15737   else if (!LHSHasPattern && !RHSHasPattern)
15738     return SDValue();
15739 
15740   SDLoc DL(N);
15741   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15742   SDValue Cmp = RHS.getOperand(0);
15743   SDValue Z = Cmp.getOperand(0);
15744   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15745 
15746   assert(Constant && "Constant Should not be a null pointer.");
15747   int64_t NegConstant = 0 - Constant->getSExtValue();
15748 
15749   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15750   default: break;
15751   case ISD::SETNE: {
15752     //                                 when C == 0
15753     //                             --> addze X, (addic Z, -1).carry
15754     //                            /
15755     // add X, (zext(setne Z, C))--
15756     //                            \    when -32768 <= -C <= 32767 && C != 0
15757     //                             --> addze X, (addic (addi Z, -C), -1).carry
15758     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15759                               DAG.getConstant(NegConstant, DL, MVT::i64));
15760     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15761     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15762                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15763     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15764                        SDValue(Addc.getNode(), 1));
15765     }
15766   case ISD::SETEQ: {
15767     //                                 when C == 0
15768     //                             --> addze X, (subfic Z, 0).carry
15769     //                            /
15770     // add X, (zext(sete  Z, C))--
15771     //                            \    when -32768 <= -C <= 32767 && C != 0
15772     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15773     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15774                               DAG.getConstant(NegConstant, DL, MVT::i64));
15775     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15776     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15777                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15778     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15779                        SDValue(Subc.getNode(), 1));
15780     }
15781   }
15782 
15783   return SDValue();
15784 }
15785 
15786 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15787   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15788     return Value;
15789 
15790   return SDValue();
15791 }
15792 
15793 // Detect TRUNCATE operations on bitcasts of float128 values.
15794 // What we are looking for here is the situtation where we extract a subset
15795 // of bits from a 128 bit float.
15796 // This can be of two forms:
15797 // 1) BITCAST of f128 feeding TRUNCATE
15798 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15799 // The reason this is required is because we do not have a legal i128 type
15800 // and so we want to prevent having to store the f128 and then reload part
15801 // of it.
15802 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15803                                            DAGCombinerInfo &DCI) const {
15804   // If we are using CRBits then try that first.
15805   if (Subtarget.useCRBits()) {
15806     // Check if CRBits did anything and return that if it did.
15807     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15808       return CRTruncValue;
15809   }
15810 
15811   SDLoc dl(N);
15812   SDValue Op0 = N->getOperand(0);
15813 
15814   // Looking for a truncate of i128 to i64.
15815   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15816     return SDValue();
15817 
15818   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15819 
15820   // SRL feeding TRUNCATE.
15821   if (Op0.getOpcode() == ISD::SRL) {
15822     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15823     // The right shift has to be by 64 bits.
15824     if (!ConstNode || ConstNode->getZExtValue() != 64)
15825       return SDValue();
15826 
15827     // Switch the element number to extract.
15828     EltToExtract = EltToExtract ? 0 : 1;
15829     // Update Op0 past the SRL.
15830     Op0 = Op0.getOperand(0);
15831   }
15832 
15833   // BITCAST feeding a TRUNCATE possibly via SRL.
15834   if (Op0.getOpcode() == ISD::BITCAST &&
15835       Op0.getValueType() == MVT::i128 &&
15836       Op0.getOperand(0).getValueType() == MVT::f128) {
15837     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15838     return DCI.DAG.getNode(
15839         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15840         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15841   }
15842   return SDValue();
15843 }
15844 
15845 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15846   SelectionDAG &DAG = DCI.DAG;
15847 
15848   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15849   if (!ConstOpOrElement)
15850     return SDValue();
15851 
15852   // An imul is usually smaller than the alternative sequence for legal type.
15853   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15854       isOperationLegal(ISD::MUL, N->getValueType(0)))
15855     return SDValue();
15856 
15857   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15858     switch (this->Subtarget.getCPUDirective()) {
15859     default:
15860       // TODO: enhance the condition for subtarget before pwr8
15861       return false;
15862     case PPC::DIR_PWR8:
15863       //  type        mul     add    shl
15864       // scalar        4       1      1
15865       // vector        7       2      2
15866       return true;
15867     case PPC::DIR_PWR9:
15868     case PPC::DIR_PWR_FUTURE:
15869       //  type        mul     add    shl
15870       // scalar        5       2      2
15871       // vector        7       2      2
15872 
15873       // The cycle RATIO of related operations are showed as a table above.
15874       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15875       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15876       // are 4, it is always profitable; but for 3 instrs patterns
15877       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15878       // So we should only do it for vector type.
15879       return IsAddOne && IsNeg ? VT.isVector() : true;
15880     }
15881   };
15882 
15883   EVT VT = N->getValueType(0);
15884   SDLoc DL(N);
15885 
15886   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15887   bool IsNeg = MulAmt.isNegative();
15888   APInt MulAmtAbs = MulAmt.abs();
15889 
15890   if ((MulAmtAbs - 1).isPowerOf2()) {
15891     // (mul x, 2^N + 1) => (add (shl x, N), x)
15892     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15893 
15894     if (!IsProfitable(IsNeg, true, VT))
15895       return SDValue();
15896 
15897     SDValue Op0 = N->getOperand(0);
15898     SDValue Op1 =
15899         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15900                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15901     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15902 
15903     if (!IsNeg)
15904       return Res;
15905 
15906     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15907   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15908     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15909     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15910 
15911     if (!IsProfitable(IsNeg, false, VT))
15912       return SDValue();
15913 
15914     SDValue Op0 = N->getOperand(0);
15915     SDValue Op1 =
15916         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15917                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15918 
15919     if (!IsNeg)
15920       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15921     else
15922       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15923 
15924   } else {
15925     return SDValue();
15926   }
15927 }
15928 
15929 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15930   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15931   if (!Subtarget.is64BitELFABI())
15932     return false;
15933 
15934   // If not a tail call then no need to proceed.
15935   if (!CI->isTailCall())
15936     return false;
15937 
15938   // If sibling calls have been disabled and tail-calls aren't guaranteed
15939   // there is no reason to duplicate.
15940   auto &TM = getTargetMachine();
15941   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15942     return false;
15943 
15944   // Can't tail call a function called indirectly, or if it has variadic args.
15945   const Function *Callee = CI->getCalledFunction();
15946   if (!Callee || Callee->isVarArg())
15947     return false;
15948 
15949   // Make sure the callee and caller calling conventions are eligible for tco.
15950   const Function *Caller = CI->getParent()->getParent();
15951   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15952                                            CI->getCallingConv()))
15953       return false;
15954 
15955   // If the function is local then we have a good chance at tail-calling it
15956   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15957 }
15958 
15959 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15960   if (!Subtarget.hasVSX())
15961     return false;
15962   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15963     return true;
15964   return VT == MVT::f32 || VT == MVT::f64 ||
15965     VT == MVT::v4f32 || VT == MVT::v2f64;
15966 }
15967 
15968 bool PPCTargetLowering::
15969 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15970   const Value *Mask = AndI.getOperand(1);
15971   // If the mask is suitable for andi. or andis. we should sink the and.
15972   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15973     // Can't handle constants wider than 64-bits.
15974     if (CI->getBitWidth() > 64)
15975       return false;
15976     int64_t ConstVal = CI->getZExtValue();
15977     return isUInt<16>(ConstVal) ||
15978       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15979   }
15980 
15981   // For non-constant masks, we can always use the record-form and.
15982   return true;
15983 }
15984 
15985 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15986 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15987 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15988 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15989 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15990 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15991   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15992   assert(Subtarget.hasP9Altivec() &&
15993          "Only combine this when P9 altivec supported!");
15994   EVT VT = N->getValueType(0);
15995   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15996     return SDValue();
15997 
15998   SelectionDAG &DAG = DCI.DAG;
15999   SDLoc dl(N);
16000   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16001     // Even for signed integers, if it's known to be positive (as signed
16002     // integer) due to zero-extended inputs.
16003     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16004     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16005     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16006          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16007         (SubOpcd1 == ISD::ZERO_EXTEND ||
16008          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16009       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16010                          N->getOperand(0)->getOperand(0),
16011                          N->getOperand(0)->getOperand(1),
16012                          DAG.getTargetConstant(0, dl, MVT::i32));
16013     }
16014 
16015     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16016     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16017         N->getOperand(0).hasOneUse()) {
16018       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16019                          N->getOperand(0)->getOperand(0),
16020                          N->getOperand(0)->getOperand(1),
16021                          DAG.getTargetConstant(1, dl, MVT::i32));
16022     }
16023   }
16024 
16025   return SDValue();
16026 }
16027 
16028 // For type v4i32/v8ii16/v16i8, transform
16029 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16030 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16031 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16032 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16033 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16034                                           DAGCombinerInfo &DCI) const {
16035   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16036   assert(Subtarget.hasP9Altivec() &&
16037          "Only combine this when P9 altivec supported!");
16038 
16039   SelectionDAG &DAG = DCI.DAG;
16040   SDLoc dl(N);
16041   SDValue Cond = N->getOperand(0);
16042   SDValue TrueOpnd = N->getOperand(1);
16043   SDValue FalseOpnd = N->getOperand(2);
16044   EVT VT = N->getOperand(1).getValueType();
16045 
16046   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16047       FalseOpnd.getOpcode() != ISD::SUB)
16048     return SDValue();
16049 
16050   // ABSD only available for type v4i32/v8i16/v16i8
16051   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16052     return SDValue();
16053 
16054   // At least to save one more dependent computation
16055   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16056     return SDValue();
16057 
16058   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16059 
16060   // Can only handle unsigned comparison here
16061   switch (CC) {
16062   default:
16063     return SDValue();
16064   case ISD::SETUGT:
16065   case ISD::SETUGE:
16066     break;
16067   case ISD::SETULT:
16068   case ISD::SETULE:
16069     std::swap(TrueOpnd, FalseOpnd);
16070     break;
16071   }
16072 
16073   SDValue CmpOpnd1 = Cond.getOperand(0);
16074   SDValue CmpOpnd2 = Cond.getOperand(1);
16075 
16076   // SETCC CmpOpnd1 CmpOpnd2 cond
16077   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16078   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16079   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16080       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16081       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16082       FalseOpnd.getOperand(1) == CmpOpnd1) {
16083     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16084                        CmpOpnd1, CmpOpnd2,
16085                        DAG.getTargetConstant(0, dl, MVT::i32));
16086   }
16087 
16088   return SDValue();
16089 }
16090