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, Custom);
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   unsigned TargetAlign = Lowering->getStackAlignment();
3451   unsigned AlignMask = TargetAlign - 1;
3452   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3453   return NumBytes;
3454 }
3455 
3456 SDValue PPCTargetLowering::LowerFormalArguments(
3457     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3458     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3459     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3460   if (Subtarget.isAIXABI())
3461     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3462                                     InVals);
3463   if (Subtarget.is64BitELFABI())
3464     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3465                                        InVals);
3466   if (Subtarget.is32BitELFABI())
3467     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3468                                        InVals);
3469 
3470   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3471                                      InVals);
3472 }
3473 
3474 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3475     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3476     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3477     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3478 
3479   // 32-bit SVR4 ABI Stack Frame Layout:
3480   //              +-----------------------------------+
3481   //        +-->  |            Back chain             |
3482   //        |     +-----------------------------------+
3483   //        |     | Floating-point register save area |
3484   //        |     +-----------------------------------+
3485   //        |     |    General register save area     |
3486   //        |     +-----------------------------------+
3487   //        |     |          CR save word             |
3488   //        |     +-----------------------------------+
3489   //        |     |         VRSAVE save word          |
3490   //        |     +-----------------------------------+
3491   //        |     |         Alignment padding         |
3492   //        |     +-----------------------------------+
3493   //        |     |     Vector register save area     |
3494   //        |     +-----------------------------------+
3495   //        |     |       Local variable space        |
3496   //        |     +-----------------------------------+
3497   //        |     |        Parameter list area        |
3498   //        |     +-----------------------------------+
3499   //        |     |           LR save word            |
3500   //        |     +-----------------------------------+
3501   // SP-->  +---  |            Back chain             |
3502   //              +-----------------------------------+
3503   //
3504   // Specifications:
3505   //   System V Application Binary Interface PowerPC Processor Supplement
3506   //   AltiVec Technology Programming Interface Manual
3507 
3508   MachineFunction &MF = DAG.getMachineFunction();
3509   MachineFrameInfo &MFI = MF.getFrameInfo();
3510   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3511 
3512   EVT PtrVT = getPointerTy(MF.getDataLayout());
3513   // Potential tail calls could cause overwriting of argument stack slots.
3514   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3515                        (CallConv == CallingConv::Fast));
3516   unsigned PtrByteSize = 4;
3517 
3518   // Assign locations to all of the incoming arguments.
3519   SmallVector<CCValAssign, 16> ArgLocs;
3520   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3521                  *DAG.getContext());
3522 
3523   // Reserve space for the linkage area on the stack.
3524   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3525   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3526   if (useSoftFloat())
3527     CCInfo.PreAnalyzeFormalArguments(Ins);
3528 
3529   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3530   CCInfo.clearWasPPCF128();
3531 
3532   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3533     CCValAssign &VA = ArgLocs[i];
3534 
3535     // Arguments stored in registers.
3536     if (VA.isRegLoc()) {
3537       const TargetRegisterClass *RC;
3538       EVT ValVT = VA.getValVT();
3539 
3540       switch (ValVT.getSimpleVT().SimpleTy) {
3541         default:
3542           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3543         case MVT::i1:
3544         case MVT::i32:
3545           RC = &PPC::GPRCRegClass;
3546           break;
3547         case MVT::f32:
3548           if (Subtarget.hasP8Vector())
3549             RC = &PPC::VSSRCRegClass;
3550           else if (Subtarget.hasSPE())
3551             RC = &PPC::GPRCRegClass;
3552           else
3553             RC = &PPC::F4RCRegClass;
3554           break;
3555         case MVT::f64:
3556           if (Subtarget.hasVSX())
3557             RC = &PPC::VSFRCRegClass;
3558           else if (Subtarget.hasSPE())
3559             // SPE passes doubles in GPR pairs.
3560             RC = &PPC::GPRCRegClass;
3561           else
3562             RC = &PPC::F8RCRegClass;
3563           break;
3564         case MVT::v16i8:
3565         case MVT::v8i16:
3566         case MVT::v4i32:
3567           RC = &PPC::VRRCRegClass;
3568           break;
3569         case MVT::v4f32:
3570           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3571           break;
3572         case MVT::v2f64:
3573         case MVT::v2i64:
3574           RC = &PPC::VRRCRegClass;
3575           break;
3576         case MVT::v4f64:
3577           RC = &PPC::QFRCRegClass;
3578           break;
3579         case MVT::v4i1:
3580           RC = &PPC::QBRCRegClass;
3581           break;
3582       }
3583 
3584       SDValue ArgValue;
3585       // Transform the arguments stored in physical registers into
3586       // virtual ones.
3587       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3588         assert(i + 1 < e && "No second half of double precision argument");
3589         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3590         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3591         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3592         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3593         if (!Subtarget.isLittleEndian())
3594           std::swap (ArgValueLo, ArgValueHi);
3595         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3596                                ArgValueHi);
3597       } else {
3598         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3599         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3600                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3601         if (ValVT == MVT::i1)
3602           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3603       }
3604 
3605       InVals.push_back(ArgValue);
3606     } else {
3607       // Argument stored in memory.
3608       assert(VA.isMemLoc());
3609 
3610       // Get the extended size of the argument type in stack
3611       unsigned ArgSize = VA.getLocVT().getStoreSize();
3612       // Get the actual size of the argument type
3613       unsigned ObjSize = VA.getValVT().getStoreSize();
3614       unsigned ArgOffset = VA.getLocMemOffset();
3615       // Stack objects in PPC32 are right justified.
3616       ArgOffset += ArgSize - ObjSize;
3617       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3618 
3619       // Create load nodes to retrieve arguments from the stack.
3620       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3621       InVals.push_back(
3622           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3623     }
3624   }
3625 
3626   // Assign locations to all of the incoming aggregate by value arguments.
3627   // Aggregates passed by value are stored in the local variable space of the
3628   // caller's stack frame, right above the parameter list area.
3629   SmallVector<CCValAssign, 16> ByValArgLocs;
3630   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3631                       ByValArgLocs, *DAG.getContext());
3632 
3633   // Reserve stack space for the allocations in CCInfo.
3634   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3635 
3636   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3637 
3638   // Area that is at least reserved in the caller of this function.
3639   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3640   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3641 
3642   // Set the size that is at least reserved in caller of this function.  Tail
3643   // call optimized function's reserved stack space needs to be aligned so that
3644   // taking the difference between two stack areas will result in an aligned
3645   // stack.
3646   MinReservedArea =
3647       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3648   FuncInfo->setMinReservedArea(MinReservedArea);
3649 
3650   SmallVector<SDValue, 8> MemOps;
3651 
3652   // If the function takes variable number of arguments, make a frame index for
3653   // the start of the first vararg value... for expansion of llvm.va_start.
3654   if (isVarArg) {
3655     static const MCPhysReg GPArgRegs[] = {
3656       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3657       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3658     };
3659     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3660 
3661     static const MCPhysReg FPArgRegs[] = {
3662       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3663       PPC::F8
3664     };
3665     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3666 
3667     if (useSoftFloat() || hasSPE())
3668        NumFPArgRegs = 0;
3669 
3670     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3671     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3672 
3673     // Make room for NumGPArgRegs and NumFPArgRegs.
3674     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3675                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3676 
3677     FuncInfo->setVarArgsStackOffset(
3678       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3679                             CCInfo.getNextStackOffset(), true));
3680 
3681     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3682     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3683 
3684     // The fixed integer arguments of a variadic function are stored to the
3685     // VarArgsFrameIndex on the stack so that they may be loaded by
3686     // dereferencing the result of va_next.
3687     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3688       // Get an existing live-in vreg, or add a new one.
3689       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3690       if (!VReg)
3691         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3692 
3693       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3694       SDValue Store =
3695           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3696       MemOps.push_back(Store);
3697       // Increment the address by four for the next argument to store
3698       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3699       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3700     }
3701 
3702     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3703     // is set.
3704     // The double arguments are stored to the VarArgsFrameIndex
3705     // on the stack.
3706     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3707       // Get an existing live-in vreg, or add a new one.
3708       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3709       if (!VReg)
3710         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3711 
3712       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3713       SDValue Store =
3714           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3715       MemOps.push_back(Store);
3716       // Increment the address by eight for the next argument to store
3717       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3718                                          PtrVT);
3719       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3720     }
3721   }
3722 
3723   if (!MemOps.empty())
3724     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3725 
3726   return Chain;
3727 }
3728 
3729 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3730 // value to MVT::i64 and then truncate to the correct register size.
3731 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3732                                              EVT ObjectVT, SelectionDAG &DAG,
3733                                              SDValue ArgVal,
3734                                              const SDLoc &dl) const {
3735   if (Flags.isSExt())
3736     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3737                          DAG.getValueType(ObjectVT));
3738   else if (Flags.isZExt())
3739     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3740                          DAG.getValueType(ObjectVT));
3741 
3742   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3743 }
3744 
3745 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3746     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3747     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3748     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3749   // TODO: add description of PPC stack frame format, or at least some docs.
3750   //
3751   bool isELFv2ABI = Subtarget.isELFv2ABI();
3752   bool isLittleEndian = Subtarget.isLittleEndian();
3753   MachineFunction &MF = DAG.getMachineFunction();
3754   MachineFrameInfo &MFI = MF.getFrameInfo();
3755   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3756 
3757   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3758          "fastcc not supported on varargs functions");
3759 
3760   EVT PtrVT = getPointerTy(MF.getDataLayout());
3761   // Potential tail calls could cause overwriting of argument stack slots.
3762   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3763                        (CallConv == CallingConv::Fast));
3764   unsigned PtrByteSize = 8;
3765   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3766 
3767   static const MCPhysReg GPR[] = {
3768     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3769     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3770   };
3771   static const MCPhysReg VR[] = {
3772     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3773     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3774   };
3775 
3776   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3777   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3778   const unsigned Num_VR_Regs  = array_lengthof(VR);
3779   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3780 
3781   // Do a first pass over the arguments to determine whether the ABI
3782   // guarantees that our caller has allocated the parameter save area
3783   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3784   // in the ELFv2 ABI, it is true if this is a vararg function or if
3785   // any parameter is located in a stack slot.
3786 
3787   bool HasParameterArea = !isELFv2ABI || isVarArg;
3788   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3789   unsigned NumBytes = LinkageSize;
3790   unsigned AvailableFPRs = Num_FPR_Regs;
3791   unsigned AvailableVRs = Num_VR_Regs;
3792   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3793     if (Ins[i].Flags.isNest())
3794       continue;
3795 
3796     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3797                                PtrByteSize, LinkageSize, ParamAreaSize,
3798                                NumBytes, AvailableFPRs, AvailableVRs,
3799                                Subtarget.hasQPX()))
3800       HasParameterArea = true;
3801   }
3802 
3803   // Add DAG nodes to load the arguments or copy them out of registers.  On
3804   // entry to a function on PPC, the arguments start after the linkage area,
3805   // although the first ones are often in registers.
3806 
3807   unsigned ArgOffset = LinkageSize;
3808   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3809   unsigned &QFPR_idx = FPR_idx;
3810   SmallVector<SDValue, 8> MemOps;
3811   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3812   unsigned CurArgIdx = 0;
3813   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3814     SDValue ArgVal;
3815     bool needsLoad = false;
3816     EVT ObjectVT = Ins[ArgNo].VT;
3817     EVT OrigVT = Ins[ArgNo].ArgVT;
3818     unsigned ObjSize = ObjectVT.getStoreSize();
3819     unsigned ArgSize = ObjSize;
3820     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3821     if (Ins[ArgNo].isOrigArg()) {
3822       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3823       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3824     }
3825     // We re-align the argument offset for each argument, except when using the
3826     // fast calling convention, when we need to make sure we do that only when
3827     // we'll actually use a stack slot.
3828     unsigned CurArgOffset;
3829     Align Alignment;
3830     auto ComputeArgOffset = [&]() {
3831       /* Respect alignment of argument on the stack.  */
3832       Alignment =
3833           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3834       ArgOffset = alignTo(ArgOffset, Alignment);
3835       CurArgOffset = ArgOffset;
3836     };
3837 
3838     if (CallConv != CallingConv::Fast) {
3839       ComputeArgOffset();
3840 
3841       /* Compute GPR index associated with argument offset.  */
3842       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3843       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3844     }
3845 
3846     // FIXME the codegen can be much improved in some cases.
3847     // We do not have to keep everything in memory.
3848     if (Flags.isByVal()) {
3849       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3850 
3851       if (CallConv == CallingConv::Fast)
3852         ComputeArgOffset();
3853 
3854       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3855       ObjSize = Flags.getByValSize();
3856       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3857       // Empty aggregate parameters do not take up registers.  Examples:
3858       //   struct { } a;
3859       //   union  { } b;
3860       //   int c[0];
3861       // etc.  However, we have to provide a place-holder in InVals, so
3862       // pretend we have an 8-byte item at the current address for that
3863       // purpose.
3864       if (!ObjSize) {
3865         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3866         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3867         InVals.push_back(FIN);
3868         continue;
3869       }
3870 
3871       // Create a stack object covering all stack doublewords occupied
3872       // by the argument.  If the argument is (fully or partially) on
3873       // the stack, or if the argument is fully in registers but the
3874       // caller has allocated the parameter save anyway, we can refer
3875       // directly to the caller's stack frame.  Otherwise, create a
3876       // local copy in our own frame.
3877       int FI;
3878       if (HasParameterArea ||
3879           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3880         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3881       else
3882         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3883       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3884 
3885       // Handle aggregates smaller than 8 bytes.
3886       if (ObjSize < PtrByteSize) {
3887         // The value of the object is its address, which differs from the
3888         // address of the enclosing doubleword on big-endian systems.
3889         SDValue Arg = FIN;
3890         if (!isLittleEndian) {
3891           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3892           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3893         }
3894         InVals.push_back(Arg);
3895 
3896         if (GPR_idx != Num_GPR_Regs) {
3897           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3898           FuncInfo->addLiveInAttr(VReg, Flags);
3899           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3900           SDValue Store;
3901 
3902           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3903             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3904                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3905             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3906                                       MachinePointerInfo(&*FuncArg), ObjType);
3907           } else {
3908             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3909             // store the whole register as-is to the parameter save area
3910             // slot.
3911             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3912                                  MachinePointerInfo(&*FuncArg));
3913           }
3914 
3915           MemOps.push_back(Store);
3916         }
3917         // Whether we copied from a register or not, advance the offset
3918         // into the parameter save area by a full doubleword.
3919         ArgOffset += PtrByteSize;
3920         continue;
3921       }
3922 
3923       // The value of the object is its address, which is the address of
3924       // its first stack doubleword.
3925       InVals.push_back(FIN);
3926 
3927       // Store whatever pieces of the object are in registers to memory.
3928       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3929         if (GPR_idx == Num_GPR_Regs)
3930           break;
3931 
3932         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3933         FuncInfo->addLiveInAttr(VReg, Flags);
3934         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3935         SDValue Addr = FIN;
3936         if (j) {
3937           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3938           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3939         }
3940         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3941                                      MachinePointerInfo(&*FuncArg, j));
3942         MemOps.push_back(Store);
3943         ++GPR_idx;
3944       }
3945       ArgOffset += ArgSize;
3946       continue;
3947     }
3948 
3949     switch (ObjectVT.getSimpleVT().SimpleTy) {
3950     default: llvm_unreachable("Unhandled argument type!");
3951     case MVT::i1:
3952     case MVT::i32:
3953     case MVT::i64:
3954       if (Flags.isNest()) {
3955         // The 'nest' parameter, if any, is passed in R11.
3956         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3957         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3958 
3959         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3960           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3961 
3962         break;
3963       }
3964 
3965       // These can be scalar arguments or elements of an integer array type
3966       // passed directly.  Clang may use those instead of "byval" aggregate
3967       // types to avoid forcing arguments to memory unnecessarily.
3968       if (GPR_idx != Num_GPR_Regs) {
3969         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3970         FuncInfo->addLiveInAttr(VReg, Flags);
3971         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3972 
3973         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3974           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3975           // value to MVT::i64 and then truncate to the correct register size.
3976           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3977       } else {
3978         if (CallConv == CallingConv::Fast)
3979           ComputeArgOffset();
3980 
3981         needsLoad = true;
3982         ArgSize = PtrByteSize;
3983       }
3984       if (CallConv != CallingConv::Fast || needsLoad)
3985         ArgOffset += 8;
3986       break;
3987 
3988     case MVT::f32:
3989     case MVT::f64:
3990       // These can be scalar arguments or elements of a float array type
3991       // passed directly.  The latter are used to implement ELFv2 homogenous
3992       // float aggregates.
3993       if (FPR_idx != Num_FPR_Regs) {
3994         unsigned VReg;
3995 
3996         if (ObjectVT == MVT::f32)
3997           VReg = MF.addLiveIn(FPR[FPR_idx],
3998                               Subtarget.hasP8Vector()
3999                                   ? &PPC::VSSRCRegClass
4000                                   : &PPC::F4RCRegClass);
4001         else
4002           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4003                                                 ? &PPC::VSFRCRegClass
4004                                                 : &PPC::F8RCRegClass);
4005 
4006         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4007         ++FPR_idx;
4008       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4009         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4010         // once we support fp <-> gpr moves.
4011 
4012         // This can only ever happen in the presence of f32 array types,
4013         // since otherwise we never run out of FPRs before running out
4014         // of GPRs.
4015         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4016         FuncInfo->addLiveInAttr(VReg, Flags);
4017         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4018 
4019         if (ObjectVT == MVT::f32) {
4020           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4021             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4022                                  DAG.getConstant(32, dl, MVT::i32));
4023           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4024         }
4025 
4026         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4027       } else {
4028         if (CallConv == CallingConv::Fast)
4029           ComputeArgOffset();
4030 
4031         needsLoad = true;
4032       }
4033 
4034       // When passing an array of floats, the array occupies consecutive
4035       // space in the argument area; only round up to the next doubleword
4036       // at the end of the array.  Otherwise, each float takes 8 bytes.
4037       if (CallConv != CallingConv::Fast || needsLoad) {
4038         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4039         ArgOffset += ArgSize;
4040         if (Flags.isInConsecutiveRegsLast())
4041           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4042       }
4043       break;
4044     case MVT::v4f32:
4045     case MVT::v4i32:
4046     case MVT::v8i16:
4047     case MVT::v16i8:
4048     case MVT::v2f64:
4049     case MVT::v2i64:
4050     case MVT::v1i128:
4051     case MVT::f128:
4052       if (!Subtarget.hasQPX()) {
4053         // These can be scalar arguments or elements of a vector array type
4054         // passed directly.  The latter are used to implement ELFv2 homogenous
4055         // vector aggregates.
4056         if (VR_idx != Num_VR_Regs) {
4057           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4058           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4059           ++VR_idx;
4060         } else {
4061           if (CallConv == CallingConv::Fast)
4062             ComputeArgOffset();
4063           needsLoad = true;
4064         }
4065         if (CallConv != CallingConv::Fast || needsLoad)
4066           ArgOffset += 16;
4067         break;
4068       } // not QPX
4069 
4070       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4071              "Invalid QPX parameter type");
4072       LLVM_FALLTHROUGH;
4073 
4074     case MVT::v4f64:
4075     case MVT::v4i1:
4076       // QPX vectors are treated like their scalar floating-point subregisters
4077       // (except that they're larger).
4078       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4079       if (QFPR_idx != Num_QFPR_Regs) {
4080         const TargetRegisterClass *RC;
4081         switch (ObjectVT.getSimpleVT().SimpleTy) {
4082         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4083         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4084         default:         RC = &PPC::QBRCRegClass; break;
4085         }
4086 
4087         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4088         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4089         ++QFPR_idx;
4090       } else {
4091         if (CallConv == CallingConv::Fast)
4092           ComputeArgOffset();
4093         needsLoad = true;
4094       }
4095       if (CallConv != CallingConv::Fast || needsLoad)
4096         ArgOffset += Sz;
4097       break;
4098     }
4099 
4100     // We need to load the argument to a virtual register if we determined
4101     // above that we ran out of physical registers of the appropriate type.
4102     if (needsLoad) {
4103       if (ObjSize < ArgSize && !isLittleEndian)
4104         CurArgOffset += ArgSize - ObjSize;
4105       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4106       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4107       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4108     }
4109 
4110     InVals.push_back(ArgVal);
4111   }
4112 
4113   // Area that is at least reserved in the caller of this function.
4114   unsigned MinReservedArea;
4115   if (HasParameterArea)
4116     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4117   else
4118     MinReservedArea = LinkageSize;
4119 
4120   // Set the size that is at least reserved in caller of this function.  Tail
4121   // call optimized functions' reserved stack space needs to be aligned so that
4122   // taking the difference between two stack areas will result in an aligned
4123   // stack.
4124   MinReservedArea =
4125       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4126   FuncInfo->setMinReservedArea(MinReservedArea);
4127 
4128   // If the function takes variable number of arguments, make a frame index for
4129   // the start of the first vararg value... for expansion of llvm.va_start.
4130   if (isVarArg) {
4131     int Depth = ArgOffset;
4132 
4133     FuncInfo->setVarArgsFrameIndex(
4134       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4135     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4136 
4137     // If this function is vararg, store any remaining integer argument regs
4138     // to their spots on the stack so that they may be loaded by dereferencing
4139     // the result of va_next.
4140     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4141          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4142       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4143       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4144       SDValue Store =
4145           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4146       MemOps.push_back(Store);
4147       // Increment the address by four for the next argument to store
4148       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4149       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4150     }
4151   }
4152 
4153   if (!MemOps.empty())
4154     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4155 
4156   return Chain;
4157 }
4158 
4159 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4160     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4161     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4162     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4163   // TODO: add description of PPC stack frame format, or at least some docs.
4164   //
4165   MachineFunction &MF = DAG.getMachineFunction();
4166   MachineFrameInfo &MFI = MF.getFrameInfo();
4167   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4168 
4169   EVT PtrVT = getPointerTy(MF.getDataLayout());
4170   bool isPPC64 = PtrVT == MVT::i64;
4171   // Potential tail calls could cause overwriting of argument stack slots.
4172   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4173                        (CallConv == CallingConv::Fast));
4174   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4175   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4176   unsigned ArgOffset = LinkageSize;
4177   // Area that is at least reserved in caller of this function.
4178   unsigned MinReservedArea = ArgOffset;
4179 
4180   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4181     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4182     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4183   };
4184   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4185     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4186     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4187   };
4188   static const MCPhysReg VR[] = {
4189     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4190     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4191   };
4192 
4193   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4194   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4195   const unsigned Num_VR_Regs  = array_lengthof( VR);
4196 
4197   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4198 
4199   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4200 
4201   // In 32-bit non-varargs functions, the stack space for vectors is after the
4202   // stack space for non-vectors.  We do not use this space unless we have
4203   // too many vectors to fit in registers, something that only occurs in
4204   // constructed examples:), but we have to walk the arglist to figure
4205   // that out...for the pathological case, compute VecArgOffset as the
4206   // start of the vector parameter area.  Computing VecArgOffset is the
4207   // entire point of the following loop.
4208   unsigned VecArgOffset = ArgOffset;
4209   if (!isVarArg && !isPPC64) {
4210     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4211          ++ArgNo) {
4212       EVT ObjectVT = Ins[ArgNo].VT;
4213       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4214 
4215       if (Flags.isByVal()) {
4216         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4217         unsigned ObjSize = Flags.getByValSize();
4218         unsigned ArgSize =
4219                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4220         VecArgOffset += ArgSize;
4221         continue;
4222       }
4223 
4224       switch(ObjectVT.getSimpleVT().SimpleTy) {
4225       default: llvm_unreachable("Unhandled argument type!");
4226       case MVT::i1:
4227       case MVT::i32:
4228       case MVT::f32:
4229         VecArgOffset += 4;
4230         break;
4231       case MVT::i64:  // PPC64
4232       case MVT::f64:
4233         // FIXME: We are guaranteed to be !isPPC64 at this point.
4234         // Does MVT::i64 apply?
4235         VecArgOffset += 8;
4236         break;
4237       case MVT::v4f32:
4238       case MVT::v4i32:
4239       case MVT::v8i16:
4240       case MVT::v16i8:
4241         // Nothing to do, we're only looking at Nonvector args here.
4242         break;
4243       }
4244     }
4245   }
4246   // We've found where the vector parameter area in memory is.  Skip the
4247   // first 12 parameters; these don't use that memory.
4248   VecArgOffset = ((VecArgOffset+15)/16)*16;
4249   VecArgOffset += 12*16;
4250 
4251   // Add DAG nodes to load the arguments or copy them out of registers.  On
4252   // entry to a function on PPC, the arguments start after the linkage area,
4253   // although the first ones are often in registers.
4254 
4255   SmallVector<SDValue, 8> MemOps;
4256   unsigned nAltivecParamsAtEnd = 0;
4257   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4258   unsigned CurArgIdx = 0;
4259   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4260     SDValue ArgVal;
4261     bool needsLoad = false;
4262     EVT ObjectVT = Ins[ArgNo].VT;
4263     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4264     unsigned ArgSize = ObjSize;
4265     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4266     if (Ins[ArgNo].isOrigArg()) {
4267       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4268       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4269     }
4270     unsigned CurArgOffset = ArgOffset;
4271 
4272     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4273     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4274         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4275       if (isVarArg || isPPC64) {
4276         MinReservedArea = ((MinReservedArea+15)/16)*16;
4277         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4278                                                   Flags,
4279                                                   PtrByteSize);
4280       } else  nAltivecParamsAtEnd++;
4281     } else
4282       // Calculate min reserved area.
4283       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4284                                                 Flags,
4285                                                 PtrByteSize);
4286 
4287     // FIXME the codegen can be much improved in some cases.
4288     // We do not have to keep everything in memory.
4289     if (Flags.isByVal()) {
4290       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4291 
4292       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4293       ObjSize = Flags.getByValSize();
4294       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4295       // Objects of size 1 and 2 are right justified, everything else is
4296       // left justified.  This means the memory address is adjusted forwards.
4297       if (ObjSize==1 || ObjSize==2) {
4298         CurArgOffset = CurArgOffset + (4 - ObjSize);
4299       }
4300       // The value of the object is its address.
4301       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4302       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4303       InVals.push_back(FIN);
4304       if (ObjSize==1 || ObjSize==2) {
4305         if (GPR_idx != Num_GPR_Regs) {
4306           unsigned VReg;
4307           if (isPPC64)
4308             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4309           else
4310             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4311           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4312           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4313           SDValue Store =
4314               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4315                                 MachinePointerInfo(&*FuncArg), ObjType);
4316           MemOps.push_back(Store);
4317           ++GPR_idx;
4318         }
4319 
4320         ArgOffset += PtrByteSize;
4321 
4322         continue;
4323       }
4324       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4325         // Store whatever pieces of the object are in registers
4326         // to memory.  ArgOffset will be the address of the beginning
4327         // of the object.
4328         if (GPR_idx != Num_GPR_Regs) {
4329           unsigned VReg;
4330           if (isPPC64)
4331             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4332           else
4333             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4334           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4335           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4336           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4337           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4338                                        MachinePointerInfo(&*FuncArg, j));
4339           MemOps.push_back(Store);
4340           ++GPR_idx;
4341           ArgOffset += PtrByteSize;
4342         } else {
4343           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4344           break;
4345         }
4346       }
4347       continue;
4348     }
4349 
4350     switch (ObjectVT.getSimpleVT().SimpleTy) {
4351     default: llvm_unreachable("Unhandled argument type!");
4352     case MVT::i1:
4353     case MVT::i32:
4354       if (!isPPC64) {
4355         if (GPR_idx != Num_GPR_Regs) {
4356           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4357           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4358 
4359           if (ObjectVT == MVT::i1)
4360             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4361 
4362           ++GPR_idx;
4363         } else {
4364           needsLoad = true;
4365           ArgSize = PtrByteSize;
4366         }
4367         // All int arguments reserve stack space in the Darwin ABI.
4368         ArgOffset += PtrByteSize;
4369         break;
4370       }
4371       LLVM_FALLTHROUGH;
4372     case MVT::i64:  // PPC64
4373       if (GPR_idx != Num_GPR_Regs) {
4374         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4375         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4376 
4377         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4378           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4379           // value to MVT::i64 and then truncate to the correct register size.
4380           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4381 
4382         ++GPR_idx;
4383       } else {
4384         needsLoad = true;
4385         ArgSize = PtrByteSize;
4386       }
4387       // All int arguments reserve stack space in the Darwin ABI.
4388       ArgOffset += 8;
4389       break;
4390 
4391     case MVT::f32:
4392     case MVT::f64:
4393       // Every 4 bytes of argument space consumes one of the GPRs available for
4394       // argument passing.
4395       if (GPR_idx != Num_GPR_Regs) {
4396         ++GPR_idx;
4397         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4398           ++GPR_idx;
4399       }
4400       if (FPR_idx != Num_FPR_Regs) {
4401         unsigned VReg;
4402 
4403         if (ObjectVT == MVT::f32)
4404           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4405         else
4406           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4407 
4408         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4409         ++FPR_idx;
4410       } else {
4411         needsLoad = true;
4412       }
4413 
4414       // All FP arguments reserve stack space in the Darwin ABI.
4415       ArgOffset += isPPC64 ? 8 : ObjSize;
4416       break;
4417     case MVT::v4f32:
4418     case MVT::v4i32:
4419     case MVT::v8i16:
4420     case MVT::v16i8:
4421       // Note that vector arguments in registers don't reserve stack space,
4422       // except in varargs functions.
4423       if (VR_idx != Num_VR_Regs) {
4424         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4425         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4426         if (isVarArg) {
4427           while ((ArgOffset % 16) != 0) {
4428             ArgOffset += PtrByteSize;
4429             if (GPR_idx != Num_GPR_Regs)
4430               GPR_idx++;
4431           }
4432           ArgOffset += 16;
4433           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4434         }
4435         ++VR_idx;
4436       } else {
4437         if (!isVarArg && !isPPC64) {
4438           // Vectors go after all the nonvectors.
4439           CurArgOffset = VecArgOffset;
4440           VecArgOffset += 16;
4441         } else {
4442           // Vectors are aligned.
4443           ArgOffset = ((ArgOffset+15)/16)*16;
4444           CurArgOffset = ArgOffset;
4445           ArgOffset += 16;
4446         }
4447         needsLoad = true;
4448       }
4449       break;
4450     }
4451 
4452     // We need to load the argument to a virtual register if we determined above
4453     // that we ran out of physical registers of the appropriate type.
4454     if (needsLoad) {
4455       int FI = MFI.CreateFixedObject(ObjSize,
4456                                      CurArgOffset + (ArgSize - ObjSize),
4457                                      isImmutable);
4458       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4459       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4460     }
4461 
4462     InVals.push_back(ArgVal);
4463   }
4464 
4465   // Allow for Altivec parameters at the end, if needed.
4466   if (nAltivecParamsAtEnd) {
4467     MinReservedArea = ((MinReservedArea+15)/16)*16;
4468     MinReservedArea += 16*nAltivecParamsAtEnd;
4469   }
4470 
4471   // Area that is at least reserved in the caller of this function.
4472   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4473 
4474   // Set the size that is at least reserved in caller of this function.  Tail
4475   // call optimized functions' reserved stack space needs to be aligned so that
4476   // taking the difference between two stack areas will result in an aligned
4477   // stack.
4478   MinReservedArea =
4479       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4480   FuncInfo->setMinReservedArea(MinReservedArea);
4481 
4482   // If the function takes variable number of arguments, make a frame index for
4483   // the start of the first vararg value... for expansion of llvm.va_start.
4484   if (isVarArg) {
4485     int Depth = ArgOffset;
4486 
4487     FuncInfo->setVarArgsFrameIndex(
4488       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4489                             Depth, true));
4490     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4491 
4492     // If this function is vararg, store any remaining integer argument regs
4493     // to their spots on the stack so that they may be loaded by dereferencing
4494     // the result of va_next.
4495     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4496       unsigned VReg;
4497 
4498       if (isPPC64)
4499         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4500       else
4501         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4502 
4503       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4504       SDValue Store =
4505           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4506       MemOps.push_back(Store);
4507       // Increment the address by four for the next argument to store
4508       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4509       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4510     }
4511   }
4512 
4513   if (!MemOps.empty())
4514     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4515 
4516   return Chain;
4517 }
4518 
4519 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4520 /// adjusted to accommodate the arguments for the tailcall.
4521 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4522                                    unsigned ParamSize) {
4523 
4524   if (!isTailCall) return 0;
4525 
4526   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4527   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4528   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4529   // Remember only if the new adjustment is bigger.
4530   if (SPDiff < FI->getTailCallSPDelta())
4531     FI->setTailCallSPDelta(SPDiff);
4532 
4533   return SPDiff;
4534 }
4535 
4536 static bool isFunctionGlobalAddress(SDValue Callee);
4537 
4538 static bool
4539 callsShareTOCBase(const Function *Caller, SDValue Callee,
4540                     const TargetMachine &TM) {
4541    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4542    // don't have enough information to determine if the caller and calle share
4543    // the same  TOC base, so we have to pessimistically assume they don't for
4544    // correctness.
4545    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4546    if (!G)
4547      return false;
4548 
4549    const GlobalValue *GV = G->getGlobal();
4550   // The medium and large code models are expected to provide a sufficiently
4551   // large TOC to provide all data addressing needs of a module with a
4552   // single TOC. Since each module will be addressed with a single TOC then we
4553   // only need to check that caller and callee don't cross dso boundaries.
4554   if (CodeModel::Medium == TM.getCodeModel() ||
4555       CodeModel::Large == TM.getCodeModel())
4556     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4557 
4558   // Otherwise we need to ensure callee and caller are in the same section,
4559   // since the linker may allocate multiple TOCs, and we don't know which
4560   // sections will belong to the same TOC base.
4561 
4562   if (!GV->isStrongDefinitionForLinker())
4563     return false;
4564 
4565   // Any explicitly-specified sections and section prefixes must also match.
4566   // Also, if we're using -ffunction-sections, then each function is always in
4567   // a different section (the same is true for COMDAT functions).
4568   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4569       GV->getSection() != Caller->getSection())
4570     return false;
4571   if (const auto *F = dyn_cast<Function>(GV)) {
4572     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4573       return false;
4574   }
4575 
4576   // If the callee might be interposed, then we can't assume the ultimate call
4577   // target will be in the same section. Even in cases where we can assume that
4578   // interposition won't happen, in any case where the linker might insert a
4579   // stub to allow for interposition, we must generate code as though
4580   // interposition might occur. To understand why this matters, consider a
4581   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4582   // in the same section, but a is in a different module (i.e. has a different
4583   // TOC base pointer). If the linker allows for interposition between b and c,
4584   // then it will generate a stub for the call edge between b and c which will
4585   // save the TOC pointer into the designated stack slot allocated by b. If we
4586   // return true here, and therefore allow a tail call between b and c, that
4587   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4588   // pointer into the stack slot allocated by a (where the a -> b stub saved
4589   // a's TOC base pointer). If we're not considering a tail call, but rather,
4590   // whether a nop is needed after the call instruction in b, because the linker
4591   // will insert a stub, it might complain about a missing nop if we omit it
4592   // (although many don't complain in this case).
4593   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4594     return false;
4595 
4596   return true;
4597 }
4598 
4599 static bool
4600 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4601                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4602   assert(Subtarget.is64BitELFABI());
4603 
4604   const unsigned PtrByteSize = 8;
4605   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4606 
4607   static const MCPhysReg GPR[] = {
4608     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4609     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4610   };
4611   static const MCPhysReg VR[] = {
4612     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4613     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4614   };
4615 
4616   const unsigned NumGPRs = array_lengthof(GPR);
4617   const unsigned NumFPRs = 13;
4618   const unsigned NumVRs = array_lengthof(VR);
4619   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4620 
4621   unsigned NumBytes = LinkageSize;
4622   unsigned AvailableFPRs = NumFPRs;
4623   unsigned AvailableVRs = NumVRs;
4624 
4625   for (const ISD::OutputArg& Param : Outs) {
4626     if (Param.Flags.isNest()) continue;
4627 
4628     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4629                                PtrByteSize, LinkageSize, ParamAreaSize,
4630                                NumBytes, AvailableFPRs, AvailableVRs,
4631                                Subtarget.hasQPX()))
4632       return true;
4633   }
4634   return false;
4635 }
4636 
4637 static bool
4638 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4639   if (CS.arg_size() != CallerFn->arg_size())
4640     return false;
4641 
4642   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4643   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4644   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4645 
4646   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4647     const Value* CalleeArg = *CalleeArgIter;
4648     const Value* CallerArg = &(*CallerArgIter);
4649     if (CalleeArg == CallerArg)
4650       continue;
4651 
4652     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4653     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4654     //      }
4655     // 1st argument of callee is undef and has the same type as caller.
4656     if (CalleeArg->getType() == CallerArg->getType() &&
4657         isa<UndefValue>(CalleeArg))
4658       continue;
4659 
4660     return false;
4661   }
4662 
4663   return true;
4664 }
4665 
4666 // Returns true if TCO is possible between the callers and callees
4667 // calling conventions.
4668 static bool
4669 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4670                                     CallingConv::ID CalleeCC) {
4671   // Tail calls are possible with fastcc and ccc.
4672   auto isTailCallableCC  = [] (CallingConv::ID CC){
4673       return  CC == CallingConv::C || CC == CallingConv::Fast;
4674   };
4675   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4676     return false;
4677 
4678   // We can safely tail call both fastcc and ccc callees from a c calling
4679   // convention caller. If the caller is fastcc, we may have less stack space
4680   // than a non-fastcc caller with the same signature so disable tail-calls in
4681   // that case.
4682   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4683 }
4684 
4685 bool
4686 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4687                                     SDValue Callee,
4688                                     CallingConv::ID CalleeCC,
4689                                     ImmutableCallSite CS,
4690                                     bool isVarArg,
4691                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4692                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4693                                     SelectionDAG& DAG) const {
4694   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4695 
4696   if (DisableSCO && !TailCallOpt) return false;
4697 
4698   // Variadic argument functions are not supported.
4699   if (isVarArg) return false;
4700 
4701   auto &Caller = DAG.getMachineFunction().getFunction();
4702   // Check that the calling conventions are compatible for tco.
4703   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4704     return false;
4705 
4706   // Caller contains any byval parameter is not supported.
4707   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4708     return false;
4709 
4710   // Callee contains any byval parameter is not supported, too.
4711   // Note: This is a quick work around, because in some cases, e.g.
4712   // caller's stack size > callee's stack size, we are still able to apply
4713   // sibling call optimization. For example, gcc is able to do SCO for caller1
4714   // in the following example, but not for caller2.
4715   //   struct test {
4716   //     long int a;
4717   //     char ary[56];
4718   //   } gTest;
4719   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4720   //     b->a = v.a;
4721   //     return 0;
4722   //   }
4723   //   void caller1(struct test a, struct test c, struct test *b) {
4724   //     callee(gTest, b); }
4725   //   void caller2(struct test *b) { callee(gTest, b); }
4726   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4727     return false;
4728 
4729   // If callee and caller use different calling conventions, we cannot pass
4730   // parameters on stack since offsets for the parameter area may be different.
4731   if (Caller.getCallingConv() != CalleeCC &&
4732       needStackSlotPassParameters(Subtarget, Outs))
4733     return false;
4734 
4735   // No TCO/SCO on indirect call because Caller have to restore its TOC
4736   if (!isFunctionGlobalAddress(Callee) &&
4737       !isa<ExternalSymbolSDNode>(Callee))
4738     return false;
4739 
4740   // If the caller and callee potentially have different TOC bases then we
4741   // cannot tail call since we need to restore the TOC pointer after the call.
4742   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4743   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4744     return false;
4745 
4746   // TCO allows altering callee ABI, so we don't have to check further.
4747   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4748     return true;
4749 
4750   if (DisableSCO) return false;
4751 
4752   // If callee use the same argument list that caller is using, then we can
4753   // apply SCO on this case. If it is not, then we need to check if callee needs
4754   // stack for passing arguments.
4755   if (!hasSameArgumentList(&Caller, CS) &&
4756       needStackSlotPassParameters(Subtarget, Outs)) {
4757     return false;
4758   }
4759 
4760   return true;
4761 }
4762 
4763 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4764 /// for tail call optimization. Targets which want to do tail call
4765 /// optimization should implement this function.
4766 bool
4767 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4768                                                      CallingConv::ID CalleeCC,
4769                                                      bool isVarArg,
4770                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4771                                                      SelectionDAG& DAG) const {
4772   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4773     return false;
4774 
4775   // Variable argument functions are not supported.
4776   if (isVarArg)
4777     return false;
4778 
4779   MachineFunction &MF = DAG.getMachineFunction();
4780   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4781   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4782     // Functions containing by val parameters are not supported.
4783     for (unsigned i = 0; i != Ins.size(); i++) {
4784        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4785        if (Flags.isByVal()) return false;
4786     }
4787 
4788     // Non-PIC/GOT tail calls are supported.
4789     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4790       return true;
4791 
4792     // At the moment we can only do local tail calls (in same module, hidden
4793     // or protected) if we are generating PIC.
4794     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4795       return G->getGlobal()->hasHiddenVisibility()
4796           || G->getGlobal()->hasProtectedVisibility();
4797   }
4798 
4799   return false;
4800 }
4801 
4802 /// isCallCompatibleAddress - Return the immediate to use if the specified
4803 /// 32-bit value is representable in the immediate field of a BxA instruction.
4804 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4805   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4806   if (!C) return nullptr;
4807 
4808   int Addr = C->getZExtValue();
4809   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4810       SignExtend32<26>(Addr) != Addr)
4811     return nullptr;  // Top 6 bits have to be sext of immediate.
4812 
4813   return DAG
4814       .getConstant(
4815           (int)C->getZExtValue() >> 2, SDLoc(Op),
4816           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4817       .getNode();
4818 }
4819 
4820 namespace {
4821 
4822 struct TailCallArgumentInfo {
4823   SDValue Arg;
4824   SDValue FrameIdxOp;
4825   int FrameIdx = 0;
4826 
4827   TailCallArgumentInfo() = default;
4828 };
4829 
4830 } // end anonymous namespace
4831 
4832 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4833 static void StoreTailCallArgumentsToStackSlot(
4834     SelectionDAG &DAG, SDValue Chain,
4835     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4836     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4837   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4838     SDValue Arg = TailCallArgs[i].Arg;
4839     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4840     int FI = TailCallArgs[i].FrameIdx;
4841     // Store relative to framepointer.
4842     MemOpChains.push_back(DAG.getStore(
4843         Chain, dl, Arg, FIN,
4844         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4845   }
4846 }
4847 
4848 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4849 /// the appropriate stack slot for the tail call optimized function call.
4850 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4851                                              SDValue OldRetAddr, SDValue OldFP,
4852                                              int SPDiff, const SDLoc &dl) {
4853   if (SPDiff) {
4854     // Calculate the new stack slot for the return address.
4855     MachineFunction &MF = DAG.getMachineFunction();
4856     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4857     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4858     bool isPPC64 = Subtarget.isPPC64();
4859     int SlotSize = isPPC64 ? 8 : 4;
4860     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4861     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4862                                                          NewRetAddrLoc, true);
4863     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4864     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4865     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4866                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4867   }
4868   return Chain;
4869 }
4870 
4871 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4872 /// the position of the argument.
4873 static void
4874 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4875                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4876                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4877   int Offset = ArgOffset + SPDiff;
4878   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4879   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4880   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4881   SDValue FIN = DAG.getFrameIndex(FI, VT);
4882   TailCallArgumentInfo Info;
4883   Info.Arg = Arg;
4884   Info.FrameIdxOp = FIN;
4885   Info.FrameIdx = FI;
4886   TailCallArguments.push_back(Info);
4887 }
4888 
4889 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4890 /// stack slot. Returns the chain as result and the loaded frame pointers in
4891 /// LROpOut/FPOpout. Used when tail calling.
4892 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4893     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4894     SDValue &FPOpOut, const SDLoc &dl) const {
4895   if (SPDiff) {
4896     // Load the LR and FP stack slot for later adjusting.
4897     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4898     LROpOut = getReturnAddrFrameIndex(DAG);
4899     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4900     Chain = SDValue(LROpOut.getNode(), 1);
4901   }
4902   return Chain;
4903 }
4904 
4905 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4906 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4907 /// specified by the specific parameter attribute. The copy will be passed as
4908 /// a byval function parameter.
4909 /// Sometimes what we are copying is the end of a larger object, the part that
4910 /// does not fit in registers.
4911 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4912                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4913                                          SelectionDAG &DAG, const SDLoc &dl) {
4914   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4915   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4916                        Flags.getNonZeroByValAlign(), false, false, false,
4917                        MachinePointerInfo(), MachinePointerInfo());
4918 }
4919 
4920 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4921 /// tail calls.
4922 static void LowerMemOpCallTo(
4923     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4924     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4925     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4926     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4927   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4928   if (!isTailCall) {
4929     if (isVector) {
4930       SDValue StackPtr;
4931       if (isPPC64)
4932         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4933       else
4934         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4935       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4936                            DAG.getConstant(ArgOffset, dl, PtrVT));
4937     }
4938     MemOpChains.push_back(
4939         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4940     // Calculate and remember argument location.
4941   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4942                                   TailCallArguments);
4943 }
4944 
4945 static void
4946 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4947                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4948                 SDValue FPOp,
4949                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4950   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4951   // might overwrite each other in case of tail call optimization.
4952   SmallVector<SDValue, 8> MemOpChains2;
4953   // Do not flag preceding copytoreg stuff together with the following stuff.
4954   InFlag = SDValue();
4955   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4956                                     MemOpChains2, dl);
4957   if (!MemOpChains2.empty())
4958     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4959 
4960   // Store the return address to the appropriate stack slot.
4961   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4962 
4963   // Emit callseq_end just before tailcall node.
4964   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4965                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4966   InFlag = Chain.getValue(1);
4967 }
4968 
4969 // Is this global address that of a function that can be called by name? (as
4970 // opposed to something that must hold a descriptor for an indirect call).
4971 static bool isFunctionGlobalAddress(SDValue Callee) {
4972   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4973     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4974         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4975       return false;
4976 
4977     return G->getGlobal()->getValueType()->isFunctionTy();
4978   }
4979 
4980   return false;
4981 }
4982 
4983 SDValue PPCTargetLowering::LowerCallResult(
4984     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4985     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4986     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4987   SmallVector<CCValAssign, 16> RVLocs;
4988   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4989                     *DAG.getContext());
4990 
4991   CCRetInfo.AnalyzeCallResult(
4992       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4993                ? RetCC_PPC_Cold
4994                : RetCC_PPC);
4995 
4996   // Copy all of the result registers out of their specified physreg.
4997   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4998     CCValAssign &VA = RVLocs[i];
4999     assert(VA.isRegLoc() && "Can only return in registers!");
5000 
5001     SDValue Val;
5002 
5003     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5004       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5005                                       InFlag);
5006       Chain = Lo.getValue(1);
5007       InFlag = Lo.getValue(2);
5008       VA = RVLocs[++i]; // skip ahead to next loc
5009       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5010                                       InFlag);
5011       Chain = Hi.getValue(1);
5012       InFlag = Hi.getValue(2);
5013       if (!Subtarget.isLittleEndian())
5014         std::swap (Lo, Hi);
5015       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5016     } else {
5017       Val = DAG.getCopyFromReg(Chain, dl,
5018                                VA.getLocReg(), VA.getLocVT(), InFlag);
5019       Chain = Val.getValue(1);
5020       InFlag = Val.getValue(2);
5021     }
5022 
5023     switch (VA.getLocInfo()) {
5024     default: llvm_unreachable("Unknown loc info!");
5025     case CCValAssign::Full: break;
5026     case CCValAssign::AExt:
5027       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5028       break;
5029     case CCValAssign::ZExt:
5030       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5031                         DAG.getValueType(VA.getValVT()));
5032       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5033       break;
5034     case CCValAssign::SExt:
5035       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5036                         DAG.getValueType(VA.getValVT()));
5037       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5038       break;
5039     }
5040 
5041     InVals.push_back(Val);
5042   }
5043 
5044   return Chain;
5045 }
5046 
5047 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5048                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5049   // PatchPoint calls are not indirect.
5050   if (isPatchPoint)
5051     return false;
5052 
5053   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5054     return false;
5055 
5056   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5057   // becuase the immediate function pointer points to a descriptor instead of
5058   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5059   // pointer immediate points to the global entry point, while the BLA would
5060   // need to jump to the local entry point (see rL211174).
5061   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5062       isBLACompatibleAddress(Callee, DAG))
5063     return false;
5064 
5065   return true;
5066 }
5067 
5068 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5069                               const Function &Caller,
5070                               const SDValue &Callee,
5071                               const PPCSubtarget &Subtarget,
5072                               const TargetMachine &TM) {
5073   if (CFlags.IsTailCall)
5074     return PPCISD::TC_RETURN;
5075 
5076   // This is a call through a function pointer.
5077   if (CFlags.IsIndirect) {
5078     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5079     // indirect calls. The save of the caller's TOC pointer to the stack will be
5080     // inserted into the DAG as part of call lowering. The restore of the TOC
5081     // pointer is modeled by using a pseudo instruction for the call opcode that
5082     // represents the 2 instruction sequence of an indirect branch and link,
5083     // immediately followed by a load of the TOC pointer from the the stack save
5084     // slot into gpr2.
5085     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5086       return PPCISD::BCTRL_LOAD_TOC;
5087 
5088     // An indirect call that does not need a TOC restore.
5089     return PPCISD::BCTRL;
5090   }
5091 
5092   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5093   // immediately following the call instruction if the caller and callee may
5094   // have different TOC bases. At link time if the linker determines the calls
5095   // may not share a TOC base, the call is redirected to a trampoline inserted
5096   // by the linker. The trampoline will (among other things) save the callers
5097   // TOC pointer at an ABI designated offset in the linkage area and the linker
5098   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5099   // into gpr2.
5100   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5101     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5102                                                   : PPCISD::CALL_NOP;
5103 
5104   return PPCISD::CALL;
5105 }
5106 
5107 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5108                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5109   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5110     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5111       return SDValue(Dest, 0);
5112 
5113   // Returns true if the callee is local, and false otherwise.
5114   auto isLocalCallee = [&]() {
5115     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5116     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5117     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5118 
5119     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5120            !dyn_cast_or_null<GlobalIFunc>(GV);
5121   };
5122 
5123   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5124   // a static relocation model causes some versions of GNU LD (2.17.50, at
5125   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5126   // built with secure-PLT.
5127   bool UsePlt =
5128       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5129       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5130 
5131   // On AIX, direct function calls reference the symbol for the function's
5132   // entry point, which is named by prepending a "." before the function's
5133   // C-linkage name.
5134   const auto getAIXFuncEntryPointSymbolSDNode =
5135       [&](StringRef FuncName, bool IsDeclaration,
5136           const XCOFF::StorageClass &SC) {
5137         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5138 
5139         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5140             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5141 
5142         if (IsDeclaration && !S->hasContainingCsect()) {
5143           // On AIX, an undefined symbol needs to be associated with a
5144           // MCSectionXCOFF to get the correct storage mapping class.
5145           // In this case, XCOFF::XMC_PR.
5146           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5147               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5148               SectionKind::getMetadata());
5149           S->setContainingCsect(Sec);
5150         }
5151 
5152         MVT PtrVT =
5153             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5154         return DAG.getMCSymbol(S, PtrVT);
5155       };
5156 
5157   if (isFunctionGlobalAddress(Callee)) {
5158     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5159     const GlobalValue *GV = G->getGlobal();
5160 
5161     if (!Subtarget.isAIXABI())
5162       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5163                                         UsePlt ? PPCII::MO_PLT : 0);
5164 
5165     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5166     const GlobalObject *GO = cast<GlobalObject>(GV);
5167     const XCOFF::StorageClass SC =
5168         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5169     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5170                                             SC);
5171   }
5172 
5173   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5174     const char *SymName = S->getSymbol();
5175     if (!Subtarget.isAIXABI())
5176       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5177                                          UsePlt ? PPCII::MO_PLT : 0);
5178 
5179     // If there exists a user-declared function whose name is the same as the
5180     // ExternalSymbol's, then we pick up the user-declared version.
5181     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5182     if (const Function *F =
5183             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5184       const XCOFF::StorageClass SC =
5185           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5186       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5187                                               SC);
5188     }
5189 
5190     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5191   }
5192 
5193   // No transformation needed.
5194   assert(Callee.getNode() && "What no callee?");
5195   return Callee;
5196 }
5197 
5198 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5199   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5200          "Expected a CALLSEQ_STARTSDNode.");
5201 
5202   // The last operand is the chain, except when the node has glue. If the node
5203   // has glue, then the last operand is the glue, and the chain is the second
5204   // last operand.
5205   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5206   if (LastValue.getValueType() != MVT::Glue)
5207     return LastValue;
5208 
5209   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5210 }
5211 
5212 // Creates the node that moves a functions address into the count register
5213 // to prepare for an indirect call instruction.
5214 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5215                                 SDValue &Glue, SDValue &Chain,
5216                                 const SDLoc &dl) {
5217   SDValue MTCTROps[] = {Chain, Callee, Glue};
5218   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5219   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5220                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5221   // The glue is the second value produced.
5222   Glue = Chain.getValue(1);
5223 }
5224 
5225 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5226                                           SDValue &Glue, SDValue &Chain,
5227                                           SDValue CallSeqStart,
5228                                           ImmutableCallSite CS, const SDLoc &dl,
5229                                           bool hasNest,
5230                                           const PPCSubtarget &Subtarget) {
5231   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5232   // entry point, but to the function descriptor (the function entry point
5233   // address is part of the function descriptor though).
5234   // The function descriptor is a three doubleword structure with the
5235   // following fields: function entry point, TOC base address and
5236   // environment pointer.
5237   // Thus for a call through a function pointer, the following actions need
5238   // to be performed:
5239   //   1. Save the TOC of the caller in the TOC save area of its stack
5240   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5241   //   2. Load the address of the function entry point from the function
5242   //      descriptor.
5243   //   3. Load the TOC of the callee from the function descriptor into r2.
5244   //   4. Load the environment pointer from the function descriptor into
5245   //      r11.
5246   //   5. Branch to the function entry point address.
5247   //   6. On return of the callee, the TOC of the caller needs to be
5248   //      restored (this is done in FinishCall()).
5249   //
5250   // The loads are scheduled at the beginning of the call sequence, and the
5251   // register copies are flagged together to ensure that no other
5252   // operations can be scheduled in between. E.g. without flagging the
5253   // copies together, a TOC access in the caller could be scheduled between
5254   // the assignment of the callee TOC and the branch to the callee, which leads
5255   // to incorrect code.
5256 
5257   // Start by loading the function address from the descriptor.
5258   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5259   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5260                       ? (MachineMemOperand::MODereferenceable |
5261                          MachineMemOperand::MOInvariant)
5262                       : MachineMemOperand::MONone;
5263 
5264   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5265 
5266   // Registers used in building the DAG.
5267   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5268   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5269 
5270   // Offsets of descriptor members.
5271   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5272   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5273 
5274   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5275   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5276 
5277   // One load for the functions entry point address.
5278   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5279                                     Alignment, MMOFlags);
5280 
5281   // One for loading the TOC anchor for the module that contains the called
5282   // function.
5283   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5284   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5285   SDValue TOCPtr =
5286       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5287                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5288 
5289   // One for loading the environment pointer.
5290   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5291   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5292   SDValue LoadEnvPtr =
5293       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5294                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5295 
5296 
5297   // Then copy the newly loaded TOC anchor to the TOC pointer.
5298   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5299   Chain = TOCVal.getValue(0);
5300   Glue = TOCVal.getValue(1);
5301 
5302   // If the function call has an explicit 'nest' parameter, it takes the
5303   // place of the environment pointer.
5304   assert((!hasNest || !Subtarget.isAIXABI()) &&
5305          "Nest parameter is not supported on AIX.");
5306   if (!hasNest) {
5307     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5308     Chain = EnvVal.getValue(0);
5309     Glue = EnvVal.getValue(1);
5310   }
5311 
5312   // The rest of the indirect call sequence is the same as the non-descriptor
5313   // DAG.
5314   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5315 }
5316 
5317 static void
5318 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5319                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5320                   SelectionDAG &DAG,
5321                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5322                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5323                   const PPCSubtarget &Subtarget) {
5324   const bool IsPPC64 = Subtarget.isPPC64();
5325   // MVT for a general purpose register.
5326   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5327 
5328   // First operand is always the chain.
5329   Ops.push_back(Chain);
5330 
5331   // If it's a direct call pass the callee as the second operand.
5332   if (!CFlags.IsIndirect)
5333     Ops.push_back(Callee);
5334   else {
5335     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5336 
5337     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5338     // on the stack (this would have been done in `LowerCall_64SVR4` or
5339     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5340     // represents both the indirect branch and a load that restores the TOC
5341     // pointer from the linkage area. The operand for the TOC restore is an add
5342     // of the TOC save offset to the stack pointer. This must be the second
5343     // operand: after the chain input but before any other variadic arguments.
5344     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5345       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5346 
5347       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5348       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5349       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5350       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5351       Ops.push_back(AddTOC);
5352     }
5353 
5354     // Add the register used for the environment pointer.
5355     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5356       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5357                                     RegVT));
5358 
5359 
5360     // Add CTR register as callee so a bctr can be emitted later.
5361     if (CFlags.IsTailCall)
5362       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5363   }
5364 
5365   // If this is a tail call add stack pointer delta.
5366   if (CFlags.IsTailCall)
5367     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5368 
5369   // Add argument registers to the end of the list so that they are known live
5370   // into the call.
5371   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5372     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5373                                   RegsToPass[i].second.getValueType()));
5374 
5375   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5376   // no way to mark dependencies as implicit here.
5377   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5378   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5379       !CFlags.IsPatchPoint)
5380     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5381 
5382   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5383   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5384     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5385 
5386   // Add a register mask operand representing the call-preserved registers.
5387   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5388   const uint32_t *Mask =
5389       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5390   assert(Mask && "Missing call preserved mask for calling convention");
5391   Ops.push_back(DAG.getRegisterMask(Mask));
5392 
5393   // If the glue is valid, it is the last operand.
5394   if (Glue.getNode())
5395     Ops.push_back(Glue);
5396 }
5397 
5398 SDValue PPCTargetLowering::FinishCall(
5399     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5400     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5401     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5402     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5403     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5404 
5405   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5406     setUsesTOCBasePtr(DAG);
5407 
5408   unsigned CallOpc =
5409       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5410                     Subtarget, DAG.getTarget());
5411 
5412   if (!CFlags.IsIndirect)
5413     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5414   else if (Subtarget.usesFunctionDescriptors())
5415     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5416                                   dl, CFlags.HasNest, Subtarget);
5417   else
5418     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5419 
5420   // Build the operand list for the call instruction.
5421   SmallVector<SDValue, 8> Ops;
5422   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5423                     SPDiff, Subtarget);
5424 
5425   // Emit tail call.
5426   if (CFlags.IsTailCall) {
5427     assert(((Callee.getOpcode() == ISD::Register &&
5428              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5429             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5430             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5431             isa<ConstantSDNode>(Callee)) &&
5432            "Expecting a global address, external symbol, absolute value or "
5433            "register");
5434     assert(CallOpc == PPCISD::TC_RETURN &&
5435            "Unexpected call opcode for a tail call.");
5436     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5437     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5438   }
5439 
5440   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5441   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5442   Glue = Chain.getValue(1);
5443 
5444   // When performing tail call optimization the callee pops its arguments off
5445   // the stack. Account for this here so these bytes can be pushed back on in
5446   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5447   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5448                          getTargetMachine().Options.GuaranteedTailCallOpt)
5449                             ? NumBytes
5450                             : 0;
5451 
5452   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5453                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5454                              Glue, dl);
5455   Glue = Chain.getValue(1);
5456 
5457   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5458                          DAG, InVals);
5459 }
5460 
5461 SDValue
5462 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5463                              SmallVectorImpl<SDValue> &InVals) const {
5464   SelectionDAG &DAG                     = CLI.DAG;
5465   SDLoc &dl                             = CLI.DL;
5466   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5467   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5468   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5469   SDValue Chain                         = CLI.Chain;
5470   SDValue Callee                        = CLI.Callee;
5471   bool &isTailCall                      = CLI.IsTailCall;
5472   CallingConv::ID CallConv              = CLI.CallConv;
5473   bool isVarArg                         = CLI.IsVarArg;
5474   bool isPatchPoint                     = CLI.IsPatchPoint;
5475   ImmutableCallSite CS                  = CLI.CS;
5476 
5477   if (isTailCall) {
5478     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5479       isTailCall = false;
5480     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5481       isTailCall =
5482         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5483                                                  isVarArg, Outs, Ins, DAG);
5484     else
5485       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5486                                                      Ins, DAG);
5487     if (isTailCall) {
5488       ++NumTailCalls;
5489       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5490         ++NumSiblingCalls;
5491 
5492       assert(isa<GlobalAddressSDNode>(Callee) &&
5493              "Callee should be an llvm::Function object.");
5494       LLVM_DEBUG(
5495           const GlobalValue *GV =
5496               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5497           const unsigned Width =
5498               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5499           dbgs() << "TCO caller: "
5500                  << left_justify(DAG.getMachineFunction().getName(), Width)
5501                  << ", callee linkage: " << GV->getVisibility() << ", "
5502                  << GV->getLinkage() << "\n");
5503     }
5504   }
5505 
5506   if (!isTailCall && CS && CS.isMustTailCall())
5507     report_fatal_error("failed to perform tail call elimination on a call "
5508                        "site marked musttail");
5509 
5510   // When long calls (i.e. indirect calls) are always used, calls are always
5511   // made via function pointer. If we have a function name, first translate it
5512   // into a pointer.
5513   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5514       !isTailCall)
5515     Callee = LowerGlobalAddress(Callee, DAG);
5516 
5517   CallFlags CFlags(
5518       CallConv, isTailCall, isVarArg, isPatchPoint,
5519       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5520       // hasNest
5521       Subtarget.is64BitELFABI() &&
5522           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5523 
5524   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5525     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5526                             InVals, CS);
5527 
5528   if (Subtarget.isSVR4ABI())
5529     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5530                             InVals, CS);
5531 
5532   if (Subtarget.isAIXABI())
5533     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5534                          InVals, CS);
5535 
5536   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5537                           InVals, CS);
5538 }
5539 
5540 SDValue PPCTargetLowering::LowerCall_32SVR4(
5541     SDValue Chain, SDValue Callee, CallFlags CFlags,
5542     const SmallVectorImpl<ISD::OutputArg> &Outs,
5543     const SmallVectorImpl<SDValue> &OutVals,
5544     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5545     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5546     ImmutableCallSite CS) const {
5547   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5548   // of the 32-bit SVR4 ABI stack frame layout.
5549 
5550   const CallingConv::ID CallConv = CFlags.CallConv;
5551   const bool IsVarArg = CFlags.IsVarArg;
5552   const bool IsTailCall = CFlags.IsTailCall;
5553 
5554   assert((CallConv == CallingConv::C ||
5555           CallConv == CallingConv::Cold ||
5556           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5557 
5558   unsigned PtrByteSize = 4;
5559 
5560   MachineFunction &MF = DAG.getMachineFunction();
5561 
5562   // Mark this function as potentially containing a function that contains a
5563   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5564   // and restoring the callers stack pointer in this functions epilog. This is
5565   // done because by tail calling the called function might overwrite the value
5566   // in this function's (MF) stack pointer stack slot 0(SP).
5567   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5568       CallConv == CallingConv::Fast)
5569     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5570 
5571   // Count how many bytes are to be pushed on the stack, including the linkage
5572   // area, parameter list area and the part of the local variable space which
5573   // contains copies of aggregates which are passed by value.
5574 
5575   // Assign locations to all of the outgoing arguments.
5576   SmallVector<CCValAssign, 16> ArgLocs;
5577   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5578 
5579   // Reserve space for the linkage area on the stack.
5580   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5581                        PtrByteSize);
5582   if (useSoftFloat())
5583     CCInfo.PreAnalyzeCallOperands(Outs);
5584 
5585   if (IsVarArg) {
5586     // Handle fixed and variable vector arguments differently.
5587     // Fixed vector arguments go into registers as long as registers are
5588     // available. Variable vector arguments always go into memory.
5589     unsigned NumArgs = Outs.size();
5590 
5591     for (unsigned i = 0; i != NumArgs; ++i) {
5592       MVT ArgVT = Outs[i].VT;
5593       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5594       bool Result;
5595 
5596       if (Outs[i].IsFixed) {
5597         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5598                                CCInfo);
5599       } else {
5600         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5601                                       ArgFlags, CCInfo);
5602       }
5603 
5604       if (Result) {
5605 #ifndef NDEBUG
5606         errs() << "Call operand #" << i << " has unhandled type "
5607              << EVT(ArgVT).getEVTString() << "\n";
5608 #endif
5609         llvm_unreachable(nullptr);
5610       }
5611     }
5612   } else {
5613     // All arguments are treated the same.
5614     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5615   }
5616   CCInfo.clearWasPPCF128();
5617 
5618   // Assign locations to all of the outgoing aggregate by value arguments.
5619   SmallVector<CCValAssign, 16> ByValArgLocs;
5620   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5621 
5622   // Reserve stack space for the allocations in CCInfo.
5623   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5624 
5625   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5626 
5627   // Size of the linkage area, parameter list area and the part of the local
5628   // space variable where copies of aggregates which are passed by value are
5629   // stored.
5630   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5631 
5632   // Calculate by how many bytes the stack has to be adjusted in case of tail
5633   // call optimization.
5634   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5635 
5636   // Adjust the stack pointer for the new arguments...
5637   // These operations are automatically eliminated by the prolog/epilog pass
5638   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5639   SDValue CallSeqStart = Chain;
5640 
5641   // Load the return address and frame pointer so it can be moved somewhere else
5642   // later.
5643   SDValue LROp, FPOp;
5644   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5645 
5646   // Set up a copy of the stack pointer for use loading and storing any
5647   // arguments that may not fit in the registers available for argument
5648   // passing.
5649   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5650 
5651   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5652   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5653   SmallVector<SDValue, 8> MemOpChains;
5654 
5655   bool seenFloatArg = false;
5656   // Walk the register/memloc assignments, inserting copies/loads.
5657   // i - Tracks the index into the list of registers allocated for the call
5658   // RealArgIdx - Tracks the index into the list of actual function arguments
5659   // j - Tracks the index into the list of byval arguments
5660   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5661        i != e;
5662        ++i, ++RealArgIdx) {
5663     CCValAssign &VA = ArgLocs[i];
5664     SDValue Arg = OutVals[RealArgIdx];
5665     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5666 
5667     if (Flags.isByVal()) {
5668       // Argument is an aggregate which is passed by value, thus we need to
5669       // create a copy of it in the local variable space of the current stack
5670       // frame (which is the stack frame of the caller) and pass the address of
5671       // this copy to the callee.
5672       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5673       CCValAssign &ByValVA = ByValArgLocs[j++];
5674       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5675 
5676       // Memory reserved in the local variable space of the callers stack frame.
5677       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5678 
5679       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5680       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5681                            StackPtr, PtrOff);
5682 
5683       // Create a copy of the argument in the local area of the current
5684       // stack frame.
5685       SDValue MemcpyCall =
5686         CreateCopyOfByValArgument(Arg, PtrOff,
5687                                   CallSeqStart.getNode()->getOperand(0),
5688                                   Flags, DAG, dl);
5689 
5690       // This must go outside the CALLSEQ_START..END.
5691       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5692                                                      SDLoc(MemcpyCall));
5693       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5694                              NewCallSeqStart.getNode());
5695       Chain = CallSeqStart = NewCallSeqStart;
5696 
5697       // Pass the address of the aggregate copy on the stack either in a
5698       // physical register or in the parameter list area of the current stack
5699       // frame to the callee.
5700       Arg = PtrOff;
5701     }
5702 
5703     // When useCRBits() is true, there can be i1 arguments.
5704     // It is because getRegisterType(MVT::i1) => MVT::i1,
5705     // and for other integer types getRegisterType() => MVT::i32.
5706     // Extend i1 and ensure callee will get i32.
5707     if (Arg.getValueType() == MVT::i1)
5708       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5709                         dl, MVT::i32, Arg);
5710 
5711     if (VA.isRegLoc()) {
5712       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5713       // Put argument in a physical register.
5714       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5715         bool IsLE = Subtarget.isLittleEndian();
5716         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5717                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5718         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5719         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5720                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5721         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5722                              SVal.getValue(0)));
5723       } else
5724         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5725     } else {
5726       // Put argument in the parameter list area of the current stack frame.
5727       assert(VA.isMemLoc());
5728       unsigned LocMemOffset = VA.getLocMemOffset();
5729 
5730       if (!IsTailCall) {
5731         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5732         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5733                              StackPtr, PtrOff);
5734 
5735         MemOpChains.push_back(
5736             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5737       } else {
5738         // Calculate and remember argument location.
5739         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5740                                  TailCallArguments);
5741       }
5742     }
5743   }
5744 
5745   if (!MemOpChains.empty())
5746     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5747 
5748   // Build a sequence of copy-to-reg nodes chained together with token chain
5749   // and flag operands which copy the outgoing args into the appropriate regs.
5750   SDValue InFlag;
5751   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5752     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5753                              RegsToPass[i].second, InFlag);
5754     InFlag = Chain.getValue(1);
5755   }
5756 
5757   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5758   // registers.
5759   if (IsVarArg) {
5760     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5761     SDValue Ops[] = { Chain, InFlag };
5762 
5763     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5764                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5765 
5766     InFlag = Chain.getValue(1);
5767   }
5768 
5769   if (IsTailCall)
5770     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5771                     TailCallArguments);
5772 
5773   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5774                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
5775 }
5776 
5777 // Copy an argument into memory, being careful to do this outside the
5778 // call sequence for the call to which the argument belongs.
5779 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5780     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5781     SelectionDAG &DAG, const SDLoc &dl) const {
5782   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5783                         CallSeqStart.getNode()->getOperand(0),
5784                         Flags, DAG, dl);
5785   // The MEMCPY must go outside the CALLSEQ_START..END.
5786   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5787   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5788                                                  SDLoc(MemcpyCall));
5789   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5790                          NewCallSeqStart.getNode());
5791   return NewCallSeqStart;
5792 }
5793 
5794 SDValue PPCTargetLowering::LowerCall_64SVR4(
5795     SDValue Chain, SDValue Callee, CallFlags CFlags,
5796     const SmallVectorImpl<ISD::OutputArg> &Outs,
5797     const SmallVectorImpl<SDValue> &OutVals,
5798     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5799     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5800     ImmutableCallSite CS) const {
5801   bool isELFv2ABI = Subtarget.isELFv2ABI();
5802   bool isLittleEndian = Subtarget.isLittleEndian();
5803   unsigned NumOps = Outs.size();
5804   bool IsSibCall = false;
5805   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5806 
5807   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5808   unsigned PtrByteSize = 8;
5809 
5810   MachineFunction &MF = DAG.getMachineFunction();
5811 
5812   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5813     IsSibCall = true;
5814 
5815   // Mark this function as potentially containing a function that contains a
5816   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5817   // and restoring the callers stack pointer in this functions epilog. This is
5818   // done because by tail calling the called function might overwrite the value
5819   // in this function's (MF) stack pointer stack slot 0(SP).
5820   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5821     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5822 
5823   assert(!(IsFastCall && CFlags.IsVarArg) &&
5824          "fastcc not supported on varargs functions");
5825 
5826   // Count how many bytes are to be pushed on the stack, including the linkage
5827   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5828   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5829   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5830   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5831   unsigned NumBytes = LinkageSize;
5832   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5833   unsigned &QFPR_idx = FPR_idx;
5834 
5835   static const MCPhysReg GPR[] = {
5836     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5837     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5838   };
5839   static const MCPhysReg VR[] = {
5840     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5841     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5842   };
5843 
5844   const unsigned NumGPRs = array_lengthof(GPR);
5845   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5846   const unsigned NumVRs  = array_lengthof(VR);
5847   const unsigned NumQFPRs = NumFPRs;
5848 
5849   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5850   // can be passed to the callee in registers.
5851   // For the fast calling convention, there is another check below.
5852   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5853   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5854   if (!HasParameterArea) {
5855     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5856     unsigned AvailableFPRs = NumFPRs;
5857     unsigned AvailableVRs = NumVRs;
5858     unsigned NumBytesTmp = NumBytes;
5859     for (unsigned i = 0; i != NumOps; ++i) {
5860       if (Outs[i].Flags.isNest()) continue;
5861       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5862                                 PtrByteSize, LinkageSize, ParamAreaSize,
5863                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5864                                 Subtarget.hasQPX()))
5865         HasParameterArea = true;
5866     }
5867   }
5868 
5869   // When using the fast calling convention, we don't provide backing for
5870   // arguments that will be in registers.
5871   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5872 
5873   // Avoid allocating parameter area for fastcc functions if all the arguments
5874   // can be passed in the registers.
5875   if (IsFastCall)
5876     HasParameterArea = false;
5877 
5878   // Add up all the space actually used.
5879   for (unsigned i = 0; i != NumOps; ++i) {
5880     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5881     EVT ArgVT = Outs[i].VT;
5882     EVT OrigVT = Outs[i].ArgVT;
5883 
5884     if (Flags.isNest())
5885       continue;
5886 
5887     if (IsFastCall) {
5888       if (Flags.isByVal()) {
5889         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5890         if (NumGPRsUsed > NumGPRs)
5891           HasParameterArea = true;
5892       } else {
5893         switch (ArgVT.getSimpleVT().SimpleTy) {
5894         default: llvm_unreachable("Unexpected ValueType for argument!");
5895         case MVT::i1:
5896         case MVT::i32:
5897         case MVT::i64:
5898           if (++NumGPRsUsed <= NumGPRs)
5899             continue;
5900           break;
5901         case MVT::v4i32:
5902         case MVT::v8i16:
5903         case MVT::v16i8:
5904         case MVT::v2f64:
5905         case MVT::v2i64:
5906         case MVT::v1i128:
5907         case MVT::f128:
5908           if (++NumVRsUsed <= NumVRs)
5909             continue;
5910           break;
5911         case MVT::v4f32:
5912           // When using QPX, this is handled like a FP register, otherwise, it
5913           // is an Altivec register.
5914           if (Subtarget.hasQPX()) {
5915             if (++NumFPRsUsed <= NumFPRs)
5916               continue;
5917           } else {
5918             if (++NumVRsUsed <= NumVRs)
5919               continue;
5920           }
5921           break;
5922         case MVT::f32:
5923         case MVT::f64:
5924         case MVT::v4f64: // QPX
5925         case MVT::v4i1:  // QPX
5926           if (++NumFPRsUsed <= NumFPRs)
5927             continue;
5928           break;
5929         }
5930         HasParameterArea = true;
5931       }
5932     }
5933 
5934     /* Respect alignment of argument on the stack.  */
5935     auto Alignement =
5936         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5937     NumBytes = alignTo(NumBytes, Alignement);
5938 
5939     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5940     if (Flags.isInConsecutiveRegsLast())
5941       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5942   }
5943 
5944   unsigned NumBytesActuallyUsed = NumBytes;
5945 
5946   // In the old ELFv1 ABI,
5947   // the prolog code of the callee may store up to 8 GPR argument registers to
5948   // the stack, allowing va_start to index over them in memory if its varargs.
5949   // Because we cannot tell if this is needed on the caller side, we have to
5950   // conservatively assume that it is needed.  As such, make sure we have at
5951   // least enough stack space for the caller to store the 8 GPRs.
5952   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5953   // really requires memory operands, e.g. a vararg function.
5954   if (HasParameterArea)
5955     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5956   else
5957     NumBytes = LinkageSize;
5958 
5959   // Tail call needs the stack to be aligned.
5960   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5961     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5962 
5963   int SPDiff = 0;
5964 
5965   // Calculate by how many bytes the stack has to be adjusted in case of tail
5966   // call optimization.
5967   if (!IsSibCall)
5968     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5969 
5970   // To protect arguments on the stack from being clobbered in a tail call,
5971   // force all the loads to happen before doing any other lowering.
5972   if (CFlags.IsTailCall)
5973     Chain = DAG.getStackArgumentTokenFactor(Chain);
5974 
5975   // Adjust the stack pointer for the new arguments...
5976   // These operations are automatically eliminated by the prolog/epilog pass
5977   if (!IsSibCall)
5978     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5979   SDValue CallSeqStart = Chain;
5980 
5981   // Load the return address and frame pointer so it can be move somewhere else
5982   // later.
5983   SDValue LROp, FPOp;
5984   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5985 
5986   // Set up a copy of the stack pointer for use loading and storing any
5987   // arguments that may not fit in the registers available for argument
5988   // passing.
5989   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5990 
5991   // Figure out which arguments are going to go in registers, and which in
5992   // memory.  Also, if this is a vararg function, floating point operations
5993   // must be stored to our stack, and loaded into integer regs as well, if
5994   // any integer regs are available for argument passing.
5995   unsigned ArgOffset = LinkageSize;
5996 
5997   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5998   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5999 
6000   SmallVector<SDValue, 8> MemOpChains;
6001   for (unsigned i = 0; i != NumOps; ++i) {
6002     SDValue Arg = OutVals[i];
6003     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6004     EVT ArgVT = Outs[i].VT;
6005     EVT OrigVT = Outs[i].ArgVT;
6006 
6007     // PtrOff will be used to store the current argument to the stack if a
6008     // register cannot be found for it.
6009     SDValue PtrOff;
6010 
6011     // We re-align the argument offset for each argument, except when using the
6012     // fast calling convention, when we need to make sure we do that only when
6013     // we'll actually use a stack slot.
6014     auto ComputePtrOff = [&]() {
6015       /* Respect alignment of argument on the stack.  */
6016       auto Alignment =
6017           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6018       ArgOffset = alignTo(ArgOffset, Alignment);
6019 
6020       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6021 
6022       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6023     };
6024 
6025     if (!IsFastCall) {
6026       ComputePtrOff();
6027 
6028       /* Compute GPR index associated with argument offset.  */
6029       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6030       GPR_idx = std::min(GPR_idx, NumGPRs);
6031     }
6032 
6033     // Promote integers to 64-bit values.
6034     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6035       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6036       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6037       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6038     }
6039 
6040     // FIXME memcpy is used way more than necessary.  Correctness first.
6041     // Note: "by value" is code for passing a structure by value, not
6042     // basic types.
6043     if (Flags.isByVal()) {
6044       // Note: Size includes alignment padding, so
6045       //   struct x { short a; char b; }
6046       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6047       // These are the proper values we need for right-justifying the
6048       // aggregate in a parameter register.
6049       unsigned Size = Flags.getByValSize();
6050 
6051       // An empty aggregate parameter takes up no storage and no
6052       // registers.
6053       if (Size == 0)
6054         continue;
6055 
6056       if (IsFastCall)
6057         ComputePtrOff();
6058 
6059       // All aggregates smaller than 8 bytes must be passed right-justified.
6060       if (Size==1 || Size==2 || Size==4) {
6061         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6062         if (GPR_idx != NumGPRs) {
6063           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6064                                         MachinePointerInfo(), VT);
6065           MemOpChains.push_back(Load.getValue(1));
6066           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6067 
6068           ArgOffset += PtrByteSize;
6069           continue;
6070         }
6071       }
6072 
6073       if (GPR_idx == NumGPRs && Size < 8) {
6074         SDValue AddPtr = PtrOff;
6075         if (!isLittleEndian) {
6076           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6077                                           PtrOff.getValueType());
6078           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6079         }
6080         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6081                                                           CallSeqStart,
6082                                                           Flags, DAG, dl);
6083         ArgOffset += PtrByteSize;
6084         continue;
6085       }
6086       // Copy entire object into memory.  There are cases where gcc-generated
6087       // code assumes it is there, even if it could be put entirely into
6088       // registers.  (This is not what the doc says.)
6089 
6090       // FIXME: The above statement is likely due to a misunderstanding of the
6091       // documents.  All arguments must be copied into the parameter area BY
6092       // THE CALLEE in the event that the callee takes the address of any
6093       // formal argument.  That has not yet been implemented.  However, it is
6094       // reasonable to use the stack area as a staging area for the register
6095       // load.
6096 
6097       // Skip this for small aggregates, as we will use the same slot for a
6098       // right-justified copy, below.
6099       if (Size >= 8)
6100         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6101                                                           CallSeqStart,
6102                                                           Flags, DAG, dl);
6103 
6104       // When a register is available, pass a small aggregate right-justified.
6105       if (Size < 8 && GPR_idx != NumGPRs) {
6106         // The easiest way to get this right-justified in a register
6107         // is to copy the structure into the rightmost portion of a
6108         // local variable slot, then load the whole slot into the
6109         // register.
6110         // FIXME: The memcpy seems to produce pretty awful code for
6111         // small aggregates, particularly for packed ones.
6112         // FIXME: It would be preferable to use the slot in the
6113         // parameter save area instead of a new local variable.
6114         SDValue AddPtr = PtrOff;
6115         if (!isLittleEndian) {
6116           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6117           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6118         }
6119         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6120                                                           CallSeqStart,
6121                                                           Flags, DAG, dl);
6122 
6123         // Load the slot into the register.
6124         SDValue Load =
6125             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6126         MemOpChains.push_back(Load.getValue(1));
6127         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6128 
6129         // Done with this argument.
6130         ArgOffset += PtrByteSize;
6131         continue;
6132       }
6133 
6134       // For aggregates larger than PtrByteSize, copy the pieces of the
6135       // object that fit into registers from the parameter save area.
6136       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6137         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6138         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6139         if (GPR_idx != NumGPRs) {
6140           SDValue Load =
6141               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6142           MemOpChains.push_back(Load.getValue(1));
6143           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6144           ArgOffset += PtrByteSize;
6145         } else {
6146           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6147           break;
6148         }
6149       }
6150       continue;
6151     }
6152 
6153     switch (Arg.getSimpleValueType().SimpleTy) {
6154     default: llvm_unreachable("Unexpected ValueType for argument!");
6155     case MVT::i1:
6156     case MVT::i32:
6157     case MVT::i64:
6158       if (Flags.isNest()) {
6159         // The 'nest' parameter, if any, is passed in R11.
6160         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6161         break;
6162       }
6163 
6164       // These can be scalar arguments or elements of an integer array type
6165       // passed directly.  Clang may use those instead of "byval" aggregate
6166       // types to avoid forcing arguments to memory unnecessarily.
6167       if (GPR_idx != NumGPRs) {
6168         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6169       } else {
6170         if (IsFastCall)
6171           ComputePtrOff();
6172 
6173         assert(HasParameterArea &&
6174                "Parameter area must exist to pass an argument in memory.");
6175         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6176                          true, CFlags.IsTailCall, false, MemOpChains,
6177                          TailCallArguments, dl);
6178         if (IsFastCall)
6179           ArgOffset += PtrByteSize;
6180       }
6181       if (!IsFastCall)
6182         ArgOffset += PtrByteSize;
6183       break;
6184     case MVT::f32:
6185     case MVT::f64: {
6186       // These can be scalar arguments or elements of a float array type
6187       // passed directly.  The latter are used to implement ELFv2 homogenous
6188       // float aggregates.
6189 
6190       // Named arguments go into FPRs first, and once they overflow, the
6191       // remaining arguments go into GPRs and then the parameter save area.
6192       // Unnamed arguments for vararg functions always go to GPRs and
6193       // then the parameter save area.  For now, put all arguments to vararg
6194       // routines always in both locations (FPR *and* GPR or stack slot).
6195       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6196       bool NeededLoad = false;
6197 
6198       // First load the argument into the next available FPR.
6199       if (FPR_idx != NumFPRs)
6200         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6201 
6202       // Next, load the argument into GPR or stack slot if needed.
6203       if (!NeedGPROrStack)
6204         ;
6205       else if (GPR_idx != NumGPRs && !IsFastCall) {
6206         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6207         // once we support fp <-> gpr moves.
6208 
6209         // In the non-vararg case, this can only ever happen in the
6210         // presence of f32 array types, since otherwise we never run
6211         // out of FPRs before running out of GPRs.
6212         SDValue ArgVal;
6213 
6214         // Double values are always passed in a single GPR.
6215         if (Arg.getValueType() != MVT::f32) {
6216           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6217 
6218         // Non-array float values are extended and passed in a GPR.
6219         } else if (!Flags.isInConsecutiveRegs()) {
6220           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6221           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6222 
6223         // If we have an array of floats, we collect every odd element
6224         // together with its predecessor into one GPR.
6225         } else if (ArgOffset % PtrByteSize != 0) {
6226           SDValue Lo, Hi;
6227           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6228           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6229           if (!isLittleEndian)
6230             std::swap(Lo, Hi);
6231           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6232 
6233         // The final element, if even, goes into the first half of a GPR.
6234         } else if (Flags.isInConsecutiveRegsLast()) {
6235           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6236           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6237           if (!isLittleEndian)
6238             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6239                                  DAG.getConstant(32, dl, MVT::i32));
6240 
6241         // Non-final even elements are skipped; they will be handled
6242         // together the with subsequent argument on the next go-around.
6243         } else
6244           ArgVal = SDValue();
6245 
6246         if (ArgVal.getNode())
6247           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6248       } else {
6249         if (IsFastCall)
6250           ComputePtrOff();
6251 
6252         // Single-precision floating-point values are mapped to the
6253         // second (rightmost) word of the stack doubleword.
6254         if (Arg.getValueType() == MVT::f32 &&
6255             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6256           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6257           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6258         }
6259 
6260         assert(HasParameterArea &&
6261                "Parameter area must exist to pass an argument in memory.");
6262         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6263                          true, CFlags.IsTailCall, false, MemOpChains,
6264                          TailCallArguments, dl);
6265 
6266         NeededLoad = true;
6267       }
6268       // When passing an array of floats, the array occupies consecutive
6269       // space in the argument area; only round up to the next doubleword
6270       // at the end of the array.  Otherwise, each float takes 8 bytes.
6271       if (!IsFastCall || NeededLoad) {
6272         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6273                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6274         if (Flags.isInConsecutiveRegsLast())
6275           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6276       }
6277       break;
6278     }
6279     case MVT::v4f32:
6280     case MVT::v4i32:
6281     case MVT::v8i16:
6282     case MVT::v16i8:
6283     case MVT::v2f64:
6284     case MVT::v2i64:
6285     case MVT::v1i128:
6286     case MVT::f128:
6287       if (!Subtarget.hasQPX()) {
6288       // These can be scalar arguments or elements of a vector array type
6289       // passed directly.  The latter are used to implement ELFv2 homogenous
6290       // vector aggregates.
6291 
6292       // For a varargs call, named arguments go into VRs or on the stack as
6293       // usual; unnamed arguments always go to the stack or the corresponding
6294       // GPRs when within range.  For now, we always put the value in both
6295       // locations (or even all three).
6296       if (CFlags.IsVarArg) {
6297         assert(HasParameterArea &&
6298                "Parameter area must exist if we have a varargs call.");
6299         // We could elide this store in the case where the object fits
6300         // entirely in R registers.  Maybe later.
6301         SDValue Store =
6302             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6303         MemOpChains.push_back(Store);
6304         if (VR_idx != NumVRs) {
6305           SDValue Load =
6306               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6307           MemOpChains.push_back(Load.getValue(1));
6308           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6309         }
6310         ArgOffset += 16;
6311         for (unsigned i=0; i<16; i+=PtrByteSize) {
6312           if (GPR_idx == NumGPRs)
6313             break;
6314           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6315                                    DAG.getConstant(i, dl, PtrVT));
6316           SDValue Load =
6317               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6318           MemOpChains.push_back(Load.getValue(1));
6319           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6320         }
6321         break;
6322       }
6323 
6324       // Non-varargs Altivec params go into VRs or on the stack.
6325       if (VR_idx != NumVRs) {
6326         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6327       } else {
6328         if (IsFastCall)
6329           ComputePtrOff();
6330 
6331         assert(HasParameterArea &&
6332                "Parameter area must exist to pass an argument in memory.");
6333         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6334                          true, CFlags.IsTailCall, true, MemOpChains,
6335                          TailCallArguments, dl);
6336         if (IsFastCall)
6337           ArgOffset += 16;
6338       }
6339 
6340       if (!IsFastCall)
6341         ArgOffset += 16;
6342       break;
6343       } // not QPX
6344 
6345       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6346              "Invalid QPX parameter type");
6347 
6348       LLVM_FALLTHROUGH;
6349     case MVT::v4f64:
6350     case MVT::v4i1: {
6351       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6352       if (CFlags.IsVarArg) {
6353         assert(HasParameterArea &&
6354                "Parameter area must exist if we have a varargs call.");
6355         // We could elide this store in the case where the object fits
6356         // entirely in R registers.  Maybe later.
6357         SDValue Store =
6358             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6359         MemOpChains.push_back(Store);
6360         if (QFPR_idx != NumQFPRs) {
6361           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6362                                      PtrOff, MachinePointerInfo());
6363           MemOpChains.push_back(Load.getValue(1));
6364           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6365         }
6366         ArgOffset += (IsF32 ? 16 : 32);
6367         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6368           if (GPR_idx == NumGPRs)
6369             break;
6370           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6371                                    DAG.getConstant(i, dl, PtrVT));
6372           SDValue Load =
6373               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6374           MemOpChains.push_back(Load.getValue(1));
6375           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6376         }
6377         break;
6378       }
6379 
6380       // Non-varargs QPX params go into registers or on the stack.
6381       if (QFPR_idx != NumQFPRs) {
6382         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6383       } else {
6384         if (IsFastCall)
6385           ComputePtrOff();
6386 
6387         assert(HasParameterArea &&
6388                "Parameter area must exist to pass an argument in memory.");
6389         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6390                          true, CFlags.IsTailCall, true, MemOpChains,
6391                          TailCallArguments, dl);
6392         if (IsFastCall)
6393           ArgOffset += (IsF32 ? 16 : 32);
6394       }
6395 
6396       if (!IsFastCall)
6397         ArgOffset += (IsF32 ? 16 : 32);
6398       break;
6399       }
6400     }
6401   }
6402 
6403   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6404          "mismatch in size of parameter area");
6405   (void)NumBytesActuallyUsed;
6406 
6407   if (!MemOpChains.empty())
6408     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6409 
6410   // Check if this is an indirect call (MTCTR/BCTRL).
6411   // See prepareDescriptorIndirectCall and buildCallOperands for more
6412   // information about calls through function pointers in the 64-bit SVR4 ABI.
6413   if (CFlags.IsIndirect) {
6414     assert(!CFlags.IsTailCall &&  "Indirect tails calls not supported");
6415     // Load r2 into a virtual register and store it to the TOC save area.
6416     setUsesTOCBasePtr(DAG);
6417     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6418     // TOC save area offset.
6419     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6420     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6421     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6422     Chain = DAG.getStore(
6423         Val.getValue(1), dl, Val, AddPtr,
6424         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6425     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6426     // This does not mean the MTCTR instruction must use R12; it's easier
6427     // to model this as an extra parameter, so do that.
6428     if (isELFv2ABI && !CFlags.IsPatchPoint)
6429       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6430   }
6431 
6432   // Build a sequence of copy-to-reg nodes chained together with token chain
6433   // and flag operands which copy the outgoing args into the appropriate regs.
6434   SDValue InFlag;
6435   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6436     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6437                              RegsToPass[i].second, InFlag);
6438     InFlag = Chain.getValue(1);
6439   }
6440 
6441   if (CFlags.IsTailCall && !IsSibCall)
6442     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6443                     TailCallArguments);
6444 
6445   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6446                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6447 }
6448 
6449 SDValue PPCTargetLowering::LowerCall_Darwin(
6450     SDValue Chain, SDValue Callee, CallFlags CFlags,
6451     const SmallVectorImpl<ISD::OutputArg> &Outs,
6452     const SmallVectorImpl<SDValue> &OutVals,
6453     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6454     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6455     ImmutableCallSite CS) const {
6456   unsigned NumOps = Outs.size();
6457 
6458   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6459   bool isPPC64 = PtrVT == MVT::i64;
6460   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6461 
6462   MachineFunction &MF = DAG.getMachineFunction();
6463 
6464   // Mark this function as potentially containing a function that contains a
6465   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6466   // and restoring the callers stack pointer in this functions epilog. This is
6467   // done because by tail calling the called function might overwrite the value
6468   // in this function's (MF) stack pointer stack slot 0(SP).
6469   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6470       CFlags.CallConv == CallingConv::Fast)
6471     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6472 
6473   // Count how many bytes are to be pushed on the stack, including the linkage
6474   // area, and parameter passing area.  We start with 24/48 bytes, which is
6475   // prereserved space for [SP][CR][LR][3 x unused].
6476   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6477   unsigned NumBytes = LinkageSize;
6478 
6479   // Add up all the space actually used.
6480   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6481   // they all go in registers, but we must reserve stack space for them for
6482   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6483   // assigned stack space in order, with padding so Altivec parameters are
6484   // 16-byte aligned.
6485   unsigned nAltivecParamsAtEnd = 0;
6486   for (unsigned i = 0; i != NumOps; ++i) {
6487     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6488     EVT ArgVT = Outs[i].VT;
6489     // Varargs Altivec parameters are padded to a 16 byte boundary.
6490     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6491         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6492         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6493       if (!CFlags.IsVarArg && !isPPC64) {
6494         // Non-varargs Altivec parameters go after all the non-Altivec
6495         // parameters; handle those later so we know how much padding we need.
6496         nAltivecParamsAtEnd++;
6497         continue;
6498       }
6499       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6500       NumBytes = ((NumBytes+15)/16)*16;
6501     }
6502     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6503   }
6504 
6505   // Allow for Altivec parameters at the end, if needed.
6506   if (nAltivecParamsAtEnd) {
6507     NumBytes = ((NumBytes+15)/16)*16;
6508     NumBytes += 16*nAltivecParamsAtEnd;
6509   }
6510 
6511   // The prolog code of the callee may store up to 8 GPR argument registers to
6512   // the stack, allowing va_start to index over them in memory if its varargs.
6513   // Because we cannot tell if this is needed on the caller side, we have to
6514   // conservatively assume that it is needed.  As such, make sure we have at
6515   // least enough stack space for the caller to store the 8 GPRs.
6516   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6517 
6518   // Tail call needs the stack to be aligned.
6519   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6520       CFlags.CallConv == CallingConv::Fast)
6521     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6522 
6523   // Calculate by how many bytes the stack has to be adjusted in case of tail
6524   // call optimization.
6525   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6526 
6527   // To protect arguments on the stack from being clobbered in a tail call,
6528   // force all the loads to happen before doing any other lowering.
6529   if (CFlags.IsTailCall)
6530     Chain = DAG.getStackArgumentTokenFactor(Chain);
6531 
6532   // Adjust the stack pointer for the new arguments...
6533   // These operations are automatically eliminated by the prolog/epilog pass
6534   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6535   SDValue CallSeqStart = Chain;
6536 
6537   // Load the return address and frame pointer so it can be move somewhere else
6538   // later.
6539   SDValue LROp, FPOp;
6540   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6541 
6542   // Set up a copy of the stack pointer for use loading and storing any
6543   // arguments that may not fit in the registers available for argument
6544   // passing.
6545   SDValue StackPtr;
6546   if (isPPC64)
6547     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6548   else
6549     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6550 
6551   // Figure out which arguments are going to go in registers, and which in
6552   // memory.  Also, if this is a vararg function, floating point operations
6553   // must be stored to our stack, and loaded into integer regs as well, if
6554   // any integer regs are available for argument passing.
6555   unsigned ArgOffset = LinkageSize;
6556   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6557 
6558   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6559     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6560     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6561   };
6562   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6563     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6564     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6565   };
6566   static const MCPhysReg VR[] = {
6567     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6568     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6569   };
6570   const unsigned NumGPRs = array_lengthof(GPR_32);
6571   const unsigned NumFPRs = 13;
6572   const unsigned NumVRs  = array_lengthof(VR);
6573 
6574   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6575 
6576   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6577   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6578 
6579   SmallVector<SDValue, 8> MemOpChains;
6580   for (unsigned i = 0; i != NumOps; ++i) {
6581     SDValue Arg = OutVals[i];
6582     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6583 
6584     // PtrOff will be used to store the current argument to the stack if a
6585     // register cannot be found for it.
6586     SDValue PtrOff;
6587 
6588     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6589 
6590     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6591 
6592     // On PPC64, promote integers to 64-bit values.
6593     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6594       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6595       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6596       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6597     }
6598 
6599     // FIXME memcpy is used way more than necessary.  Correctness first.
6600     // Note: "by value" is code for passing a structure by value, not
6601     // basic types.
6602     if (Flags.isByVal()) {
6603       unsigned Size = Flags.getByValSize();
6604       // Very small objects are passed right-justified.  Everything else is
6605       // passed left-justified.
6606       if (Size==1 || Size==2) {
6607         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6608         if (GPR_idx != NumGPRs) {
6609           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6610                                         MachinePointerInfo(), VT);
6611           MemOpChains.push_back(Load.getValue(1));
6612           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6613 
6614           ArgOffset += PtrByteSize;
6615         } else {
6616           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6617                                           PtrOff.getValueType());
6618           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6619           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6620                                                             CallSeqStart,
6621                                                             Flags, DAG, dl);
6622           ArgOffset += PtrByteSize;
6623         }
6624         continue;
6625       }
6626       // Copy entire object into memory.  There are cases where gcc-generated
6627       // code assumes it is there, even if it could be put entirely into
6628       // registers.  (This is not what the doc says.)
6629       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6630                                                         CallSeqStart,
6631                                                         Flags, DAG, dl);
6632 
6633       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6634       // copy the pieces of the object that fit into registers from the
6635       // parameter save area.
6636       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6637         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6638         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6639         if (GPR_idx != NumGPRs) {
6640           SDValue Load =
6641               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6642           MemOpChains.push_back(Load.getValue(1));
6643           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6644           ArgOffset += PtrByteSize;
6645         } else {
6646           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6647           break;
6648         }
6649       }
6650       continue;
6651     }
6652 
6653     switch (Arg.getSimpleValueType().SimpleTy) {
6654     default: llvm_unreachable("Unexpected ValueType for argument!");
6655     case MVT::i1:
6656     case MVT::i32:
6657     case MVT::i64:
6658       if (GPR_idx != NumGPRs) {
6659         if (Arg.getValueType() == MVT::i1)
6660           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6661 
6662         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6663       } else {
6664         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6665                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6666                          TailCallArguments, dl);
6667       }
6668       ArgOffset += PtrByteSize;
6669       break;
6670     case MVT::f32:
6671     case MVT::f64:
6672       if (FPR_idx != NumFPRs) {
6673         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6674 
6675         if (CFlags.IsVarArg) {
6676           SDValue Store =
6677               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6678           MemOpChains.push_back(Store);
6679 
6680           // Float varargs are always shadowed in available integer registers
6681           if (GPR_idx != NumGPRs) {
6682             SDValue Load =
6683                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6684             MemOpChains.push_back(Load.getValue(1));
6685             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6686           }
6687           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6688             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6689             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6690             SDValue Load =
6691                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6692             MemOpChains.push_back(Load.getValue(1));
6693             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6694           }
6695         } else {
6696           // If we have any FPRs remaining, we may also have GPRs remaining.
6697           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6698           // GPRs.
6699           if (GPR_idx != NumGPRs)
6700             ++GPR_idx;
6701           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6702               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6703             ++GPR_idx;
6704         }
6705       } else
6706         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6707                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6708                          TailCallArguments, dl);
6709       if (isPPC64)
6710         ArgOffset += 8;
6711       else
6712         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6713       break;
6714     case MVT::v4f32:
6715     case MVT::v4i32:
6716     case MVT::v8i16:
6717     case MVT::v16i8:
6718       if (CFlags.IsVarArg) {
6719         // These go aligned on the stack, or in the corresponding R registers
6720         // when within range.  The Darwin PPC ABI doc claims they also go in
6721         // V registers; in fact gcc does this only for arguments that are
6722         // prototyped, not for those that match the ...  We do it for all
6723         // arguments, seems to work.
6724         while (ArgOffset % 16 !=0) {
6725           ArgOffset += PtrByteSize;
6726           if (GPR_idx != NumGPRs)
6727             GPR_idx++;
6728         }
6729         // We could elide this store in the case where the object fits
6730         // entirely in R registers.  Maybe later.
6731         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6732                              DAG.getConstant(ArgOffset, dl, PtrVT));
6733         SDValue Store =
6734             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6735         MemOpChains.push_back(Store);
6736         if (VR_idx != NumVRs) {
6737           SDValue Load =
6738               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6739           MemOpChains.push_back(Load.getValue(1));
6740           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6741         }
6742         ArgOffset += 16;
6743         for (unsigned i=0; i<16; i+=PtrByteSize) {
6744           if (GPR_idx == NumGPRs)
6745             break;
6746           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6747                                    DAG.getConstant(i, dl, PtrVT));
6748           SDValue Load =
6749               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6750           MemOpChains.push_back(Load.getValue(1));
6751           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6752         }
6753         break;
6754       }
6755 
6756       // Non-varargs Altivec params generally go in registers, but have
6757       // stack space allocated at the end.
6758       if (VR_idx != NumVRs) {
6759         // Doesn't have GPR space allocated.
6760         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6761       } else if (nAltivecParamsAtEnd==0) {
6762         // We are emitting Altivec params in order.
6763         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6764                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6765                          TailCallArguments, dl);
6766         ArgOffset += 16;
6767       }
6768       break;
6769     }
6770   }
6771   // If all Altivec parameters fit in registers, as they usually do,
6772   // they get stack space following the non-Altivec parameters.  We
6773   // don't track this here because nobody below needs it.
6774   // If there are more Altivec parameters than fit in registers emit
6775   // the stores here.
6776   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6777     unsigned j = 0;
6778     // Offset is aligned; skip 1st 12 params which go in V registers.
6779     ArgOffset = ((ArgOffset+15)/16)*16;
6780     ArgOffset += 12*16;
6781     for (unsigned i = 0; i != NumOps; ++i) {
6782       SDValue Arg = OutVals[i];
6783       EVT ArgType = Outs[i].VT;
6784       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6785           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6786         if (++j > NumVRs) {
6787           SDValue PtrOff;
6788           // We are emitting Altivec params in order.
6789           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6790                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6791                            TailCallArguments, dl);
6792           ArgOffset += 16;
6793         }
6794       }
6795     }
6796   }
6797 
6798   if (!MemOpChains.empty())
6799     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6800 
6801   // On Darwin, R12 must contain the address of an indirect callee.  This does
6802   // not mean the MTCTR instruction must use R12; it's easier to model this as
6803   // an extra parameter, so do that.
6804   if (CFlags.IsIndirect) {
6805     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6806     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6807                                                    PPC::R12), Callee));
6808   }
6809 
6810   // Build a sequence of copy-to-reg nodes chained together with token chain
6811   // and flag operands which copy the outgoing args into the appropriate regs.
6812   SDValue InFlag;
6813   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6814     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6815                              RegsToPass[i].second, InFlag);
6816     InFlag = Chain.getValue(1);
6817   }
6818 
6819   if (CFlags.IsTailCall)
6820     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6821                     TailCallArguments);
6822 
6823   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6824                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6825 }
6826 
6827 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6828                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6829                    CCState &State) {
6830 
6831   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6832       State.getMachineFunction().getSubtarget());
6833   const bool IsPPC64 = Subtarget.isPPC64();
6834   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6835   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6836 
6837   assert((!ValVT.isInteger() ||
6838           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6839          "Integer argument exceeds register size: should have been legalized");
6840 
6841   if (ValVT == MVT::f128)
6842     report_fatal_error("f128 is unimplemented on AIX.");
6843 
6844   if (ArgFlags.isNest())
6845     report_fatal_error("Nest arguments are unimplemented.");
6846 
6847   if (ValVT.isVector() || LocVT.isVector())
6848     report_fatal_error("Vector arguments are unimplemented on AIX.");
6849 
6850   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6851                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6852                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6853   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6854                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6855                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6856 
6857   if (ArgFlags.isByVal()) {
6858     if (ArgFlags.getNonZeroByValAlign() > PtrByteSize)
6859       report_fatal_error("Pass-by-value arguments with alignment greater than "
6860                          "register width are not supported.");
6861 
6862     const unsigned ByValSize = ArgFlags.getByValSize();
6863 
6864     // An empty aggregate parameter takes up no storage and no registers,
6865     // but needs a MemLoc for a stack slot for the formal arguments side.
6866     if (ByValSize == 0) {
6867       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6868                                        State.getNextStackOffset(), RegVT,
6869                                        LocInfo));
6870       return false;
6871     }
6872 
6873     if (ByValSize <= PtrByteSize) {
6874       State.AllocateStack(PtrByteSize, PtrByteSize);
6875       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6876         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6877         return false;
6878       }
6879     }
6880 
6881     report_fatal_error(
6882         "Pass-by-value arguments are only supported in a single register.");
6883   }
6884 
6885   // Arguments always reserve parameter save area.
6886   switch (ValVT.SimpleTy) {
6887   default:
6888     report_fatal_error("Unhandled value type for argument.");
6889   case MVT::i64:
6890     // i64 arguments should have been split to i32 for PPC32.
6891     assert(IsPPC64 && "PPC32 should have split i64 values.");
6892     LLVM_FALLTHROUGH;
6893   case MVT::i1:
6894   case MVT::i32: {
6895     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
6896     // AIX integer arguments are always passed in register width.
6897     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6898       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6899                                   : CCValAssign::LocInfo::ZExt;
6900     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6901       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6902     else
6903       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6904 
6905     return false;
6906   }
6907   case MVT::f32:
6908   case MVT::f64: {
6909     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6910     const unsigned StoreSize = LocVT.getStoreSize();
6911     // Floats are always 4-byte aligned in the PSA on AIX.
6912     // This includes f64 in 64-bit mode for ABI compatibility.
6913     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6914     unsigned FReg = State.AllocateReg(FPR);
6915     if (FReg)
6916       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6917 
6918     // Reserve and initialize GPRs or initialize the PSA as required.
6919     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
6920       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6921         assert(FReg && "An FPR should be available when a GPR is reserved.");
6922         if (State.isVarArg()) {
6923           // Successfully reserved GPRs are only initialized for vararg calls.
6924           // Custom handling is required for:
6925           //   f64 in PPC32 needs to be split into 2 GPRs.
6926           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6927           State.addLoc(
6928               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6929         }
6930       } else {
6931         // If there are insufficient GPRs, the PSA needs to be initialized.
6932         // Initialization occurs even if an FPR was initialized for
6933         // compatibility with the AIX XL compiler. The full memory for the
6934         // argument will be initialized even if a prior word is saved in GPR.
6935         // A custom memLoc is used when the argument also passes in FPR so
6936         // that the callee handling can skip over it easily.
6937         State.addLoc(
6938             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6939                                              LocInfo)
6940                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6941         break;
6942       }
6943     }
6944 
6945     return false;
6946   }
6947   }
6948   return true;
6949 }
6950 
6951 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6952                                                     bool IsPPC64) {
6953   assert((IsPPC64 || SVT != MVT::i64) &&
6954          "i64 should have been split for 32-bit codegen.");
6955 
6956   switch (SVT) {
6957   default:
6958     report_fatal_error("Unexpected value type for formal argument");
6959   case MVT::i1:
6960   case MVT::i32:
6961   case MVT::i64:
6962     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6963   case MVT::f32:
6964     return &PPC::F4RCRegClass;
6965   case MVT::f64:
6966     return &PPC::F8RCRegClass;
6967   }
6968 }
6969 
6970 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6971                                         SelectionDAG &DAG, SDValue ArgValue,
6972                                         MVT LocVT, const SDLoc &dl) {
6973   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6974   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6975 
6976   if (Flags.isSExt())
6977     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6978                            DAG.getValueType(ValVT));
6979   else if (Flags.isZExt())
6980     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6981                            DAG.getValueType(ValVT));
6982 
6983   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6984 }
6985 
6986 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6987   const unsigned LASize = FL->getLinkageSize();
6988 
6989   if (PPC::GPRCRegClass.contains(Reg)) {
6990     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6991            "Reg must be a valid argument register!");
6992     return LASize + 4 * (Reg - PPC::R3);
6993   }
6994 
6995   if (PPC::G8RCRegClass.contains(Reg)) {
6996     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6997            "Reg must be a valid argument register!");
6998     return LASize + 8 * (Reg - PPC::X3);
6999   }
7000 
7001   llvm_unreachable("Only general purpose registers expected.");
7002 }
7003 
7004 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7005     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7006     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7007     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7008 
7009   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7010           CallConv == CallingConv::Fast) &&
7011          "Unexpected calling convention!");
7012 
7013   if (isVarArg)
7014     report_fatal_error("This call type is unimplemented on AIX.");
7015 
7016   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7017     report_fatal_error("Tail call support is unimplemented on AIX.");
7018 
7019   if (useSoftFloat())
7020     report_fatal_error("Soft float support is unimplemented on AIX.");
7021 
7022   const PPCSubtarget &Subtarget =
7023       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7024   if (Subtarget.hasQPX())
7025     report_fatal_error("QPX support is not supported on AIX.");
7026 
7027   const bool IsPPC64 = Subtarget.isPPC64();
7028   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7029 
7030   // Assign locations to all of the incoming arguments.
7031   SmallVector<CCValAssign, 16> ArgLocs;
7032   MachineFunction &MF = DAG.getMachineFunction();
7033   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7034 
7035   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7036   // Reserve space for the linkage area on the stack.
7037   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7038   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7039   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7040 
7041   SmallVector<SDValue, 8> MemOps;
7042 
7043   for (CCValAssign &VA : ArgLocs) {
7044     EVT ValVT = VA.getValVT();
7045     MVT LocVT = VA.getLocVT();
7046     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7047     assert((VA.isRegLoc() || VA.isMemLoc()) &&
7048            "Unexpected location for function call argument.");
7049 
7050     // For compatibility with the AIX XL compiler, the float args in the
7051     // parameter save area are initialized even if the argument is available
7052     // in register.  The caller is required to initialize both the register
7053     // and memory, however, the callee can choose to expect it in either.
7054     // The memloc is dismissed here because the argument is retrieved from
7055     // the register.
7056     if (VA.isMemLoc() && VA.needsCustom())
7057       continue;
7058 
7059     if (Flags.isByVal() && VA.isMemLoc()) {
7060       if (Flags.getByValSize() != 0)
7061         report_fatal_error(
7062             "ByVal arguments passed on stack not implemented yet");
7063 
7064       const int FI = MF.getFrameInfo().CreateFixedObject(
7065           PtrByteSize, VA.getLocMemOffset(), /* IsImmutable */ false,
7066           /* IsAliased */ true);
7067       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7068       InVals.push_back(FIN);
7069 
7070       continue;
7071     }
7072 
7073     if (Flags.isByVal()) {
7074       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7075 
7076       const unsigned ByValSize = Flags.getByValSize();
7077       if (ByValSize > PtrByteSize)
7078         report_fatal_error("Formal arguments greater then register size not "
7079                            "implemented yet.");
7080 
7081       const MCPhysReg ArgReg = VA.getLocReg();
7082       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7083       const unsigned Offset = mapArgRegToOffsetAIX(ArgReg, FL);
7084 
7085       const unsigned StackSize = alignTo(ByValSize, PtrByteSize);
7086       const int FI = MF.getFrameInfo().CreateFixedObject(
7087           StackSize, Offset, /* IsImmutable */ false, /* IsAliased */ true);
7088       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7089 
7090       InVals.push_back(FIN);
7091 
7092       const unsigned VReg = MF.addLiveIn(ArgReg, IsPPC64 ? &PPC::G8RCRegClass
7093                                                          : &PPC::GPRCRegClass);
7094 
7095       // Since the callers side has left justified the aggregate in the
7096       // register, we can simply store the entire register into the stack
7097       // slot.
7098       // The store to the fixedstack object is needed becuase accessing a
7099       // field of the ByVal will use a gep and load. Ideally we will optimize
7100       // to extracting the value from the register directly, and elide the
7101       // stores when the arguments address is not taken, but that will need to
7102       // be future work.
7103       SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7104       SDValue Store =
7105           DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, FIN,
7106                        MachinePointerInfo::getFixedStack(MF, FI, 0));
7107 
7108       MemOps.push_back(Store);
7109       continue;
7110     }
7111 
7112     if (VA.isRegLoc()) {
7113       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7114       unsigned VReg =
7115           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7116       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7117       if (ValVT.isScalarInteger() &&
7118           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7119         ArgValue =
7120             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7121       }
7122       InVals.push_back(ArgValue);
7123       continue;
7124     }
7125 
7126     const unsigned LocSize = LocVT.getStoreSize();
7127     const unsigned ValSize = ValVT.getStoreSize();
7128     assert((ValSize <= LocSize) && "Object size is larger than size of MemLoc");
7129     int CurArgOffset = VA.getLocMemOffset();
7130     // Objects are right-justified because AIX is big-endian.
7131     if (LocSize > ValSize)
7132       CurArgOffset += LocSize - ValSize;
7133     MachineFrameInfo &MFI = MF.getFrameInfo();
7134     // Potential tail calls could cause overwriting of argument stack slots.
7135     const bool IsImmutable =
7136         !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7137           (CallConv == CallingConv::Fast));
7138     int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7139     SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7140     SDValue ArgValue = DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7141     InVals.push_back(ArgValue);
7142   }
7143 
7144   // On AIX a minimum of 8 words is saved to the parameter save area.
7145   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7146   // Area that is at least reserved in the caller of this function.
7147   unsigned CallerReservedArea =
7148       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7149 
7150   // Set the size that is at least reserved in caller of this function. Tail
7151   // call optimized function's reserved stack space needs to be aligned so
7152   // that taking the difference between two stack areas will result in an
7153   // aligned stack.
7154   CallerReservedArea =
7155       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7156   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7157   FuncInfo->setMinReservedArea(CallerReservedArea);
7158 
7159   if (!MemOps.empty())
7160     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7161 
7162   return Chain;
7163 }
7164 
7165 SDValue PPCTargetLowering::LowerCall_AIX(
7166     SDValue Chain, SDValue Callee, CallFlags CFlags,
7167     const SmallVectorImpl<ISD::OutputArg> &Outs,
7168     const SmallVectorImpl<SDValue> &OutVals,
7169     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7170     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7171     ImmutableCallSite CS) const {
7172 
7173   assert((CFlags.CallConv == CallingConv::C ||
7174           CFlags.CallConv == CallingConv::Cold ||
7175           CFlags.CallConv == CallingConv::Fast) &&
7176          "Unexpected calling convention!");
7177 
7178   if (CFlags.IsPatchPoint)
7179     report_fatal_error("This call type is unimplemented on AIX.");
7180 
7181   const PPCSubtarget& Subtarget =
7182       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7183   if (Subtarget.hasQPX())
7184     report_fatal_error("QPX is not supported on AIX.");
7185   if (Subtarget.hasAltivec())
7186     report_fatal_error("Altivec support is unimplemented on AIX.");
7187 
7188   MachineFunction &MF = DAG.getMachineFunction();
7189   SmallVector<CCValAssign, 16> ArgLocs;
7190   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7191                  *DAG.getContext());
7192 
7193   // Reserve space for the linkage save area (LSA) on the stack.
7194   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7195   //   [SP][CR][LR][2 x reserved][TOC].
7196   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7197   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7198   const bool IsPPC64 = Subtarget.isPPC64();
7199   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7200   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7201   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7202   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7203 
7204   // The prolog code of the callee may store up to 8 GPR argument registers to
7205   // the stack, allowing va_start to index over them in memory if the callee
7206   // is variadic.
7207   // Because we cannot tell if this is needed on the caller side, we have to
7208   // conservatively assume that it is needed.  As such, make sure we have at
7209   // least enough stack space for the caller to store the 8 GPRs.
7210   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7211   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7212                                      CCInfo.getNextStackOffset());
7213 
7214   // Adjust the stack pointer for the new arguments...
7215   // These operations are automatically eliminated by the prolog/epilog pass.
7216   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7217   SDValue CallSeqStart = Chain;
7218 
7219   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7220   SmallVector<SDValue, 8> MemOpChains;
7221 
7222   // Set up a copy of the stack pointer for loading and storing any
7223   // arguments that may not fit in the registers available for argument
7224   // passing.
7225   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7226                                    : DAG.getRegister(PPC::R1, MVT::i32);
7227 
7228   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7229     CCValAssign &VA = ArgLocs[I++];
7230 
7231     SDValue Arg = OutVals[VA.getValNo()];
7232     ISD::ArgFlagsTy Flags = Outs[VA.getValNo()].Flags;
7233     const MVT LocVT = VA.getLocVT();
7234     const MVT ValVT = VA.getValVT();
7235 
7236     if (Flags.isByVal()) {
7237       const unsigned ByValSize = Flags.getByValSize();
7238 
7239       // Nothing to do for zero-sized ByVals on the caller side.
7240       if (!ByValSize)
7241         continue;
7242 
7243       assert(
7244           VA.isRegLoc() && ByValSize <= PtrByteSize &&
7245           "Pass-by-value arguments are only supported in a single register.");
7246 
7247       // Loads must be a power-of-2 size and cannot be larger than the
7248       // ByValSize. For example: a 7 byte by-val arg requires 4, 2 and 1 byte
7249       // loads.
7250       SDValue RegVal;
7251       for (unsigned Bytes = 0; Bytes != ByValSize;) {
7252         unsigned N = PowerOf2Floor(ByValSize - Bytes);
7253         const MVT VT =
7254             N == 1 ? MVT::i8
7255                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7256 
7257         SDValue LoadAddr = Arg;
7258         if (Bytes != 0) {
7259           // Adjust the load offset by the number of bytes read so far.
7260           SDNodeFlags Flags;
7261           Flags.setNoUnsignedWrap(true);
7262           LoadAddr = DAG.getNode(ISD::ADD, dl, LocVT, Arg,
7263                                  DAG.getConstant(Bytes, dl, LocVT), Flags);
7264         }
7265         SDValue Load = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, LoadAddr,
7266                                       MachinePointerInfo(), VT);
7267         MemOpChains.push_back(Load.getValue(1));
7268 
7269         Bytes += N;
7270         assert(LocVT.getSizeInBits() >= (Bytes * 8));
7271         if (unsigned NumSHLBits = LocVT.getSizeInBits() - (Bytes * 8)) {
7272           // By-val arguments are passed left-justfied in register.
7273           EVT ShiftAmountTy =
7274               getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7275           SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7276           SDValue ShiftedLoad =
7277               DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7278           RegVal = RegVal ? DAG.getNode(ISD::OR, dl, LocVT, RegVal, ShiftedLoad)
7279                           : ShiftedLoad;
7280         } else {
7281           assert(!RegVal && Bytes == ByValSize &&
7282                  "Pass-by-value argument handling unexpectedly incomplete.");
7283           RegVal = Load;
7284         }
7285       }
7286 
7287       RegsToPass.push_back(std::make_pair(VA.getLocReg(), RegVal));
7288       continue;
7289     }
7290 
7291     switch (VA.getLocInfo()) {
7292     default:
7293       report_fatal_error("Unexpected argument extension type.");
7294     case CCValAssign::Full:
7295       break;
7296     case CCValAssign::ZExt:
7297       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7298       break;
7299     case CCValAssign::SExt:
7300       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7301       break;
7302     }
7303 
7304     if (VA.isRegLoc() && !VA.needsCustom()) {
7305       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7306       continue;
7307     }
7308 
7309     if (VA.isMemLoc()) {
7310       SDValue PtrOff =
7311           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7312       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7313       MemOpChains.push_back(
7314           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7315 
7316       continue;
7317     }
7318 
7319     // Custom handling is used for GPR initializations for vararg float
7320     // arguments.
7321     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7322            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7323            "Unexpected register handling for calling convention.");
7324 
7325     SDValue ArgAsInt =
7326         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7327 
7328     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7329       // f32 in 32-bit GPR
7330       // f64 in 64-bit GPR
7331       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7332     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7333       // f32 in 64-bit GPR.
7334       RegsToPass.push_back(std::make_pair(
7335           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7336     else {
7337       // f64 in two 32-bit GPRs
7338       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7339       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7340              "Unexpected custom register for argument!");
7341       CCValAssign &GPR1 = VA;
7342       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7343                                      DAG.getConstant(32, dl, MVT::i8));
7344       RegsToPass.push_back(std::make_pair(
7345           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7346 
7347       if (I != E) {
7348         // If only 1 GPR was available, there will only be one custom GPR and
7349         // the argument will also pass in memory.
7350         CCValAssign &PeekArg = ArgLocs[I];
7351         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7352           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7353           CCValAssign &GPR2 = ArgLocs[I++];
7354           RegsToPass.push_back(std::make_pair(
7355               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7356         }
7357       }
7358     }
7359   }
7360 
7361   if (!MemOpChains.empty())
7362     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7363 
7364   // For indirect calls, we need to save the TOC base to the stack for
7365   // restoration after the call.
7366   if (CFlags.IsIndirect) {
7367     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7368     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7369     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7370     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7371     const unsigned TOCSaveOffset =
7372         Subtarget.getFrameLowering()->getTOCSaveOffset();
7373 
7374     setUsesTOCBasePtr(DAG);
7375     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7376     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7377     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7378     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7379     Chain = DAG.getStore(
7380         Val.getValue(1), dl, Val, AddPtr,
7381         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7382   }
7383 
7384   // Build a sequence of copy-to-reg nodes chained together with token chain
7385   // and flag operands which copy the outgoing args into the appropriate regs.
7386   SDValue InFlag;
7387   for (auto Reg : RegsToPass) {
7388     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7389     InFlag = Chain.getValue(1);
7390   }
7391 
7392   const int SPDiff = 0;
7393   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7394                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
7395 }
7396 
7397 bool
7398 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7399                                   MachineFunction &MF, bool isVarArg,
7400                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7401                                   LLVMContext &Context) const {
7402   SmallVector<CCValAssign, 16> RVLocs;
7403   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7404   return CCInfo.CheckReturn(
7405       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7406                 ? RetCC_PPC_Cold
7407                 : RetCC_PPC);
7408 }
7409 
7410 SDValue
7411 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7412                                bool isVarArg,
7413                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7414                                const SmallVectorImpl<SDValue> &OutVals,
7415                                const SDLoc &dl, SelectionDAG &DAG) const {
7416   SmallVector<CCValAssign, 16> RVLocs;
7417   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7418                  *DAG.getContext());
7419   CCInfo.AnalyzeReturn(Outs,
7420                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7421                            ? RetCC_PPC_Cold
7422                            : RetCC_PPC);
7423 
7424   SDValue Flag;
7425   SmallVector<SDValue, 4> RetOps(1, Chain);
7426 
7427   // Copy the result values into the output registers.
7428   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7429     CCValAssign &VA = RVLocs[i];
7430     assert(VA.isRegLoc() && "Can only return in registers!");
7431 
7432     SDValue Arg = OutVals[RealResIdx];
7433 
7434     switch (VA.getLocInfo()) {
7435     default: llvm_unreachable("Unknown loc info!");
7436     case CCValAssign::Full: break;
7437     case CCValAssign::AExt:
7438       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7439       break;
7440     case CCValAssign::ZExt:
7441       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7442       break;
7443     case CCValAssign::SExt:
7444       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7445       break;
7446     }
7447     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7448       bool isLittleEndian = Subtarget.isLittleEndian();
7449       // Legalize ret f64 -> ret 2 x i32.
7450       SDValue SVal =
7451           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7452                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7453       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7454       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7455       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7456                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7457       Flag = Chain.getValue(1);
7458       VA = RVLocs[++i]; // skip ahead to next loc
7459       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7460     } else
7461       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7462     Flag = Chain.getValue(1);
7463     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7464   }
7465 
7466   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7467   const MCPhysReg *I =
7468     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7469   if (I) {
7470     for (; *I; ++I) {
7471 
7472       if (PPC::G8RCRegClass.contains(*I))
7473         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7474       else if (PPC::F8RCRegClass.contains(*I))
7475         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7476       else if (PPC::CRRCRegClass.contains(*I))
7477         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7478       else if (PPC::VRRCRegClass.contains(*I))
7479         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7480       else
7481         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7482     }
7483   }
7484 
7485   RetOps[0] = Chain;  // Update chain.
7486 
7487   // Add the flag if we have it.
7488   if (Flag.getNode())
7489     RetOps.push_back(Flag);
7490 
7491   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7492 }
7493 
7494 SDValue
7495 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7496                                                 SelectionDAG &DAG) const {
7497   SDLoc dl(Op);
7498 
7499   // Get the correct type for integers.
7500   EVT IntVT = Op.getValueType();
7501 
7502   // Get the inputs.
7503   SDValue Chain = Op.getOperand(0);
7504   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7505   // Build a DYNAREAOFFSET node.
7506   SDValue Ops[2] = {Chain, FPSIdx};
7507   SDVTList VTs = DAG.getVTList(IntVT);
7508   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7509 }
7510 
7511 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7512                                              SelectionDAG &DAG) const {
7513   // When we pop the dynamic allocation we need to restore the SP link.
7514   SDLoc dl(Op);
7515 
7516   // Get the correct type for pointers.
7517   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7518 
7519   // Construct the stack pointer operand.
7520   bool isPPC64 = Subtarget.isPPC64();
7521   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7522   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7523 
7524   // Get the operands for the STACKRESTORE.
7525   SDValue Chain = Op.getOperand(0);
7526   SDValue SaveSP = Op.getOperand(1);
7527 
7528   // Load the old link SP.
7529   SDValue LoadLinkSP =
7530       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7531 
7532   // Restore the stack pointer.
7533   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7534 
7535   // Store the old link SP.
7536   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7537 }
7538 
7539 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7540   MachineFunction &MF = DAG.getMachineFunction();
7541   bool isPPC64 = Subtarget.isPPC64();
7542   EVT PtrVT = getPointerTy(MF.getDataLayout());
7543 
7544   // Get current frame pointer save index.  The users of this index will be
7545   // primarily DYNALLOC instructions.
7546   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7547   int RASI = FI->getReturnAddrSaveIndex();
7548 
7549   // If the frame pointer save index hasn't been defined yet.
7550   if (!RASI) {
7551     // Find out what the fix offset of the frame pointer save area.
7552     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7553     // Allocate the frame index for frame pointer save area.
7554     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7555     // Save the result.
7556     FI->setReturnAddrSaveIndex(RASI);
7557   }
7558   return DAG.getFrameIndex(RASI, PtrVT);
7559 }
7560 
7561 SDValue
7562 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7563   MachineFunction &MF = DAG.getMachineFunction();
7564   bool isPPC64 = Subtarget.isPPC64();
7565   EVT PtrVT = getPointerTy(MF.getDataLayout());
7566 
7567   // Get current frame pointer save index.  The users of this index will be
7568   // primarily DYNALLOC instructions.
7569   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7570   int FPSI = FI->getFramePointerSaveIndex();
7571 
7572   // If the frame pointer save index hasn't been defined yet.
7573   if (!FPSI) {
7574     // Find out what the fix offset of the frame pointer save area.
7575     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7576     // Allocate the frame index for frame pointer save area.
7577     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7578     // Save the result.
7579     FI->setFramePointerSaveIndex(FPSI);
7580   }
7581   return DAG.getFrameIndex(FPSI, PtrVT);
7582 }
7583 
7584 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7585                                                    SelectionDAG &DAG) const {
7586   // Get the inputs.
7587   SDValue Chain = Op.getOperand(0);
7588   SDValue Size  = Op.getOperand(1);
7589   SDLoc dl(Op);
7590 
7591   // Get the correct type for pointers.
7592   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7593   // Negate the size.
7594   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7595                                 DAG.getConstant(0, dl, PtrVT), Size);
7596   // Construct a node for the frame pointer save index.
7597   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7598   // Build a DYNALLOC node.
7599   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7600   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7601   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7602 }
7603 
7604 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7605                                                      SelectionDAG &DAG) const {
7606   MachineFunction &MF = DAG.getMachineFunction();
7607 
7608   bool isPPC64 = Subtarget.isPPC64();
7609   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7610 
7611   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7612   return DAG.getFrameIndex(FI, PtrVT);
7613 }
7614 
7615 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7616                                                SelectionDAG &DAG) const {
7617   SDLoc DL(Op);
7618   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7619                      DAG.getVTList(MVT::i32, MVT::Other),
7620                      Op.getOperand(0), Op.getOperand(1));
7621 }
7622 
7623 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7624                                                 SelectionDAG &DAG) const {
7625   SDLoc DL(Op);
7626   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7627                      Op.getOperand(0), Op.getOperand(1));
7628 }
7629 
7630 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7631   if (Op.getValueType().isVector())
7632     return LowerVectorLoad(Op, DAG);
7633 
7634   assert(Op.getValueType() == MVT::i1 &&
7635          "Custom lowering only for i1 loads");
7636 
7637   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7638 
7639   SDLoc dl(Op);
7640   LoadSDNode *LD = cast<LoadSDNode>(Op);
7641 
7642   SDValue Chain = LD->getChain();
7643   SDValue BasePtr = LD->getBasePtr();
7644   MachineMemOperand *MMO = LD->getMemOperand();
7645 
7646   SDValue NewLD =
7647       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7648                      BasePtr, MVT::i8, MMO);
7649   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7650 
7651   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7652   return DAG.getMergeValues(Ops, dl);
7653 }
7654 
7655 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7656   if (Op.getOperand(1).getValueType().isVector())
7657     return LowerVectorStore(Op, DAG);
7658 
7659   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7660          "Custom lowering only for i1 stores");
7661 
7662   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7663 
7664   SDLoc dl(Op);
7665   StoreSDNode *ST = cast<StoreSDNode>(Op);
7666 
7667   SDValue Chain = ST->getChain();
7668   SDValue BasePtr = ST->getBasePtr();
7669   SDValue Value = ST->getValue();
7670   MachineMemOperand *MMO = ST->getMemOperand();
7671 
7672   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7673                       Value);
7674   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7675 }
7676 
7677 // FIXME: Remove this once the ANDI glue bug is fixed:
7678 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7679   assert(Op.getValueType() == MVT::i1 &&
7680          "Custom lowering only for i1 results");
7681 
7682   SDLoc DL(Op);
7683   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7684 }
7685 
7686 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7687                                                SelectionDAG &DAG) const {
7688 
7689   // Implements a vector truncate that fits in a vector register as a shuffle.
7690   // We want to legalize vector truncates down to where the source fits in
7691   // a vector register (and target is therefore smaller than vector register
7692   // size).  At that point legalization will try to custom lower the sub-legal
7693   // result and get here - where we can contain the truncate as a single target
7694   // operation.
7695 
7696   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7697   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7698   //
7699   // We will implement it for big-endian ordering as this (where x denotes
7700   // undefined):
7701   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7702   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7703   //
7704   // The same operation in little-endian ordering will be:
7705   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7706   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7707 
7708   assert(Op.getValueType().isVector() && "Vector type expected.");
7709 
7710   SDLoc DL(Op);
7711   SDValue N1 = Op.getOperand(0);
7712   unsigned SrcSize = N1.getValueType().getSizeInBits();
7713   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7714   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7715 
7716   EVT TrgVT = Op.getValueType();
7717   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7718   EVT EltVT = TrgVT.getVectorElementType();
7719   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7720   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7721 
7722   // First list the elements we want to keep.
7723   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7724   SmallVector<int, 16> ShuffV;
7725   if (Subtarget.isLittleEndian())
7726     for (unsigned i = 0; i < TrgNumElts; ++i)
7727       ShuffV.push_back(i * SizeMult);
7728   else
7729     for (unsigned i = 1; i <= TrgNumElts; ++i)
7730       ShuffV.push_back(i * SizeMult - 1);
7731 
7732   // Populate the remaining elements with undefs.
7733   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7734     // ShuffV.push_back(i + WideNumElts);
7735     ShuffV.push_back(WideNumElts + 1);
7736 
7737   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7738   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7739 }
7740 
7741 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7742 /// possible.
7743 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7744   // Not FP? Not a fsel.
7745   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7746       !Op.getOperand(2).getValueType().isFloatingPoint())
7747     return Op;
7748 
7749   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7750 
7751   EVT ResVT = Op.getValueType();
7752   EVT CmpVT = Op.getOperand(0).getValueType();
7753   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7754   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7755   SDLoc dl(Op);
7756 
7757   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7758   // presence of infinities.
7759   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7760     switch (CC) {
7761     default:
7762       break;
7763     case ISD::SETOGT:
7764     case ISD::SETGT:
7765       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7766     case ISD::SETOLT:
7767     case ISD::SETLT:
7768       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7769     }
7770   }
7771 
7772   // We might be able to do better than this under some circumstances, but in
7773   // general, fsel-based lowering of select is a finite-math-only optimization.
7774   // For more information, see section F.3 of the 2.06 ISA specification.
7775   // With ISA 3.0
7776   if (!DAG.getTarget().Options.NoInfsFPMath ||
7777       !DAG.getTarget().Options.NoNaNsFPMath)
7778     return Op;
7779 
7780   // TODO: Propagate flags from the select rather than global settings.
7781   SDNodeFlags Flags;
7782   Flags.setNoInfs(true);
7783   Flags.setNoNaNs(true);
7784 
7785   // If the RHS of the comparison is a 0.0, we don't need to do the
7786   // subtraction at all.
7787   SDValue Sel1;
7788   if (isFloatingPointZero(RHS))
7789     switch (CC) {
7790     default: break;       // SETUO etc aren't handled by fsel.
7791     case ISD::SETNE:
7792       std::swap(TV, FV);
7793       LLVM_FALLTHROUGH;
7794     case ISD::SETEQ:
7795       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7796         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7797       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7798       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7799         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7800       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7801                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7802     case ISD::SETULT:
7803     case ISD::SETLT:
7804       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7805       LLVM_FALLTHROUGH;
7806     case ISD::SETOGE:
7807     case ISD::SETGE:
7808       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7809         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7810       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7811     case ISD::SETUGT:
7812     case ISD::SETGT:
7813       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7814       LLVM_FALLTHROUGH;
7815     case ISD::SETOLE:
7816     case ISD::SETLE:
7817       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7818         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7819       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7820                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7821     }
7822 
7823   SDValue Cmp;
7824   switch (CC) {
7825   default: break;       // SETUO etc aren't handled by fsel.
7826   case ISD::SETNE:
7827     std::swap(TV, FV);
7828     LLVM_FALLTHROUGH;
7829   case ISD::SETEQ:
7830     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7831     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7832       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7833     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7834     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7835       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7836     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7837                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7838   case ISD::SETULT:
7839   case ISD::SETLT:
7840     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7841     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7842       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7843     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7844   case ISD::SETOGE:
7845   case ISD::SETGE:
7846     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7847     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7848       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7849     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7850   case ISD::SETUGT:
7851   case ISD::SETGT:
7852     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7853     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7854       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7855     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7856   case ISD::SETOLE:
7857   case ISD::SETLE:
7858     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7859     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7860       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7861     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7862   }
7863   return Op;
7864 }
7865 
7866 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7867                                                SelectionDAG &DAG,
7868                                                const SDLoc &dl) const {
7869   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7870   SDValue Src = Op.getOperand(0);
7871   if (Src.getValueType() == MVT::f32)
7872     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7873 
7874   SDValue Tmp;
7875   switch (Op.getSimpleValueType().SimpleTy) {
7876   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7877   case MVT::i32:
7878     Tmp = DAG.getNode(
7879         Op.getOpcode() == ISD::FP_TO_SINT
7880             ? PPCISD::FCTIWZ
7881             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7882         dl, MVT::f64, Src);
7883     break;
7884   case MVT::i64:
7885     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7886            "i64 FP_TO_UINT is supported only with FPCVT");
7887     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7888                                                         PPCISD::FCTIDUZ,
7889                       dl, MVT::f64, Src);
7890     break;
7891   }
7892 
7893   // Convert the FP value to an int value through memory.
7894   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7895     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7896   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7897   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7898   MachinePointerInfo MPI =
7899       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7900 
7901   // Emit a store to the stack slot.
7902   SDValue Chain;
7903   if (i32Stack) {
7904     MachineFunction &MF = DAG.getMachineFunction();
7905     MachineMemOperand *MMO =
7906       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7907     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7908     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7909               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7910   } else
7911     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7912 
7913   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7914   // add in a bias on big endian.
7915   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7916     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7917                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7918     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7919   }
7920 
7921   RLI.Chain = Chain;
7922   RLI.Ptr = FIPtr;
7923   RLI.MPI = MPI;
7924 }
7925 
7926 /// Custom lowers floating point to integer conversions to use
7927 /// the direct move instructions available in ISA 2.07 to avoid the
7928 /// need for load/store combinations.
7929 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7930                                                     SelectionDAG &DAG,
7931                                                     const SDLoc &dl) const {
7932   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7933   SDValue Src = Op.getOperand(0);
7934 
7935   if (Src.getValueType() == MVT::f32)
7936     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7937 
7938   SDValue Tmp;
7939   switch (Op.getSimpleValueType().SimpleTy) {
7940   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7941   case MVT::i32:
7942     Tmp = DAG.getNode(
7943         Op.getOpcode() == ISD::FP_TO_SINT
7944             ? PPCISD::FCTIWZ
7945             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7946         dl, MVT::f64, Src);
7947     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7948     break;
7949   case MVT::i64:
7950     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7951            "i64 FP_TO_UINT is supported only with FPCVT");
7952     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7953                                                         PPCISD::FCTIDUZ,
7954                       dl, MVT::f64, Src);
7955     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7956     break;
7957   }
7958   return Tmp;
7959 }
7960 
7961 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7962                                           const SDLoc &dl) const {
7963 
7964   // FP to INT conversions are legal for f128.
7965   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7966     return Op;
7967 
7968   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7969   // PPC (the libcall is not available).
7970   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7971     if (Op.getValueType() == MVT::i32) {
7972       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7973         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7974                                  MVT::f64, Op.getOperand(0),
7975                                  DAG.getIntPtrConstant(0, dl));
7976         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7977                                  MVT::f64, Op.getOperand(0),
7978                                  DAG.getIntPtrConstant(1, dl));
7979 
7980         // Add the two halves of the long double in round-to-zero mode.
7981         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7982 
7983         // Now use a smaller FP_TO_SINT.
7984         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7985       }
7986       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7987         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7988         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7989         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7990         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7991         // FIXME: generated code sucks.
7992         // TODO: Are there fast-math-flags to propagate to this FSUB?
7993         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7994                                    Op.getOperand(0), Tmp);
7995         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7996         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7997                            DAG.getConstant(0x80000000, dl, MVT::i32));
7998         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7999                                     Op.getOperand(0));
8000         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8001                                ISD::SETGE);
8002       }
8003     }
8004 
8005     return SDValue();
8006   }
8007 
8008   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8009     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8010 
8011   ReuseLoadInfo RLI;
8012   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8013 
8014   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8015                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8016 }
8017 
8018 // We're trying to insert a regular store, S, and then a load, L. If the
8019 // incoming value, O, is a load, we might just be able to have our load use the
8020 // address used by O. However, we don't know if anything else will store to
8021 // that address before we can load from it. To prevent this situation, we need
8022 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8023 // the same chain operand as O, we create a token factor from the chain results
8024 // of O and L, and we replace all uses of O's chain result with that token
8025 // factor (see spliceIntoChain below for this last part).
8026 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8027                                             ReuseLoadInfo &RLI,
8028                                             SelectionDAG &DAG,
8029                                             ISD::LoadExtType ET) const {
8030   SDLoc dl(Op);
8031   if (ET == ISD::NON_EXTLOAD &&
8032       (Op.getOpcode() == ISD::FP_TO_UINT ||
8033        Op.getOpcode() == ISD::FP_TO_SINT) &&
8034       isOperationLegalOrCustom(Op.getOpcode(),
8035                                Op.getOperand(0).getValueType())) {
8036 
8037     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8038     return true;
8039   }
8040 
8041   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8042   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8043       LD->isNonTemporal())
8044     return false;
8045   if (LD->getMemoryVT() != MemVT)
8046     return false;
8047 
8048   RLI.Ptr = LD->getBasePtr();
8049   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8050     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8051            "Non-pre-inc AM on PPC?");
8052     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8053                           LD->getOffset());
8054   }
8055 
8056   RLI.Chain = LD->getChain();
8057   RLI.MPI = LD->getPointerInfo();
8058   RLI.IsDereferenceable = LD->isDereferenceable();
8059   RLI.IsInvariant = LD->isInvariant();
8060   RLI.Alignment = LD->getAlignment();
8061   RLI.AAInfo = LD->getAAInfo();
8062   RLI.Ranges = LD->getRanges();
8063 
8064   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8065   return true;
8066 }
8067 
8068 // Given the head of the old chain, ResChain, insert a token factor containing
8069 // it and NewResChain, and make users of ResChain now be users of that token
8070 // factor.
8071 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8072 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8073                                         SDValue NewResChain,
8074                                         SelectionDAG &DAG) const {
8075   if (!ResChain)
8076     return;
8077 
8078   SDLoc dl(NewResChain);
8079 
8080   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8081                            NewResChain, DAG.getUNDEF(MVT::Other));
8082   assert(TF.getNode() != NewResChain.getNode() &&
8083          "A new TF really is required here");
8084 
8085   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8086   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8087 }
8088 
8089 /// Analyze profitability of direct move
8090 /// prefer float load to int load plus direct move
8091 /// when there is no integer use of int load
8092 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8093   SDNode *Origin = Op.getOperand(0).getNode();
8094   if (Origin->getOpcode() != ISD::LOAD)
8095     return true;
8096 
8097   // If there is no LXSIBZX/LXSIHZX, like Power8,
8098   // prefer direct move if the memory size is 1 or 2 bytes.
8099   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8100   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8101     return true;
8102 
8103   for (SDNode::use_iterator UI = Origin->use_begin(),
8104                             UE = Origin->use_end();
8105        UI != UE; ++UI) {
8106 
8107     // Only look at the users of the loaded value.
8108     if (UI.getUse().get().getResNo() != 0)
8109       continue;
8110 
8111     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8112         UI->getOpcode() != ISD::UINT_TO_FP)
8113       return true;
8114   }
8115 
8116   return false;
8117 }
8118 
8119 /// Custom lowers integer to floating point conversions to use
8120 /// the direct move instructions available in ISA 2.07 to avoid the
8121 /// need for load/store combinations.
8122 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8123                                                     SelectionDAG &DAG,
8124                                                     const SDLoc &dl) const {
8125   assert((Op.getValueType() == MVT::f32 ||
8126           Op.getValueType() == MVT::f64) &&
8127          "Invalid floating point type as target of conversion");
8128   assert(Subtarget.hasFPCVT() &&
8129          "Int to FP conversions with direct moves require FPCVT");
8130   SDValue FP;
8131   SDValue Src = Op.getOperand(0);
8132   bool SinglePrec = Op.getValueType() == MVT::f32;
8133   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8134   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8135   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8136                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8137 
8138   if (WordInt) {
8139     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8140                      dl, MVT::f64, Src);
8141     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8142   }
8143   else {
8144     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8145     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8146   }
8147 
8148   return FP;
8149 }
8150 
8151 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8152 
8153   EVT VecVT = Vec.getValueType();
8154   assert(VecVT.isVector() && "Expected a vector type.");
8155   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8156 
8157   EVT EltVT = VecVT.getVectorElementType();
8158   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8159   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8160 
8161   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8162   SmallVector<SDValue, 16> Ops(NumConcat);
8163   Ops[0] = Vec;
8164   SDValue UndefVec = DAG.getUNDEF(VecVT);
8165   for (unsigned i = 1; i < NumConcat; ++i)
8166     Ops[i] = UndefVec;
8167 
8168   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8169 }
8170 
8171 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8172                                                 const SDLoc &dl) const {
8173 
8174   unsigned Opc = Op.getOpcode();
8175   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8176          "Unexpected conversion type");
8177   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8178          "Supports conversions to v2f64/v4f32 only.");
8179 
8180   bool SignedConv = Opc == ISD::SINT_TO_FP;
8181   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8182 
8183   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8184   EVT WideVT = Wide.getValueType();
8185   unsigned WideNumElts = WideVT.getVectorNumElements();
8186   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8187 
8188   SmallVector<int, 16> ShuffV;
8189   for (unsigned i = 0; i < WideNumElts; ++i)
8190     ShuffV.push_back(i + WideNumElts);
8191 
8192   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8193   int SaveElts = FourEltRes ? 4 : 2;
8194   if (Subtarget.isLittleEndian())
8195     for (int i = 0; i < SaveElts; i++)
8196       ShuffV[i * Stride] = i;
8197   else
8198     for (int i = 1; i <= SaveElts; i++)
8199       ShuffV[i * Stride - 1] = i - 1;
8200 
8201   SDValue ShuffleSrc2 =
8202       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8203   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8204 
8205   SDValue Extend;
8206   if (SignedConv) {
8207     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8208     EVT ExtVT = Op.getOperand(0).getValueType();
8209     if (Subtarget.hasP9Altivec())
8210       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8211                                IntermediateVT.getVectorNumElements());
8212 
8213     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8214                          DAG.getValueType(ExtVT));
8215   } else
8216     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8217 
8218   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8219 }
8220 
8221 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8222                                           SelectionDAG &DAG) const {
8223   SDLoc dl(Op);
8224 
8225   EVT InVT = Op.getOperand(0).getValueType();
8226   EVT OutVT = Op.getValueType();
8227   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8228       isOperationCustom(Op.getOpcode(), InVT))
8229     return LowerINT_TO_FPVector(Op, DAG, dl);
8230 
8231   // Conversions to f128 are legal.
8232   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8233     return Op;
8234 
8235   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8236     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8237       return SDValue();
8238 
8239     SDValue Value = Op.getOperand(0);
8240     // The values are now known to be -1 (false) or 1 (true). To convert this
8241     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8242     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8243     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8244 
8245     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8246 
8247     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8248 
8249     if (Op.getValueType() != MVT::v4f64)
8250       Value = DAG.getNode(ISD::FP_ROUND, dl,
8251                           Op.getValueType(), Value,
8252                           DAG.getIntPtrConstant(1, dl));
8253     return Value;
8254   }
8255 
8256   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8257   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8258     return SDValue();
8259 
8260   if (Op.getOperand(0).getValueType() == MVT::i1)
8261     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8262                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8263                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8264 
8265   // If we have direct moves, we can do all the conversion, skip the store/load
8266   // however, without FPCVT we can't do most conversions.
8267   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8268       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8269     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8270 
8271   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8272          "UINT_TO_FP is supported only with FPCVT");
8273 
8274   // If we have FCFIDS, then use it when converting to single-precision.
8275   // Otherwise, convert to double-precision and then round.
8276   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8277                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8278                                                             : PPCISD::FCFIDS)
8279                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8280                                                             : PPCISD::FCFID);
8281   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8282                   ? MVT::f32
8283                   : MVT::f64;
8284 
8285   if (Op.getOperand(0).getValueType() == MVT::i64) {
8286     SDValue SINT = Op.getOperand(0);
8287     // When converting to single-precision, we actually need to convert
8288     // to double-precision first and then round to single-precision.
8289     // To avoid double-rounding effects during that operation, we have
8290     // to prepare the input operand.  Bits that might be truncated when
8291     // converting to double-precision are replaced by a bit that won't
8292     // be lost at this stage, but is below the single-precision rounding
8293     // position.
8294     //
8295     // However, if -enable-unsafe-fp-math is in effect, accept double
8296     // rounding to avoid the extra overhead.
8297     if (Op.getValueType() == MVT::f32 &&
8298         !Subtarget.hasFPCVT() &&
8299         !DAG.getTarget().Options.UnsafeFPMath) {
8300 
8301       // Twiddle input to make sure the low 11 bits are zero.  (If this
8302       // is the case, we are guaranteed the value will fit into the 53 bit
8303       // mantissa of an IEEE double-precision value without rounding.)
8304       // If any of those low 11 bits were not zero originally, make sure
8305       // bit 12 (value 2048) is set instead, so that the final rounding
8306       // to single-precision gets the correct result.
8307       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8308                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8309       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8310                           Round, DAG.getConstant(2047, dl, MVT::i64));
8311       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8312       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8313                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8314 
8315       // However, we cannot use that value unconditionally: if the magnitude
8316       // of the input value is small, the bit-twiddling we did above might
8317       // end up visibly changing the output.  Fortunately, in that case, we
8318       // don't need to twiddle bits since the original input will convert
8319       // exactly to double-precision floating-point already.  Therefore,
8320       // construct a conditional to use the original value if the top 11
8321       // bits are all sign-bit copies, and use the rounded value computed
8322       // above otherwise.
8323       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8324                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8325       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8326                          Cond, DAG.getConstant(1, dl, MVT::i64));
8327       Cond = DAG.getSetCC(
8328           dl,
8329           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8330           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8331 
8332       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8333     }
8334 
8335     ReuseLoadInfo RLI;
8336     SDValue Bits;
8337 
8338     MachineFunction &MF = DAG.getMachineFunction();
8339     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8340       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8341                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8342       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8343     } else if (Subtarget.hasLFIWAX() &&
8344                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8345       MachineMemOperand *MMO =
8346         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8347                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8348       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8349       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8350                                      DAG.getVTList(MVT::f64, MVT::Other),
8351                                      Ops, MVT::i32, MMO);
8352       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8353     } else if (Subtarget.hasFPCVT() &&
8354                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8355       MachineMemOperand *MMO =
8356         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8357                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8358       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8359       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8360                                      DAG.getVTList(MVT::f64, MVT::Other),
8361                                      Ops, MVT::i32, MMO);
8362       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8363     } else if (((Subtarget.hasLFIWAX() &&
8364                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8365                 (Subtarget.hasFPCVT() &&
8366                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8367                SINT.getOperand(0).getValueType() == MVT::i32) {
8368       MachineFrameInfo &MFI = MF.getFrameInfo();
8369       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8370 
8371       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8372       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8373 
8374       SDValue Store =
8375           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8376                        MachinePointerInfo::getFixedStack(
8377                            DAG.getMachineFunction(), FrameIdx));
8378 
8379       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8380              "Expected an i32 store");
8381 
8382       RLI.Ptr = FIdx;
8383       RLI.Chain = Store;
8384       RLI.MPI =
8385           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8386       RLI.Alignment = 4;
8387 
8388       MachineMemOperand *MMO =
8389         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8390                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8391       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8392       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8393                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8394                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8395                                      Ops, MVT::i32, MMO);
8396     } else
8397       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8398 
8399     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8400 
8401     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8402       FP = DAG.getNode(ISD::FP_ROUND, dl,
8403                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8404     return FP;
8405   }
8406 
8407   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8408          "Unhandled INT_TO_FP type in custom expander!");
8409   // Since we only generate this in 64-bit mode, we can take advantage of
8410   // 64-bit registers.  In particular, sign extend the input value into the
8411   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8412   // then lfd it and fcfid it.
8413   MachineFunction &MF = DAG.getMachineFunction();
8414   MachineFrameInfo &MFI = MF.getFrameInfo();
8415   EVT PtrVT = getPointerTy(MF.getDataLayout());
8416 
8417   SDValue Ld;
8418   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8419     ReuseLoadInfo RLI;
8420     bool ReusingLoad;
8421     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8422                                             DAG))) {
8423       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8424       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8425 
8426       SDValue Store =
8427           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8428                        MachinePointerInfo::getFixedStack(
8429                            DAG.getMachineFunction(), FrameIdx));
8430 
8431       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8432              "Expected an i32 store");
8433 
8434       RLI.Ptr = FIdx;
8435       RLI.Chain = Store;
8436       RLI.MPI =
8437           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8438       RLI.Alignment = 4;
8439     }
8440 
8441     MachineMemOperand *MMO =
8442       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8443                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8444     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8445     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8446                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8447                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8448                                  Ops, MVT::i32, MMO);
8449     if (ReusingLoad)
8450       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8451   } else {
8452     assert(Subtarget.isPPC64() &&
8453            "i32->FP without LFIWAX supported only on PPC64");
8454 
8455     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8456     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8457 
8458     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8459                                 Op.getOperand(0));
8460 
8461     // STD the extended value into the stack slot.
8462     SDValue Store = DAG.getStore(
8463         DAG.getEntryNode(), dl, Ext64, FIdx,
8464         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8465 
8466     // Load the value as a double.
8467     Ld = DAG.getLoad(
8468         MVT::f64, dl, Store, FIdx,
8469         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8470   }
8471 
8472   // FCFID it and return it.
8473   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8474   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8475     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8476                      DAG.getIntPtrConstant(0, dl));
8477   return FP;
8478 }
8479 
8480 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8481                                             SelectionDAG &DAG) const {
8482   SDLoc dl(Op);
8483   /*
8484    The rounding mode is in bits 30:31 of FPSR, and has the following
8485    settings:
8486      00 Round to nearest
8487      01 Round to 0
8488      10 Round to +inf
8489      11 Round to -inf
8490 
8491   FLT_ROUNDS, on the other hand, expects the following:
8492     -1 Undefined
8493      0 Round to 0
8494      1 Round to nearest
8495      2 Round to +inf
8496      3 Round to -inf
8497 
8498   To perform the conversion, we do:
8499     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8500   */
8501 
8502   MachineFunction &MF = DAG.getMachineFunction();
8503   EVT VT = Op.getValueType();
8504   EVT PtrVT = getPointerTy(MF.getDataLayout());
8505 
8506   // Save FP Control Word to register
8507   SDValue Chain = Op.getOperand(0);
8508   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8509   Chain = MFFS.getValue(1);
8510 
8511   // Save FP register to stack slot
8512   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8513   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8514   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8515 
8516   // Load FP Control Word from low 32 bits of stack slot.
8517   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8518   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8519   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8520   Chain = CWD.getValue(1);
8521 
8522   // Transform as necessary
8523   SDValue CWD1 =
8524     DAG.getNode(ISD::AND, dl, MVT::i32,
8525                 CWD, DAG.getConstant(3, dl, MVT::i32));
8526   SDValue CWD2 =
8527     DAG.getNode(ISD::SRL, dl, MVT::i32,
8528                 DAG.getNode(ISD::AND, dl, MVT::i32,
8529                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8530                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8531                             DAG.getConstant(3, dl, MVT::i32)),
8532                 DAG.getConstant(1, dl, MVT::i32));
8533 
8534   SDValue RetVal =
8535     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8536 
8537   RetVal =
8538       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8539                   dl, VT, RetVal);
8540 
8541   return DAG.getMergeValues({RetVal, Chain}, dl);
8542 }
8543 
8544 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8545   EVT VT = Op.getValueType();
8546   unsigned BitWidth = VT.getSizeInBits();
8547   SDLoc dl(Op);
8548   assert(Op.getNumOperands() == 3 &&
8549          VT == Op.getOperand(1).getValueType() &&
8550          "Unexpected SHL!");
8551 
8552   // Expand into a bunch of logical ops.  Note that these ops
8553   // depend on the PPC behavior for oversized shift amounts.
8554   SDValue Lo = Op.getOperand(0);
8555   SDValue Hi = Op.getOperand(1);
8556   SDValue Amt = Op.getOperand(2);
8557   EVT AmtVT = Amt.getValueType();
8558 
8559   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8560                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8561   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8562   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8563   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8564   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8565                              DAG.getConstant(-BitWidth, dl, AmtVT));
8566   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8567   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8568   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8569   SDValue OutOps[] = { OutLo, OutHi };
8570   return DAG.getMergeValues(OutOps, dl);
8571 }
8572 
8573 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8574   EVT VT = Op.getValueType();
8575   SDLoc dl(Op);
8576   unsigned BitWidth = VT.getSizeInBits();
8577   assert(Op.getNumOperands() == 3 &&
8578          VT == Op.getOperand(1).getValueType() &&
8579          "Unexpected SRL!");
8580 
8581   // Expand into a bunch of logical ops.  Note that these ops
8582   // depend on the PPC behavior for oversized shift amounts.
8583   SDValue Lo = Op.getOperand(0);
8584   SDValue Hi = Op.getOperand(1);
8585   SDValue Amt = Op.getOperand(2);
8586   EVT AmtVT = Amt.getValueType();
8587 
8588   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8589                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8590   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8591   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8592   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8593   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8594                              DAG.getConstant(-BitWidth, dl, AmtVT));
8595   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8596   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8597   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8598   SDValue OutOps[] = { OutLo, OutHi };
8599   return DAG.getMergeValues(OutOps, dl);
8600 }
8601 
8602 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8603   SDLoc dl(Op);
8604   EVT VT = Op.getValueType();
8605   unsigned BitWidth = VT.getSizeInBits();
8606   assert(Op.getNumOperands() == 3 &&
8607          VT == Op.getOperand(1).getValueType() &&
8608          "Unexpected SRA!");
8609 
8610   // Expand into a bunch of logical ops, followed by a select_cc.
8611   SDValue Lo = Op.getOperand(0);
8612   SDValue Hi = Op.getOperand(1);
8613   SDValue Amt = Op.getOperand(2);
8614   EVT AmtVT = Amt.getValueType();
8615 
8616   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8617                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8618   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8619   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8620   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8621   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8622                              DAG.getConstant(-BitWidth, dl, AmtVT));
8623   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8624   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8625   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8626                                   Tmp4, Tmp6, ISD::SETLE);
8627   SDValue OutOps[] = { OutLo, OutHi };
8628   return DAG.getMergeValues(OutOps, dl);
8629 }
8630 
8631 //===----------------------------------------------------------------------===//
8632 // Vector related lowering.
8633 //
8634 
8635 /// BuildSplatI - Build a canonical splati of Val with an element size of
8636 /// SplatSize.  Cast the result to VT.
8637 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8638                            SelectionDAG &DAG, const SDLoc &dl) {
8639   static const MVT VTys[] = { // canonical VT to use for each size.
8640     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8641   };
8642 
8643   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8644 
8645   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8646   if (Val == -1)
8647     SplatSize = 1;
8648 
8649   EVT CanonicalVT = VTys[SplatSize-1];
8650 
8651   // Build a canonical splat for this value.
8652   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8653 }
8654 
8655 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8656 /// specified intrinsic ID.
8657 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8658                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8659   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8660   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8661                      DAG.getConstant(IID, dl, MVT::i32), Op);
8662 }
8663 
8664 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8665 /// specified intrinsic ID.
8666 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8667                                 SelectionDAG &DAG, const SDLoc &dl,
8668                                 EVT DestVT = MVT::Other) {
8669   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8670   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8671                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8672 }
8673 
8674 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8675 /// specified intrinsic ID.
8676 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8677                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8678                                 EVT DestVT = MVT::Other) {
8679   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8680   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8681                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8682 }
8683 
8684 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8685 /// amount.  The result has the specified value type.
8686 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8687                            SelectionDAG &DAG, const SDLoc &dl) {
8688   // Force LHS/RHS to be the right type.
8689   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8690   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8691 
8692   int Ops[16];
8693   for (unsigned i = 0; i != 16; ++i)
8694     Ops[i] = i + Amt;
8695   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8696   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8697 }
8698 
8699 /// Do we have an efficient pattern in a .td file for this node?
8700 ///
8701 /// \param V - pointer to the BuildVectorSDNode being matched
8702 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8703 ///
8704 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8705 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8706 /// the opposite is true (expansion is beneficial) are:
8707 /// - The node builds a vector out of integers that are not 32 or 64-bits
8708 /// - The node builds a vector out of constants
8709 /// - The node is a "load-and-splat"
8710 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8711 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8712                                             bool HasDirectMove,
8713                                             bool HasP8Vector) {
8714   EVT VecVT = V->getValueType(0);
8715   bool RightType = VecVT == MVT::v2f64 ||
8716     (HasP8Vector && VecVT == MVT::v4f32) ||
8717     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8718   if (!RightType)
8719     return false;
8720 
8721   bool IsSplat = true;
8722   bool IsLoad = false;
8723   SDValue Op0 = V->getOperand(0);
8724 
8725   // This function is called in a block that confirms the node is not a constant
8726   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8727   // different constants.
8728   if (V->isConstant())
8729     return false;
8730   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8731     if (V->getOperand(i).isUndef())
8732       return false;
8733     // We want to expand nodes that represent load-and-splat even if the
8734     // loaded value is a floating point truncation or conversion to int.
8735     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8736         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8737          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8738         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8739          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8740         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8741          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8742       IsLoad = true;
8743     // If the operands are different or the input is not a load and has more
8744     // uses than just this BV node, then it isn't a splat.
8745     if (V->getOperand(i) != Op0 ||
8746         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8747       IsSplat = false;
8748   }
8749   return !(IsSplat && IsLoad);
8750 }
8751 
8752 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8753 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8754 
8755   SDLoc dl(Op);
8756   SDValue Op0 = Op->getOperand(0);
8757 
8758   if (!EnableQuadPrecision ||
8759       (Op.getValueType() != MVT::f128 ) ||
8760       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8761       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8762       (Op0.getOperand(1).getValueType() != MVT::i64))
8763     return SDValue();
8764 
8765   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8766                      Op0.getOperand(1));
8767 }
8768 
8769 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8770   const SDValue *InputLoad = &Op;
8771   if (InputLoad->getOpcode() == ISD::BITCAST)
8772     InputLoad = &InputLoad->getOperand(0);
8773   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8774     InputLoad = &InputLoad->getOperand(0);
8775   if (InputLoad->getOpcode() != ISD::LOAD)
8776     return nullptr;
8777   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8778   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8779 }
8780 
8781 // If this is a case we can't handle, return null and let the default
8782 // expansion code take care of it.  If we CAN select this case, and if it
8783 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8784 // this case more efficiently than a constant pool load, lower it to the
8785 // sequence of ops that should be used.
8786 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8787                                              SelectionDAG &DAG) const {
8788   SDLoc dl(Op);
8789   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8790   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8791 
8792   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8793     // We first build an i32 vector, load it into a QPX register,
8794     // then convert it to a floating-point vector and compare it
8795     // to a zero vector to get the boolean result.
8796     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8797     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8798     MachinePointerInfo PtrInfo =
8799         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8800     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8801     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8802 
8803     assert(BVN->getNumOperands() == 4 &&
8804       "BUILD_VECTOR for v4i1 does not have 4 operands");
8805 
8806     bool IsConst = true;
8807     for (unsigned i = 0; i < 4; ++i) {
8808       if (BVN->getOperand(i).isUndef()) continue;
8809       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8810         IsConst = false;
8811         break;
8812       }
8813     }
8814 
8815     if (IsConst) {
8816       Constant *One =
8817         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8818       Constant *NegOne =
8819         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8820 
8821       Constant *CV[4];
8822       for (unsigned i = 0; i < 4; ++i) {
8823         if (BVN->getOperand(i).isUndef())
8824           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8825         else if (isNullConstant(BVN->getOperand(i)))
8826           CV[i] = NegOne;
8827         else
8828           CV[i] = One;
8829       }
8830 
8831       Constant *CP = ConstantVector::get(CV);
8832       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8833                                           16 /* alignment */);
8834 
8835       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8836       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8837       return DAG.getMemIntrinsicNode(
8838           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8839           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8840     }
8841 
8842     SmallVector<SDValue, 4> Stores;
8843     for (unsigned i = 0; i < 4; ++i) {
8844       if (BVN->getOperand(i).isUndef()) continue;
8845 
8846       unsigned Offset = 4*i;
8847       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8848       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8849 
8850       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8851       if (StoreSize > 4) {
8852         Stores.push_back(
8853             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8854                               PtrInfo.getWithOffset(Offset), MVT::i32));
8855       } else {
8856         SDValue StoreValue = BVN->getOperand(i);
8857         if (StoreSize < 4)
8858           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8859 
8860         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8861                                       PtrInfo.getWithOffset(Offset)));
8862       }
8863     }
8864 
8865     SDValue StoreChain;
8866     if (!Stores.empty())
8867       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8868     else
8869       StoreChain = DAG.getEntryNode();
8870 
8871     // Now load from v4i32 into the QPX register; this will extend it to
8872     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8873     // is typed as v4f64 because the QPX register integer states are not
8874     // explicitly represented.
8875 
8876     SDValue Ops[] = {StoreChain,
8877                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8878                      FIdx};
8879     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8880 
8881     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8882       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8883     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8884       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8885       LoadedVect);
8886 
8887     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8888 
8889     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8890   }
8891 
8892   // All other QPX vectors are handled by generic code.
8893   if (Subtarget.hasQPX())
8894     return SDValue();
8895 
8896   // Check if this is a splat of a constant value.
8897   APInt APSplatBits, APSplatUndef;
8898   unsigned SplatBitSize;
8899   bool HasAnyUndefs;
8900   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8901                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8902       SplatBitSize > 32) {
8903 
8904     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8905     // Handle load-and-splat patterns as we have instructions that will do this
8906     // in one go.
8907     if (InputLoad && DAG.isSplatValue(Op, true)) {
8908       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8909 
8910       // We have handling for 4 and 8 byte elements.
8911       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8912 
8913       // Checking for a single use of this load, we have to check for vector
8914       // width (128 bits) / ElementSize uses (since each operand of the
8915       // BUILD_VECTOR is a separate use of the value.
8916       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8917           ((Subtarget.hasVSX() && ElementSize == 64) ||
8918            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8919         SDValue Ops[] = {
8920           LD->getChain(),    // Chain
8921           LD->getBasePtr(),  // Ptr
8922           DAG.getValueType(Op.getValueType()) // VT
8923         };
8924         return
8925           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8926                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8927                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8928       }
8929     }
8930 
8931     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8932     // lowered to VSX instructions under certain conditions.
8933     // Without VSX, there is no pattern more efficient than expanding the node.
8934     if (Subtarget.hasVSX() &&
8935         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8936                                         Subtarget.hasP8Vector()))
8937       return Op;
8938     return SDValue();
8939   }
8940 
8941   unsigned SplatBits = APSplatBits.getZExtValue();
8942   unsigned SplatUndef = APSplatUndef.getZExtValue();
8943   unsigned SplatSize = SplatBitSize / 8;
8944 
8945   // First, handle single instruction cases.
8946 
8947   // All zeros?
8948   if (SplatBits == 0) {
8949     // Canonicalize all zero vectors to be v4i32.
8950     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8951       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8952       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8953     }
8954     return Op;
8955   }
8956 
8957   // We have XXSPLTIB for constant splats one byte wide
8958   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
8959   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
8960   if (Subtarget.hasP9Vector() && SplatSize == 1)
8961     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
8962 
8963   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8964   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8965                     (32-SplatBitSize));
8966   if (SextVal >= -16 && SextVal <= 15)
8967     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8968 
8969   // Two instruction sequences.
8970 
8971   // If this value is in the range [-32,30] and is even, use:
8972   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8973   // If this value is in the range [17,31] and is odd, use:
8974   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8975   // If this value is in the range [-31,-17] and is odd, use:
8976   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8977   // Note the last two are three-instruction sequences.
8978   if (SextVal >= -32 && SextVal <= 31) {
8979     // To avoid having these optimizations undone by constant folding,
8980     // we convert to a pseudo that will be expanded later into one of
8981     // the above forms.
8982     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8983     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8984               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8985     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8986     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8987     if (VT == Op.getValueType())
8988       return RetVal;
8989     else
8990       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8991   }
8992 
8993   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8994   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8995   // for fneg/fabs.
8996   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8997     // Make -1 and vspltisw -1:
8998     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8999 
9000     // Make the VSLW intrinsic, computing 0x8000_0000.
9001     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9002                                    OnesV, DAG, dl);
9003 
9004     // xor by OnesV to invert it.
9005     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9006     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9007   }
9008 
9009   // Check to see if this is a wide variety of vsplti*, binop self cases.
9010   static const signed char SplatCsts[] = {
9011     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9012     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9013   };
9014 
9015   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9016     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9017     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9018     int i = SplatCsts[idx];
9019 
9020     // Figure out what shift amount will be used by altivec if shifted by i in
9021     // this splat size.
9022     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9023 
9024     // vsplti + shl self.
9025     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9026       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9027       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9028         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9029         Intrinsic::ppc_altivec_vslw
9030       };
9031       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9032       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9033     }
9034 
9035     // vsplti + srl self.
9036     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9037       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9038       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9039         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9040         Intrinsic::ppc_altivec_vsrw
9041       };
9042       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9043       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9044     }
9045 
9046     // vsplti + sra self.
9047     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9048       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9049       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9050         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9051         Intrinsic::ppc_altivec_vsraw
9052       };
9053       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9054       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9055     }
9056 
9057     // vsplti + rol self.
9058     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9059                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9060       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9061       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9062         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9063         Intrinsic::ppc_altivec_vrlw
9064       };
9065       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9066       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9067     }
9068 
9069     // t = vsplti c, result = vsldoi t, t, 1
9070     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9071       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9072       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9073       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9074     }
9075     // t = vsplti c, result = vsldoi t, t, 2
9076     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9077       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9078       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9079       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9080     }
9081     // t = vsplti c, result = vsldoi t, t, 3
9082     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9083       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9084       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9085       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9086     }
9087   }
9088 
9089   return SDValue();
9090 }
9091 
9092 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9093 /// the specified operations to build the shuffle.
9094 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9095                                       SDValue RHS, SelectionDAG &DAG,
9096                                       const SDLoc &dl) {
9097   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9098   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9099   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9100 
9101   enum {
9102     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9103     OP_VMRGHW,
9104     OP_VMRGLW,
9105     OP_VSPLTISW0,
9106     OP_VSPLTISW1,
9107     OP_VSPLTISW2,
9108     OP_VSPLTISW3,
9109     OP_VSLDOI4,
9110     OP_VSLDOI8,
9111     OP_VSLDOI12
9112   };
9113 
9114   if (OpNum == OP_COPY) {
9115     if (LHSID == (1*9+2)*9+3) return LHS;
9116     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9117     return RHS;
9118   }
9119 
9120   SDValue OpLHS, OpRHS;
9121   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9122   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9123 
9124   int ShufIdxs[16];
9125   switch (OpNum) {
9126   default: llvm_unreachable("Unknown i32 permute!");
9127   case OP_VMRGHW:
9128     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9129     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9130     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9131     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9132     break;
9133   case OP_VMRGLW:
9134     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9135     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9136     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9137     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9138     break;
9139   case OP_VSPLTISW0:
9140     for (unsigned i = 0; i != 16; ++i)
9141       ShufIdxs[i] = (i&3)+0;
9142     break;
9143   case OP_VSPLTISW1:
9144     for (unsigned i = 0; i != 16; ++i)
9145       ShufIdxs[i] = (i&3)+4;
9146     break;
9147   case OP_VSPLTISW2:
9148     for (unsigned i = 0; i != 16; ++i)
9149       ShufIdxs[i] = (i&3)+8;
9150     break;
9151   case OP_VSPLTISW3:
9152     for (unsigned i = 0; i != 16; ++i)
9153       ShufIdxs[i] = (i&3)+12;
9154     break;
9155   case OP_VSLDOI4:
9156     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9157   case OP_VSLDOI8:
9158     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9159   case OP_VSLDOI12:
9160     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9161   }
9162   EVT VT = OpLHS.getValueType();
9163   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9164   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9165   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9166   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9167 }
9168 
9169 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9170 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9171 /// SDValue.
9172 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9173                                            SelectionDAG &DAG) const {
9174   const unsigned BytesInVector = 16;
9175   bool IsLE = Subtarget.isLittleEndian();
9176   SDLoc dl(N);
9177   SDValue V1 = N->getOperand(0);
9178   SDValue V2 = N->getOperand(1);
9179   unsigned ShiftElts = 0, InsertAtByte = 0;
9180   bool Swap = false;
9181 
9182   // Shifts required to get the byte we want at element 7.
9183   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9184                                    0, 15, 14, 13, 12, 11, 10, 9};
9185   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9186                                 1, 2,  3,  4,  5,  6,  7,  8};
9187 
9188   ArrayRef<int> Mask = N->getMask();
9189   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9190 
9191   // For each mask element, find out if we're just inserting something
9192   // from V2 into V1 or vice versa.
9193   // Possible permutations inserting an element from V2 into V1:
9194   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9195   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9196   //   ...
9197   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9198   // Inserting from V1 into V2 will be similar, except mask range will be
9199   // [16,31].
9200 
9201   bool FoundCandidate = false;
9202   // If both vector operands for the shuffle are the same vector, the mask
9203   // will contain only elements from the first one and the second one will be
9204   // undef.
9205   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9206   // Go through the mask of half-words to find an element that's being moved
9207   // from one vector to the other.
9208   for (unsigned i = 0; i < BytesInVector; ++i) {
9209     unsigned CurrentElement = Mask[i];
9210     // If 2nd operand is undefined, we should only look for element 7 in the
9211     // Mask.
9212     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9213       continue;
9214 
9215     bool OtherElementsInOrder = true;
9216     // Examine the other elements in the Mask to see if they're in original
9217     // order.
9218     for (unsigned j = 0; j < BytesInVector; ++j) {
9219       if (j == i)
9220         continue;
9221       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9222       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9223       // in which we always assume we're always picking from the 1st operand.
9224       int MaskOffset =
9225           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9226       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9227         OtherElementsInOrder = false;
9228         break;
9229       }
9230     }
9231     // If other elements are in original order, we record the number of shifts
9232     // we need to get the element we want into element 7. Also record which byte
9233     // in the vector we should insert into.
9234     if (OtherElementsInOrder) {
9235       // If 2nd operand is undefined, we assume no shifts and no swapping.
9236       if (V2.isUndef()) {
9237         ShiftElts = 0;
9238         Swap = false;
9239       } else {
9240         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9241         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9242                          : BigEndianShifts[CurrentElement & 0xF];
9243         Swap = CurrentElement < BytesInVector;
9244       }
9245       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9246       FoundCandidate = true;
9247       break;
9248     }
9249   }
9250 
9251   if (!FoundCandidate)
9252     return SDValue();
9253 
9254   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9255   // optionally with VECSHL if shift is required.
9256   if (Swap)
9257     std::swap(V1, V2);
9258   if (V2.isUndef())
9259     V2 = V1;
9260   if (ShiftElts) {
9261     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9262                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9263     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9264                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9265   }
9266   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9267                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9268 }
9269 
9270 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9271 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9272 /// SDValue.
9273 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9274                                            SelectionDAG &DAG) const {
9275   const unsigned NumHalfWords = 8;
9276   const unsigned BytesInVector = NumHalfWords * 2;
9277   // Check that the shuffle is on half-words.
9278   if (!isNByteElemShuffleMask(N, 2, 1))
9279     return SDValue();
9280 
9281   bool IsLE = Subtarget.isLittleEndian();
9282   SDLoc dl(N);
9283   SDValue V1 = N->getOperand(0);
9284   SDValue V2 = N->getOperand(1);
9285   unsigned ShiftElts = 0, InsertAtByte = 0;
9286   bool Swap = false;
9287 
9288   // Shifts required to get the half-word we want at element 3.
9289   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9290   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9291 
9292   uint32_t Mask = 0;
9293   uint32_t OriginalOrderLow = 0x1234567;
9294   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9295   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9296   // 32-bit space, only need 4-bit nibbles per element.
9297   for (unsigned i = 0; i < NumHalfWords; ++i) {
9298     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9299     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9300   }
9301 
9302   // For each mask element, find out if we're just inserting something
9303   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9304   // from V2 into V1:
9305   //   X, 1, 2, 3, 4, 5, 6, 7
9306   //   0, X, 2, 3, 4, 5, 6, 7
9307   //   0, 1, X, 3, 4, 5, 6, 7
9308   //   0, 1, 2, X, 4, 5, 6, 7
9309   //   0, 1, 2, 3, X, 5, 6, 7
9310   //   0, 1, 2, 3, 4, X, 6, 7
9311   //   0, 1, 2, 3, 4, 5, X, 7
9312   //   0, 1, 2, 3, 4, 5, 6, X
9313   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9314 
9315   bool FoundCandidate = false;
9316   // Go through the mask of half-words to find an element that's being moved
9317   // from one vector to the other.
9318   for (unsigned i = 0; i < NumHalfWords; ++i) {
9319     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9320     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9321     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9322     uint32_t TargetOrder = 0x0;
9323 
9324     // If both vector operands for the shuffle are the same vector, the mask
9325     // will contain only elements from the first one and the second one will be
9326     // undef.
9327     if (V2.isUndef()) {
9328       ShiftElts = 0;
9329       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9330       TargetOrder = OriginalOrderLow;
9331       Swap = false;
9332       // Skip if not the correct element or mask of other elements don't equal
9333       // to our expected order.
9334       if (MaskOneElt == VINSERTHSrcElem &&
9335           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9336         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9337         FoundCandidate = true;
9338         break;
9339       }
9340     } else { // If both operands are defined.
9341       // Target order is [8,15] if the current mask is between [0,7].
9342       TargetOrder =
9343           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9344       // Skip if mask of other elements don't equal our expected order.
9345       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9346         // We only need the last 3 bits for the number of shifts.
9347         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9348                          : BigEndianShifts[MaskOneElt & 0x7];
9349         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9350         Swap = MaskOneElt < NumHalfWords;
9351         FoundCandidate = true;
9352         break;
9353       }
9354     }
9355   }
9356 
9357   if (!FoundCandidate)
9358     return SDValue();
9359 
9360   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9361   // optionally with VECSHL if shift is required.
9362   if (Swap)
9363     std::swap(V1, V2);
9364   if (V2.isUndef())
9365     V2 = V1;
9366   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9367   if (ShiftElts) {
9368     // Double ShiftElts because we're left shifting on v16i8 type.
9369     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9370                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9371     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9372     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9373                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9374     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9375   }
9376   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9377   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9378                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9379   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9380 }
9381 
9382 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9383 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9384 /// return the code it can be lowered into.  Worst case, it can always be
9385 /// lowered into a vperm.
9386 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9387                                                SelectionDAG &DAG) const {
9388   SDLoc dl(Op);
9389   SDValue V1 = Op.getOperand(0);
9390   SDValue V2 = Op.getOperand(1);
9391   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9392   EVT VT = Op.getValueType();
9393   bool isLittleEndian = Subtarget.isLittleEndian();
9394 
9395   unsigned ShiftElts, InsertAtByte;
9396   bool Swap = false;
9397 
9398   // If this is a load-and-splat, we can do that with a single instruction
9399   // in some cases. However if the load has multiple uses, we don't want to
9400   // combine it because that will just produce multiple loads.
9401   const SDValue *InputLoad = getNormalLoadInput(V1);
9402   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9403       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9404       InputLoad->hasOneUse()) {
9405     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9406     int SplatIdx =
9407       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9408 
9409     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9410     // For 4-byte load-and-splat, we need Power9.
9411     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9412       uint64_t Offset = 0;
9413       if (IsFourByte)
9414         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9415       else
9416         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9417       SDValue BasePtr = LD->getBasePtr();
9418       if (Offset != 0)
9419         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9420                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9421       SDValue Ops[] = {
9422         LD->getChain(),    // Chain
9423         BasePtr,           // BasePtr
9424         DAG.getValueType(Op.getValueType()) // VT
9425       };
9426       SDVTList VTL =
9427         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9428       SDValue LdSplt =
9429         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9430                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9431       if (LdSplt.getValueType() != SVOp->getValueType(0))
9432         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9433       return LdSplt;
9434     }
9435   }
9436   if (Subtarget.hasP9Vector() &&
9437       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9438                            isLittleEndian)) {
9439     if (Swap)
9440       std::swap(V1, V2);
9441     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9442     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9443     if (ShiftElts) {
9444       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9445                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9446       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9447                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9448       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9449     }
9450     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9451                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9452     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9453   }
9454 
9455   if (Subtarget.hasP9Altivec()) {
9456     SDValue NewISDNode;
9457     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9458       return NewISDNode;
9459 
9460     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9461       return NewISDNode;
9462   }
9463 
9464   if (Subtarget.hasVSX() &&
9465       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9466     if (Swap)
9467       std::swap(V1, V2);
9468     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9469     SDValue Conv2 =
9470         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9471 
9472     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9473                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9474     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9475   }
9476 
9477   if (Subtarget.hasVSX() &&
9478     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9479     if (Swap)
9480       std::swap(V1, V2);
9481     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9482     SDValue Conv2 =
9483         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9484 
9485     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9486                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9487     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9488   }
9489 
9490   if (Subtarget.hasP9Vector()) {
9491      if (PPC::isXXBRHShuffleMask(SVOp)) {
9492       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9493       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9494       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9495     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9496       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9497       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9498       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9499     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9500       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9501       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9502       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9503     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9504       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9505       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9506       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9507     }
9508   }
9509 
9510   if (Subtarget.hasVSX()) {
9511     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9512       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9513 
9514       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9515       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9516                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9517       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9518     }
9519 
9520     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9521     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9522       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9523       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9524       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9525     }
9526   }
9527 
9528   if (Subtarget.hasQPX()) {
9529     if (VT.getVectorNumElements() != 4)
9530       return SDValue();
9531 
9532     if (V2.isUndef()) V2 = V1;
9533 
9534     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9535     if (AlignIdx != -1) {
9536       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9537                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9538     } else if (SVOp->isSplat()) {
9539       int SplatIdx = SVOp->getSplatIndex();
9540       if (SplatIdx >= 4) {
9541         std::swap(V1, V2);
9542         SplatIdx -= 4;
9543       }
9544 
9545       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9546                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9547     }
9548 
9549     // Lower this into a qvgpci/qvfperm pair.
9550 
9551     // Compute the qvgpci literal
9552     unsigned idx = 0;
9553     for (unsigned i = 0; i < 4; ++i) {
9554       int m = SVOp->getMaskElt(i);
9555       unsigned mm = m >= 0 ? (unsigned) m : i;
9556       idx |= mm << (3-i)*3;
9557     }
9558 
9559     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9560                              DAG.getConstant(idx, dl, MVT::i32));
9561     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9562   }
9563 
9564   // Cases that are handled by instructions that take permute immediates
9565   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9566   // selected by the instruction selector.
9567   if (V2.isUndef()) {
9568     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9569         PPC::isSplatShuffleMask(SVOp, 2) ||
9570         PPC::isSplatShuffleMask(SVOp, 4) ||
9571         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9572         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9573         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9574         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9575         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9576         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9577         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9578         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9579         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9580         (Subtarget.hasP8Altivec() && (
9581          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9582          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9583          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9584       return Op;
9585     }
9586   }
9587 
9588   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9589   // and produce a fixed permutation.  If any of these match, do not lower to
9590   // VPERM.
9591   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9592   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9593       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9594       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9595       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9596       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9597       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9598       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9599       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9600       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9601       (Subtarget.hasP8Altivec() && (
9602        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9603        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9604        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9605     return Op;
9606 
9607   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9608   // perfect shuffle table to emit an optimal matching sequence.
9609   ArrayRef<int> PermMask = SVOp->getMask();
9610 
9611   unsigned PFIndexes[4];
9612   bool isFourElementShuffle = true;
9613   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9614     unsigned EltNo = 8;   // Start out undef.
9615     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9616       if (PermMask[i*4+j] < 0)
9617         continue;   // Undef, ignore it.
9618 
9619       unsigned ByteSource = PermMask[i*4+j];
9620       if ((ByteSource & 3) != j) {
9621         isFourElementShuffle = false;
9622         break;
9623       }
9624 
9625       if (EltNo == 8) {
9626         EltNo = ByteSource/4;
9627       } else if (EltNo != ByteSource/4) {
9628         isFourElementShuffle = false;
9629         break;
9630       }
9631     }
9632     PFIndexes[i] = EltNo;
9633   }
9634 
9635   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9636   // perfect shuffle vector to determine if it is cost effective to do this as
9637   // discrete instructions, or whether we should use a vperm.
9638   // For now, we skip this for little endian until such time as we have a
9639   // little-endian perfect shuffle table.
9640   if (isFourElementShuffle && !isLittleEndian) {
9641     // Compute the index in the perfect shuffle table.
9642     unsigned PFTableIndex =
9643       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9644 
9645     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9646     unsigned Cost  = (PFEntry >> 30);
9647 
9648     // Determining when to avoid vperm is tricky.  Many things affect the cost
9649     // of vperm, particularly how many times the perm mask needs to be computed.
9650     // For example, if the perm mask can be hoisted out of a loop or is already
9651     // used (perhaps because there are multiple permutes with the same shuffle
9652     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9653     // the loop requires an extra register.
9654     //
9655     // As a compromise, we only emit discrete instructions if the shuffle can be
9656     // generated in 3 or fewer operations.  When we have loop information
9657     // available, if this block is within a loop, we should avoid using vperm
9658     // for 3-operation perms and use a constant pool load instead.
9659     if (Cost < 3)
9660       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9661   }
9662 
9663   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9664   // vector that will get spilled to the constant pool.
9665   if (V2.isUndef()) V2 = V1;
9666 
9667   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9668   // that it is in input element units, not in bytes.  Convert now.
9669 
9670   // For little endian, the order of the input vectors is reversed, and
9671   // the permutation mask is complemented with respect to 31.  This is
9672   // necessary to produce proper semantics with the big-endian-biased vperm
9673   // instruction.
9674   EVT EltVT = V1.getValueType().getVectorElementType();
9675   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9676 
9677   SmallVector<SDValue, 16> ResultMask;
9678   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9679     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9680 
9681     for (unsigned j = 0; j != BytesPerElement; ++j)
9682       if (isLittleEndian)
9683         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9684                                              dl, MVT::i32));
9685       else
9686         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9687                                              MVT::i32));
9688   }
9689 
9690   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9691   if (isLittleEndian)
9692     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9693                        V2, V1, VPermMask);
9694   else
9695     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9696                        V1, V2, VPermMask);
9697 }
9698 
9699 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9700 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9701 /// information about the intrinsic.
9702 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9703                                  bool &isDot, const PPCSubtarget &Subtarget) {
9704   unsigned IntrinsicID =
9705       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9706   CompareOpc = -1;
9707   isDot = false;
9708   switch (IntrinsicID) {
9709   default:
9710     return false;
9711   // Comparison predicates.
9712   case Intrinsic::ppc_altivec_vcmpbfp_p:
9713     CompareOpc = 966;
9714     isDot = true;
9715     break;
9716   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9717     CompareOpc = 198;
9718     isDot = true;
9719     break;
9720   case Intrinsic::ppc_altivec_vcmpequb_p:
9721     CompareOpc = 6;
9722     isDot = true;
9723     break;
9724   case Intrinsic::ppc_altivec_vcmpequh_p:
9725     CompareOpc = 70;
9726     isDot = true;
9727     break;
9728   case Intrinsic::ppc_altivec_vcmpequw_p:
9729     CompareOpc = 134;
9730     isDot = true;
9731     break;
9732   case Intrinsic::ppc_altivec_vcmpequd_p:
9733     if (Subtarget.hasP8Altivec()) {
9734       CompareOpc = 199;
9735       isDot = true;
9736     } else
9737       return false;
9738     break;
9739   case Intrinsic::ppc_altivec_vcmpneb_p:
9740   case Intrinsic::ppc_altivec_vcmpneh_p:
9741   case Intrinsic::ppc_altivec_vcmpnew_p:
9742   case Intrinsic::ppc_altivec_vcmpnezb_p:
9743   case Intrinsic::ppc_altivec_vcmpnezh_p:
9744   case Intrinsic::ppc_altivec_vcmpnezw_p:
9745     if (Subtarget.hasP9Altivec()) {
9746       switch (IntrinsicID) {
9747       default:
9748         llvm_unreachable("Unknown comparison intrinsic.");
9749       case Intrinsic::ppc_altivec_vcmpneb_p:
9750         CompareOpc = 7;
9751         break;
9752       case Intrinsic::ppc_altivec_vcmpneh_p:
9753         CompareOpc = 71;
9754         break;
9755       case Intrinsic::ppc_altivec_vcmpnew_p:
9756         CompareOpc = 135;
9757         break;
9758       case Intrinsic::ppc_altivec_vcmpnezb_p:
9759         CompareOpc = 263;
9760         break;
9761       case Intrinsic::ppc_altivec_vcmpnezh_p:
9762         CompareOpc = 327;
9763         break;
9764       case Intrinsic::ppc_altivec_vcmpnezw_p:
9765         CompareOpc = 391;
9766         break;
9767       }
9768       isDot = true;
9769     } else
9770       return false;
9771     break;
9772   case Intrinsic::ppc_altivec_vcmpgefp_p:
9773     CompareOpc = 454;
9774     isDot = true;
9775     break;
9776   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9777     CompareOpc = 710;
9778     isDot = true;
9779     break;
9780   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9781     CompareOpc = 774;
9782     isDot = true;
9783     break;
9784   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9785     CompareOpc = 838;
9786     isDot = true;
9787     break;
9788   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9789     CompareOpc = 902;
9790     isDot = true;
9791     break;
9792   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9793     if (Subtarget.hasP8Altivec()) {
9794       CompareOpc = 967;
9795       isDot = true;
9796     } else
9797       return false;
9798     break;
9799   case Intrinsic::ppc_altivec_vcmpgtub_p:
9800     CompareOpc = 518;
9801     isDot = true;
9802     break;
9803   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9804     CompareOpc = 582;
9805     isDot = true;
9806     break;
9807   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9808     CompareOpc = 646;
9809     isDot = true;
9810     break;
9811   case Intrinsic::ppc_altivec_vcmpgtud_p:
9812     if (Subtarget.hasP8Altivec()) {
9813       CompareOpc = 711;
9814       isDot = true;
9815     } else
9816       return false;
9817     break;
9818 
9819   // VSX predicate comparisons use the same infrastructure
9820   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9821   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9822   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9823   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9824   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9825   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9826     if (Subtarget.hasVSX()) {
9827       switch (IntrinsicID) {
9828       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9829         CompareOpc = 99;
9830         break;
9831       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9832         CompareOpc = 115;
9833         break;
9834       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9835         CompareOpc = 107;
9836         break;
9837       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9838         CompareOpc = 67;
9839         break;
9840       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9841         CompareOpc = 83;
9842         break;
9843       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9844         CompareOpc = 75;
9845         break;
9846       }
9847       isDot = true;
9848     } else
9849       return false;
9850     break;
9851 
9852   // Normal Comparisons.
9853   case Intrinsic::ppc_altivec_vcmpbfp:
9854     CompareOpc = 966;
9855     break;
9856   case Intrinsic::ppc_altivec_vcmpeqfp:
9857     CompareOpc = 198;
9858     break;
9859   case Intrinsic::ppc_altivec_vcmpequb:
9860     CompareOpc = 6;
9861     break;
9862   case Intrinsic::ppc_altivec_vcmpequh:
9863     CompareOpc = 70;
9864     break;
9865   case Intrinsic::ppc_altivec_vcmpequw:
9866     CompareOpc = 134;
9867     break;
9868   case Intrinsic::ppc_altivec_vcmpequd:
9869     if (Subtarget.hasP8Altivec())
9870       CompareOpc = 199;
9871     else
9872       return false;
9873     break;
9874   case Intrinsic::ppc_altivec_vcmpneb:
9875   case Intrinsic::ppc_altivec_vcmpneh:
9876   case Intrinsic::ppc_altivec_vcmpnew:
9877   case Intrinsic::ppc_altivec_vcmpnezb:
9878   case Intrinsic::ppc_altivec_vcmpnezh:
9879   case Intrinsic::ppc_altivec_vcmpnezw:
9880     if (Subtarget.hasP9Altivec())
9881       switch (IntrinsicID) {
9882       default:
9883         llvm_unreachable("Unknown comparison intrinsic.");
9884       case Intrinsic::ppc_altivec_vcmpneb:
9885         CompareOpc = 7;
9886         break;
9887       case Intrinsic::ppc_altivec_vcmpneh:
9888         CompareOpc = 71;
9889         break;
9890       case Intrinsic::ppc_altivec_vcmpnew:
9891         CompareOpc = 135;
9892         break;
9893       case Intrinsic::ppc_altivec_vcmpnezb:
9894         CompareOpc = 263;
9895         break;
9896       case Intrinsic::ppc_altivec_vcmpnezh:
9897         CompareOpc = 327;
9898         break;
9899       case Intrinsic::ppc_altivec_vcmpnezw:
9900         CompareOpc = 391;
9901         break;
9902       }
9903     else
9904       return false;
9905     break;
9906   case Intrinsic::ppc_altivec_vcmpgefp:
9907     CompareOpc = 454;
9908     break;
9909   case Intrinsic::ppc_altivec_vcmpgtfp:
9910     CompareOpc = 710;
9911     break;
9912   case Intrinsic::ppc_altivec_vcmpgtsb:
9913     CompareOpc = 774;
9914     break;
9915   case Intrinsic::ppc_altivec_vcmpgtsh:
9916     CompareOpc = 838;
9917     break;
9918   case Intrinsic::ppc_altivec_vcmpgtsw:
9919     CompareOpc = 902;
9920     break;
9921   case Intrinsic::ppc_altivec_vcmpgtsd:
9922     if (Subtarget.hasP8Altivec())
9923       CompareOpc = 967;
9924     else
9925       return false;
9926     break;
9927   case Intrinsic::ppc_altivec_vcmpgtub:
9928     CompareOpc = 518;
9929     break;
9930   case Intrinsic::ppc_altivec_vcmpgtuh:
9931     CompareOpc = 582;
9932     break;
9933   case Intrinsic::ppc_altivec_vcmpgtuw:
9934     CompareOpc = 646;
9935     break;
9936   case Intrinsic::ppc_altivec_vcmpgtud:
9937     if (Subtarget.hasP8Altivec())
9938       CompareOpc = 711;
9939     else
9940       return false;
9941     break;
9942   }
9943   return true;
9944 }
9945 
9946 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9947 /// lower, do it, otherwise return null.
9948 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9949                                                    SelectionDAG &DAG) const {
9950   unsigned IntrinsicID =
9951     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9952 
9953   SDLoc dl(Op);
9954 
9955   if (IntrinsicID == Intrinsic::thread_pointer) {
9956     // Reads the thread pointer register, used for __builtin_thread_pointer.
9957     if (Subtarget.isPPC64())
9958       return DAG.getRegister(PPC::X13, MVT::i64);
9959     return DAG.getRegister(PPC::R2, MVT::i32);
9960   }
9961 
9962   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9963   // opcode number of the comparison.
9964   int CompareOpc;
9965   bool isDot;
9966   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9967     return SDValue();    // Don't custom lower most intrinsics.
9968 
9969   // If this is a non-dot comparison, make the VCMP node and we are done.
9970   if (!isDot) {
9971     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9972                               Op.getOperand(1), Op.getOperand(2),
9973                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9974     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9975   }
9976 
9977   // Create the PPCISD altivec 'dot' comparison node.
9978   SDValue Ops[] = {
9979     Op.getOperand(2),  // LHS
9980     Op.getOperand(3),  // RHS
9981     DAG.getConstant(CompareOpc, dl, MVT::i32)
9982   };
9983   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9984   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9985 
9986   // Now that we have the comparison, emit a copy from the CR to a GPR.
9987   // This is flagged to the above dot comparison.
9988   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9989                                 DAG.getRegister(PPC::CR6, MVT::i32),
9990                                 CompNode.getValue(1));
9991 
9992   // Unpack the result based on how the target uses it.
9993   unsigned BitNo;   // Bit # of CR6.
9994   bool InvertBit;   // Invert result?
9995   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9996   default:  // Can't happen, don't crash on invalid number though.
9997   case 0:   // Return the value of the EQ bit of CR6.
9998     BitNo = 0; InvertBit = false;
9999     break;
10000   case 1:   // Return the inverted value of the EQ bit of CR6.
10001     BitNo = 0; InvertBit = true;
10002     break;
10003   case 2:   // Return the value of the LT bit of CR6.
10004     BitNo = 2; InvertBit = false;
10005     break;
10006   case 3:   // Return the inverted value of the LT bit of CR6.
10007     BitNo = 2; InvertBit = true;
10008     break;
10009   }
10010 
10011   // Shift the bit into the low position.
10012   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10013                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10014   // Isolate the bit.
10015   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10016                       DAG.getConstant(1, dl, MVT::i32));
10017 
10018   // If we are supposed to, toggle the bit.
10019   if (InvertBit)
10020     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10021                         DAG.getConstant(1, dl, MVT::i32));
10022   return Flags;
10023 }
10024 
10025 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10026                                                SelectionDAG &DAG) const {
10027   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10028   // the beginning of the argument list.
10029   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10030   SDLoc DL(Op);
10031   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10032   case Intrinsic::ppc_cfence: {
10033     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10034     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10035     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10036                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10037                                                   Op.getOperand(ArgStart + 1)),
10038                                       Op.getOperand(0)),
10039                    0);
10040   }
10041   default:
10042     break;
10043   }
10044   return SDValue();
10045 }
10046 
10047 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10048   // Check for a DIV with the same operands as this REM.
10049   for (auto UI : Op.getOperand(1)->uses()) {
10050     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10051         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10052       if (UI->getOperand(0) == Op.getOperand(0) &&
10053           UI->getOperand(1) == Op.getOperand(1))
10054         return SDValue();
10055   }
10056   return Op;
10057 }
10058 
10059 // Lower scalar BSWAP64 to xxbrd.
10060 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10061   SDLoc dl(Op);
10062   // MTVSRDD
10063   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10064                    Op.getOperand(0));
10065   // XXBRD
10066   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10067   // MFVSRD
10068   int VectorIndex = 0;
10069   if (Subtarget.isLittleEndian())
10070     VectorIndex = 1;
10071   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10072                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10073   return Op;
10074 }
10075 
10076 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10077 // compared to a value that is atomically loaded (atomic loads zero-extend).
10078 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10079                                                 SelectionDAG &DAG) const {
10080   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10081          "Expecting an atomic compare-and-swap here.");
10082   SDLoc dl(Op);
10083   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10084   EVT MemVT = AtomicNode->getMemoryVT();
10085   if (MemVT.getSizeInBits() >= 32)
10086     return Op;
10087 
10088   SDValue CmpOp = Op.getOperand(2);
10089   // If this is already correctly zero-extended, leave it alone.
10090   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10091   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10092     return Op;
10093 
10094   // Clear the high bits of the compare operand.
10095   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10096   SDValue NewCmpOp =
10097     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10098                 DAG.getConstant(MaskVal, dl, MVT::i32));
10099 
10100   // Replace the existing compare operand with the properly zero-extended one.
10101   SmallVector<SDValue, 4> Ops;
10102   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10103     Ops.push_back(AtomicNode->getOperand(i));
10104   Ops[2] = NewCmpOp;
10105   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10106   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10107   auto NodeTy =
10108     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10109   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10110 }
10111 
10112 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10113                                                  SelectionDAG &DAG) const {
10114   SDLoc dl(Op);
10115   // Create a stack slot that is 16-byte aligned.
10116   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10117   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10118   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10119   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10120 
10121   // Store the input value into Value#0 of the stack slot.
10122   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10123                                MachinePointerInfo());
10124   // Load it out.
10125   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10126 }
10127 
10128 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10129                                                   SelectionDAG &DAG) const {
10130   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10131          "Should only be called for ISD::INSERT_VECTOR_ELT");
10132 
10133   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10134   // We have legal lowering for constant indices but not for variable ones.
10135   if (!C)
10136     return SDValue();
10137 
10138   EVT VT = Op.getValueType();
10139   SDLoc dl(Op);
10140   SDValue V1 = Op.getOperand(0);
10141   SDValue V2 = Op.getOperand(1);
10142   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10143   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10144     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10145     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10146     unsigned InsertAtElement = C->getZExtValue();
10147     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10148     if (Subtarget.isLittleEndian()) {
10149       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10150     }
10151     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10152                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10153   }
10154   return Op;
10155 }
10156 
10157 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10158                                                    SelectionDAG &DAG) const {
10159   SDLoc dl(Op);
10160   SDNode *N = Op.getNode();
10161 
10162   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10163          "Unknown extract_vector_elt type");
10164 
10165   SDValue Value = N->getOperand(0);
10166 
10167   // The first part of this is like the store lowering except that we don't
10168   // need to track the chain.
10169 
10170   // The values are now known to be -1 (false) or 1 (true). To convert this
10171   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10172   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10173   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10174 
10175   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10176   // understand how to form the extending load.
10177   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10178 
10179   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10180 
10181   // Now convert to an integer and store.
10182   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10183     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10184     Value);
10185 
10186   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10187   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10188   MachinePointerInfo PtrInfo =
10189       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10190   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10191   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10192 
10193   SDValue StoreChain = DAG.getEntryNode();
10194   SDValue Ops[] = {StoreChain,
10195                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10196                    Value, FIdx};
10197   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10198 
10199   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10200     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10201 
10202   // Extract the value requested.
10203   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10204   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10205   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10206 
10207   SDValue IntVal =
10208       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10209 
10210   if (!Subtarget.useCRBits())
10211     return IntVal;
10212 
10213   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10214 }
10215 
10216 /// Lowering for QPX v4i1 loads
10217 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10218                                            SelectionDAG &DAG) const {
10219   SDLoc dl(Op);
10220   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10221   SDValue LoadChain = LN->getChain();
10222   SDValue BasePtr = LN->getBasePtr();
10223 
10224   if (Op.getValueType() == MVT::v4f64 ||
10225       Op.getValueType() == MVT::v4f32) {
10226     EVT MemVT = LN->getMemoryVT();
10227     unsigned Alignment = LN->getAlignment();
10228 
10229     // If this load is properly aligned, then it is legal.
10230     if (Alignment >= MemVT.getStoreSize())
10231       return Op;
10232 
10233     EVT ScalarVT = Op.getValueType().getScalarType(),
10234         ScalarMemVT = MemVT.getScalarType();
10235     unsigned Stride = ScalarMemVT.getStoreSize();
10236 
10237     SDValue Vals[4], LoadChains[4];
10238     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10239       SDValue Load;
10240       if (ScalarVT != ScalarMemVT)
10241         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10242                               BasePtr,
10243                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10244                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10245                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10246       else
10247         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10248                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10249                            MinAlign(Alignment, Idx * Stride),
10250                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10251 
10252       if (Idx == 0 && LN->isIndexed()) {
10253         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10254                "Unknown addressing mode on vector load");
10255         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10256                                   LN->getAddressingMode());
10257       }
10258 
10259       Vals[Idx] = Load;
10260       LoadChains[Idx] = Load.getValue(1);
10261 
10262       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10263                             DAG.getConstant(Stride, dl,
10264                                             BasePtr.getValueType()));
10265     }
10266 
10267     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10268     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10269 
10270     if (LN->isIndexed()) {
10271       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10272       return DAG.getMergeValues(RetOps, dl);
10273     }
10274 
10275     SDValue RetOps[] = { Value, TF };
10276     return DAG.getMergeValues(RetOps, dl);
10277   }
10278 
10279   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10280   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10281 
10282   // To lower v4i1 from a byte array, we load the byte elements of the
10283   // vector and then reuse the BUILD_VECTOR logic.
10284 
10285   SDValue VectElmts[4], VectElmtChains[4];
10286   for (unsigned i = 0; i < 4; ++i) {
10287     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10288     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10289 
10290     VectElmts[i] = DAG.getExtLoad(
10291         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10292         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10293         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10294     VectElmtChains[i] = VectElmts[i].getValue(1);
10295   }
10296 
10297   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10298   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10299 
10300   SDValue RVals[] = { Value, LoadChain };
10301   return DAG.getMergeValues(RVals, dl);
10302 }
10303 
10304 /// Lowering for QPX v4i1 stores
10305 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10306                                             SelectionDAG &DAG) const {
10307   SDLoc dl(Op);
10308   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10309   SDValue StoreChain = SN->getChain();
10310   SDValue BasePtr = SN->getBasePtr();
10311   SDValue Value = SN->getValue();
10312 
10313   if (Value.getValueType() == MVT::v4f64 ||
10314       Value.getValueType() == MVT::v4f32) {
10315     EVT MemVT = SN->getMemoryVT();
10316     unsigned Alignment = SN->getAlignment();
10317 
10318     // If this store is properly aligned, then it is legal.
10319     if (Alignment >= MemVT.getStoreSize())
10320       return Op;
10321 
10322     EVT ScalarVT = Value.getValueType().getScalarType(),
10323         ScalarMemVT = MemVT.getScalarType();
10324     unsigned Stride = ScalarMemVT.getStoreSize();
10325 
10326     SDValue Stores[4];
10327     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10328       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10329                                DAG.getVectorIdxConstant(Idx, dl));
10330       SDValue Store;
10331       if (ScalarVT != ScalarMemVT)
10332         Store =
10333             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10334                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10335                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10336                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10337       else
10338         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10339                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10340                              MinAlign(Alignment, Idx * Stride),
10341                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10342 
10343       if (Idx == 0 && SN->isIndexed()) {
10344         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10345                "Unknown addressing mode on vector store");
10346         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10347                                     SN->getAddressingMode());
10348       }
10349 
10350       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10351                             DAG.getConstant(Stride, dl,
10352                                             BasePtr.getValueType()));
10353       Stores[Idx] = Store;
10354     }
10355 
10356     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10357 
10358     if (SN->isIndexed()) {
10359       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10360       return DAG.getMergeValues(RetOps, dl);
10361     }
10362 
10363     return TF;
10364   }
10365 
10366   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10367   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10368 
10369   // The values are now known to be -1 (false) or 1 (true). To convert this
10370   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10371   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10372   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10373 
10374   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10375   // understand how to form the extending load.
10376   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10377 
10378   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10379 
10380   // Now convert to an integer and store.
10381   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10382     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10383     Value);
10384 
10385   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10386   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10387   MachinePointerInfo PtrInfo =
10388       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10389   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10390   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10391 
10392   SDValue Ops[] = {StoreChain,
10393                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10394                    Value, FIdx};
10395   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10396 
10397   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10398     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10399 
10400   // Move data into the byte array.
10401   SDValue Loads[4], LoadChains[4];
10402   for (unsigned i = 0; i < 4; ++i) {
10403     unsigned Offset = 4*i;
10404     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10405     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10406 
10407     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10408                            PtrInfo.getWithOffset(Offset));
10409     LoadChains[i] = Loads[i].getValue(1);
10410   }
10411 
10412   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10413 
10414   SDValue Stores[4];
10415   for (unsigned i = 0; i < 4; ++i) {
10416     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10417     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10418 
10419     Stores[i] = DAG.getTruncStore(
10420         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10421         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10422         SN->getAAInfo());
10423   }
10424 
10425   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10426 
10427   return StoreChain;
10428 }
10429 
10430 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10431   SDLoc dl(Op);
10432   if (Op.getValueType() == MVT::v4i32) {
10433     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10434 
10435     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10436     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10437 
10438     SDValue RHSSwap =   // = vrlw RHS, 16
10439       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10440 
10441     // Shrinkify inputs to v8i16.
10442     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10443     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10444     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10445 
10446     // Low parts multiplied together, generating 32-bit results (we ignore the
10447     // top parts).
10448     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10449                                         LHS, RHS, DAG, dl, MVT::v4i32);
10450 
10451     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10452                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10453     // Shift the high parts up 16 bits.
10454     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10455                               Neg16, DAG, dl);
10456     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10457   } else if (Op.getValueType() == MVT::v8i16) {
10458     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10459 
10460     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10461 
10462     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10463                             LHS, RHS, Zero, DAG, dl);
10464   } else if (Op.getValueType() == MVT::v16i8) {
10465     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10466     bool isLittleEndian = Subtarget.isLittleEndian();
10467 
10468     // Multiply the even 8-bit parts, producing 16-bit sums.
10469     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10470                                            LHS, RHS, DAG, dl, MVT::v8i16);
10471     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10472 
10473     // Multiply the odd 8-bit parts, producing 16-bit sums.
10474     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10475                                           LHS, RHS, DAG, dl, MVT::v8i16);
10476     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10477 
10478     // Merge the results together.  Because vmuleub and vmuloub are
10479     // instructions with a big-endian bias, we must reverse the
10480     // element numbering and reverse the meaning of "odd" and "even"
10481     // when generating little endian code.
10482     int Ops[16];
10483     for (unsigned i = 0; i != 8; ++i) {
10484       if (isLittleEndian) {
10485         Ops[i*2  ] = 2*i;
10486         Ops[i*2+1] = 2*i+16;
10487       } else {
10488         Ops[i*2  ] = 2*i+1;
10489         Ops[i*2+1] = 2*i+1+16;
10490       }
10491     }
10492     if (isLittleEndian)
10493       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10494     else
10495       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10496   } else {
10497     llvm_unreachable("Unknown mul to lower!");
10498   }
10499 }
10500 
10501 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10502 
10503   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10504 
10505   EVT VT = Op.getValueType();
10506   assert(VT.isVector() &&
10507          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10508   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10509           VT == MVT::v16i8) &&
10510          "Unexpected vector element type!");
10511   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10512          "Current subtarget doesn't support smax v2i64!");
10513 
10514   // For vector abs, it can be lowered to:
10515   // abs x
10516   // ==>
10517   // y = -x
10518   // smax(x, y)
10519 
10520   SDLoc dl(Op);
10521   SDValue X = Op.getOperand(0);
10522   SDValue Zero = DAG.getConstant(0, dl, VT);
10523   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10524 
10525   // SMAX patch https://reviews.llvm.org/D47332
10526   // hasn't landed yet, so use intrinsic first here.
10527   // TODO: Should use SMAX directly once SMAX patch landed
10528   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10529   if (VT == MVT::v2i64)
10530     BifID = Intrinsic::ppc_altivec_vmaxsd;
10531   else if (VT == MVT::v8i16)
10532     BifID = Intrinsic::ppc_altivec_vmaxsh;
10533   else if (VT == MVT::v16i8)
10534     BifID = Intrinsic::ppc_altivec_vmaxsb;
10535 
10536   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10537 }
10538 
10539 // Custom lowering for fpext vf32 to v2f64
10540 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10541 
10542   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10543          "Should only be called for ISD::FP_EXTEND");
10544 
10545   // We only want to custom lower an extend from v2f32 to v2f64.
10546   if (Op.getValueType() != MVT::v2f64 ||
10547       Op.getOperand(0).getValueType() != MVT::v2f32)
10548     return SDValue();
10549 
10550   SDLoc dl(Op);
10551   SDValue Op0 = Op.getOperand(0);
10552 
10553   switch (Op0.getOpcode()) {
10554   default:
10555     return SDValue();
10556   case ISD::EXTRACT_SUBVECTOR: {
10557     assert(Op0.getNumOperands() == 2 &&
10558            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10559            "Node should have 2 operands with second one being a constant!");
10560 
10561     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10562       return SDValue();
10563 
10564     // Custom lower is only done for high or low doubleword.
10565     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10566     if (Idx % 2 != 0)
10567       return SDValue();
10568 
10569     // Since input is v4f32, at this point Idx is either 0 or 2.
10570     // Shift to get the doubleword position we want.
10571     int DWord = Idx >> 1;
10572 
10573     // High and low word positions are different on little endian.
10574     if (Subtarget.isLittleEndian())
10575       DWord ^= 0x1;
10576 
10577     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10578                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10579   }
10580   case ISD::FADD:
10581   case ISD::FMUL:
10582   case ISD::FSUB: {
10583     SDValue NewLoad[2];
10584     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10585       // Ensure both input are loads.
10586       SDValue LdOp = Op0.getOperand(i);
10587       if (LdOp.getOpcode() != ISD::LOAD)
10588         return SDValue();
10589       // Generate new load node.
10590       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10591       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10592       NewLoad[i] = DAG.getMemIntrinsicNode(
10593           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10594           LD->getMemoryVT(), LD->getMemOperand());
10595     }
10596     SDValue NewOp =
10597         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10598                     NewLoad[1], Op0.getNode()->getFlags());
10599     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10600                        DAG.getConstant(0, dl, MVT::i32));
10601   }
10602   case ISD::LOAD: {
10603     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10604     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10605     SDValue NewLd = DAG.getMemIntrinsicNode(
10606         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10607         LD->getMemoryVT(), LD->getMemOperand());
10608     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10609                        DAG.getConstant(0, dl, MVT::i32));
10610   }
10611   }
10612   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10613 }
10614 
10615 /// LowerOperation - Provide custom lowering hooks for some operations.
10616 ///
10617 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10618   switch (Op.getOpcode()) {
10619   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10620   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10621   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10622   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10623   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10624   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10625   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10626   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10627   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10628 
10629   // Variable argument lowering.
10630   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10631   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10632   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10633 
10634   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10635   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10636   case ISD::GET_DYNAMIC_AREA_OFFSET:
10637     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10638 
10639   // Exception handling lowering.
10640   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10641   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10642   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10643 
10644   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10645   case ISD::STORE:              return LowerSTORE(Op, DAG);
10646   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10647   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10648   case ISD::FP_TO_UINT:
10649   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10650   case ISD::UINT_TO_FP:
10651   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10652   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10653 
10654   // Lower 64-bit shifts.
10655   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10656   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10657   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10658 
10659   // Vector-related lowering.
10660   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10661   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10662   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10663   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10664   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10665   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10666   case ISD::MUL:                return LowerMUL(Op, DAG);
10667   case ISD::ABS:                return LowerABS(Op, DAG);
10668   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10669 
10670   // For counter-based loop handling.
10671   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10672 
10673   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10674 
10675   // Frame & Return address.
10676   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10677   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10678 
10679   case ISD::INTRINSIC_VOID:
10680     return LowerINTRINSIC_VOID(Op, DAG);
10681   case ISD::SREM:
10682   case ISD::UREM:
10683     return LowerREM(Op, DAG);
10684   case ISD::BSWAP:
10685     return LowerBSWAP(Op, DAG);
10686   case ISD::ATOMIC_CMP_SWAP:
10687     return LowerATOMIC_CMP_SWAP(Op, DAG);
10688   }
10689 }
10690 
10691 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10692                                            SmallVectorImpl<SDValue>&Results,
10693                                            SelectionDAG &DAG) const {
10694   SDLoc dl(N);
10695   switch (N->getOpcode()) {
10696   default:
10697     llvm_unreachable("Do not know how to custom type legalize this operation!");
10698   case ISD::READCYCLECOUNTER: {
10699     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10700     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10701 
10702     Results.push_back(
10703         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10704     Results.push_back(RTB.getValue(2));
10705     break;
10706   }
10707   case ISD::INTRINSIC_W_CHAIN: {
10708     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10709         Intrinsic::loop_decrement)
10710       break;
10711 
10712     assert(N->getValueType(0) == MVT::i1 &&
10713            "Unexpected result type for CTR decrement intrinsic");
10714     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10715                                  N->getValueType(0));
10716     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10717     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10718                                  N->getOperand(1));
10719 
10720     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10721     Results.push_back(NewInt.getValue(1));
10722     break;
10723   }
10724   case ISD::VAARG: {
10725     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10726       return;
10727 
10728     EVT VT = N->getValueType(0);
10729 
10730     if (VT == MVT::i64) {
10731       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10732 
10733       Results.push_back(NewNode);
10734       Results.push_back(NewNode.getValue(1));
10735     }
10736     return;
10737   }
10738   case ISD::FP_TO_SINT:
10739   case ISD::FP_TO_UINT:
10740     // LowerFP_TO_INT() can only handle f32 and f64.
10741     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10742       return;
10743     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10744     return;
10745   case ISD::TRUNCATE: {
10746     EVT TrgVT = N->getValueType(0);
10747     EVT OpVT = N->getOperand(0).getValueType();
10748     if (TrgVT.isVector() &&
10749         isOperationCustom(N->getOpcode(), TrgVT) &&
10750         OpVT.getSizeInBits() <= 128 &&
10751         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10752       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10753     return;
10754   }
10755   case ISD::BITCAST:
10756     // Don't handle bitcast here.
10757     return;
10758   }
10759 }
10760 
10761 //===----------------------------------------------------------------------===//
10762 //  Other Lowering Code
10763 //===----------------------------------------------------------------------===//
10764 
10765 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10766   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10767   Function *Func = Intrinsic::getDeclaration(M, Id);
10768   return Builder.CreateCall(Func, {});
10769 }
10770 
10771 // The mappings for emitLeading/TrailingFence is taken from
10772 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10773 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10774                                                  Instruction *Inst,
10775                                                  AtomicOrdering Ord) const {
10776   if (Ord == AtomicOrdering::SequentiallyConsistent)
10777     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10778   if (isReleaseOrStronger(Ord))
10779     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10780   return nullptr;
10781 }
10782 
10783 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10784                                                   Instruction *Inst,
10785                                                   AtomicOrdering Ord) const {
10786   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10787     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10788     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10789     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10790     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10791       return Builder.CreateCall(
10792           Intrinsic::getDeclaration(
10793               Builder.GetInsertBlock()->getParent()->getParent(),
10794               Intrinsic::ppc_cfence, {Inst->getType()}),
10795           {Inst});
10796     // FIXME: Can use isync for rmw operation.
10797     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10798   }
10799   return nullptr;
10800 }
10801 
10802 MachineBasicBlock *
10803 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10804                                     unsigned AtomicSize,
10805                                     unsigned BinOpcode,
10806                                     unsigned CmpOpcode,
10807                                     unsigned CmpPred) const {
10808   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10809   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10810 
10811   auto LoadMnemonic = PPC::LDARX;
10812   auto StoreMnemonic = PPC::STDCX;
10813   switch (AtomicSize) {
10814   default:
10815     llvm_unreachable("Unexpected size of atomic entity");
10816   case 1:
10817     LoadMnemonic = PPC::LBARX;
10818     StoreMnemonic = PPC::STBCX;
10819     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10820     break;
10821   case 2:
10822     LoadMnemonic = PPC::LHARX;
10823     StoreMnemonic = PPC::STHCX;
10824     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10825     break;
10826   case 4:
10827     LoadMnemonic = PPC::LWARX;
10828     StoreMnemonic = PPC::STWCX;
10829     break;
10830   case 8:
10831     LoadMnemonic = PPC::LDARX;
10832     StoreMnemonic = PPC::STDCX;
10833     break;
10834   }
10835 
10836   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10837   MachineFunction *F = BB->getParent();
10838   MachineFunction::iterator It = ++BB->getIterator();
10839 
10840   Register dest = MI.getOperand(0).getReg();
10841   Register ptrA = MI.getOperand(1).getReg();
10842   Register ptrB = MI.getOperand(2).getReg();
10843   Register incr = MI.getOperand(3).getReg();
10844   DebugLoc dl = MI.getDebugLoc();
10845 
10846   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10847   MachineBasicBlock *loop2MBB =
10848     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10849   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10850   F->insert(It, loopMBB);
10851   if (CmpOpcode)
10852     F->insert(It, loop2MBB);
10853   F->insert(It, exitMBB);
10854   exitMBB->splice(exitMBB->begin(), BB,
10855                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10856   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10857 
10858   MachineRegisterInfo &RegInfo = F->getRegInfo();
10859   Register TmpReg = (!BinOpcode) ? incr :
10860     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10861                                            : &PPC::GPRCRegClass);
10862 
10863   //  thisMBB:
10864   //   ...
10865   //   fallthrough --> loopMBB
10866   BB->addSuccessor(loopMBB);
10867 
10868   //  loopMBB:
10869   //   l[wd]arx dest, ptr
10870   //   add r0, dest, incr
10871   //   st[wd]cx. r0, ptr
10872   //   bne- loopMBB
10873   //   fallthrough --> exitMBB
10874 
10875   // For max/min...
10876   //  loopMBB:
10877   //   l[wd]arx dest, ptr
10878   //   cmpl?[wd] incr, dest
10879   //   bgt exitMBB
10880   //  loop2MBB:
10881   //   st[wd]cx. dest, ptr
10882   //   bne- loopMBB
10883   //   fallthrough --> exitMBB
10884 
10885   BB = loopMBB;
10886   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10887     .addReg(ptrA).addReg(ptrB);
10888   if (BinOpcode)
10889     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10890   if (CmpOpcode) {
10891     // Signed comparisons of byte or halfword values must be sign-extended.
10892     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10893       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10894       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10895               ExtReg).addReg(dest);
10896       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10897         .addReg(incr).addReg(ExtReg);
10898     } else
10899       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10900         .addReg(incr).addReg(dest);
10901 
10902     BuildMI(BB, dl, TII->get(PPC::BCC))
10903       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10904     BB->addSuccessor(loop2MBB);
10905     BB->addSuccessor(exitMBB);
10906     BB = loop2MBB;
10907   }
10908   BuildMI(BB, dl, TII->get(StoreMnemonic))
10909     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10910   BuildMI(BB, dl, TII->get(PPC::BCC))
10911     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10912   BB->addSuccessor(loopMBB);
10913   BB->addSuccessor(exitMBB);
10914 
10915   //  exitMBB:
10916   //   ...
10917   BB = exitMBB;
10918   return BB;
10919 }
10920 
10921 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10922     MachineInstr &MI, MachineBasicBlock *BB,
10923     bool is8bit, // operation
10924     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10925   // If we support part-word atomic mnemonics, just use them
10926   if (Subtarget.hasPartwordAtomics())
10927     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10928                             CmpPred);
10929 
10930   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10931   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10932   // In 64 bit mode we have to use 64 bits for addresses, even though the
10933   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10934   // registers without caring whether they're 32 or 64, but here we're
10935   // doing actual arithmetic on the addresses.
10936   bool is64bit = Subtarget.isPPC64();
10937   bool isLittleEndian = Subtarget.isLittleEndian();
10938   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10939 
10940   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10941   MachineFunction *F = BB->getParent();
10942   MachineFunction::iterator It = ++BB->getIterator();
10943 
10944   Register dest = MI.getOperand(0).getReg();
10945   Register ptrA = MI.getOperand(1).getReg();
10946   Register ptrB = MI.getOperand(2).getReg();
10947   Register incr = MI.getOperand(3).getReg();
10948   DebugLoc dl = MI.getDebugLoc();
10949 
10950   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10951   MachineBasicBlock *loop2MBB =
10952       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10953   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10954   F->insert(It, loopMBB);
10955   if (CmpOpcode)
10956     F->insert(It, loop2MBB);
10957   F->insert(It, exitMBB);
10958   exitMBB->splice(exitMBB->begin(), BB,
10959                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10960   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10961 
10962   MachineRegisterInfo &RegInfo = F->getRegInfo();
10963   const TargetRegisterClass *RC =
10964       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10965   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10966 
10967   Register PtrReg = RegInfo.createVirtualRegister(RC);
10968   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10969   Register ShiftReg =
10970       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10971   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10972   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10973   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10974   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10975   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10976   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10977   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10978   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10979   Register Ptr1Reg;
10980   Register TmpReg =
10981       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10982 
10983   //  thisMBB:
10984   //   ...
10985   //   fallthrough --> loopMBB
10986   BB->addSuccessor(loopMBB);
10987 
10988   // The 4-byte load must be aligned, while a char or short may be
10989   // anywhere in the word.  Hence all this nasty bookkeeping code.
10990   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10991   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10992   //   xori shift, shift1, 24 [16]
10993   //   rlwinm ptr, ptr1, 0, 0, 29
10994   //   slw incr2, incr, shift
10995   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10996   //   slw mask, mask2, shift
10997   //  loopMBB:
10998   //   lwarx tmpDest, ptr
10999   //   add tmp, tmpDest, incr2
11000   //   andc tmp2, tmpDest, mask
11001   //   and tmp3, tmp, mask
11002   //   or tmp4, tmp3, tmp2
11003   //   stwcx. tmp4, ptr
11004   //   bne- loopMBB
11005   //   fallthrough --> exitMBB
11006   //   srw dest, tmpDest, shift
11007   if (ptrA != ZeroReg) {
11008     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11009     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11010         .addReg(ptrA)
11011         .addReg(ptrB);
11012   } else {
11013     Ptr1Reg = ptrB;
11014   }
11015   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11016   // mode.
11017   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11018       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11019       .addImm(3)
11020       .addImm(27)
11021       .addImm(is8bit ? 28 : 27);
11022   if (!isLittleEndian)
11023     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11024         .addReg(Shift1Reg)
11025         .addImm(is8bit ? 24 : 16);
11026   if (is64bit)
11027     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11028         .addReg(Ptr1Reg)
11029         .addImm(0)
11030         .addImm(61);
11031   else
11032     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11033         .addReg(Ptr1Reg)
11034         .addImm(0)
11035         .addImm(0)
11036         .addImm(29);
11037   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11038   if (is8bit)
11039     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11040   else {
11041     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11042     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11043         .addReg(Mask3Reg)
11044         .addImm(65535);
11045   }
11046   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11047       .addReg(Mask2Reg)
11048       .addReg(ShiftReg);
11049 
11050   BB = loopMBB;
11051   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11052       .addReg(ZeroReg)
11053       .addReg(PtrReg);
11054   if (BinOpcode)
11055     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11056         .addReg(Incr2Reg)
11057         .addReg(TmpDestReg);
11058   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11059       .addReg(TmpDestReg)
11060       .addReg(MaskReg);
11061   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11062   if (CmpOpcode) {
11063     // For unsigned comparisons, we can directly compare the shifted values.
11064     // For signed comparisons we shift and sign extend.
11065     Register SReg = RegInfo.createVirtualRegister(GPRC);
11066     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11067         .addReg(TmpDestReg)
11068         .addReg(MaskReg);
11069     unsigned ValueReg = SReg;
11070     unsigned CmpReg = Incr2Reg;
11071     if (CmpOpcode == PPC::CMPW) {
11072       ValueReg = RegInfo.createVirtualRegister(GPRC);
11073       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11074           .addReg(SReg)
11075           .addReg(ShiftReg);
11076       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11077       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11078           .addReg(ValueReg);
11079       ValueReg = ValueSReg;
11080       CmpReg = incr;
11081     }
11082     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11083         .addReg(CmpReg)
11084         .addReg(ValueReg);
11085     BuildMI(BB, dl, TII->get(PPC::BCC))
11086         .addImm(CmpPred)
11087         .addReg(PPC::CR0)
11088         .addMBB(exitMBB);
11089     BB->addSuccessor(loop2MBB);
11090     BB->addSuccessor(exitMBB);
11091     BB = loop2MBB;
11092   }
11093   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11094   BuildMI(BB, dl, TII->get(PPC::STWCX))
11095       .addReg(Tmp4Reg)
11096       .addReg(ZeroReg)
11097       .addReg(PtrReg);
11098   BuildMI(BB, dl, TII->get(PPC::BCC))
11099       .addImm(PPC::PRED_NE)
11100       .addReg(PPC::CR0)
11101       .addMBB(loopMBB);
11102   BB->addSuccessor(loopMBB);
11103   BB->addSuccessor(exitMBB);
11104 
11105   //  exitMBB:
11106   //   ...
11107   BB = exitMBB;
11108   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11109       .addReg(TmpDestReg)
11110       .addReg(ShiftReg);
11111   return BB;
11112 }
11113 
11114 llvm::MachineBasicBlock *
11115 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11116                                     MachineBasicBlock *MBB) const {
11117   DebugLoc DL = MI.getDebugLoc();
11118   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11119   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11120 
11121   MachineFunction *MF = MBB->getParent();
11122   MachineRegisterInfo &MRI = MF->getRegInfo();
11123 
11124   const BasicBlock *BB = MBB->getBasicBlock();
11125   MachineFunction::iterator I = ++MBB->getIterator();
11126 
11127   Register DstReg = MI.getOperand(0).getReg();
11128   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11129   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11130   Register mainDstReg = MRI.createVirtualRegister(RC);
11131   Register restoreDstReg = MRI.createVirtualRegister(RC);
11132 
11133   MVT PVT = getPointerTy(MF->getDataLayout());
11134   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11135          "Invalid Pointer Size!");
11136   // For v = setjmp(buf), we generate
11137   //
11138   // thisMBB:
11139   //  SjLjSetup mainMBB
11140   //  bl mainMBB
11141   //  v_restore = 1
11142   //  b sinkMBB
11143   //
11144   // mainMBB:
11145   //  buf[LabelOffset] = LR
11146   //  v_main = 0
11147   //
11148   // sinkMBB:
11149   //  v = phi(main, restore)
11150   //
11151 
11152   MachineBasicBlock *thisMBB = MBB;
11153   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11154   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11155   MF->insert(I, mainMBB);
11156   MF->insert(I, sinkMBB);
11157 
11158   MachineInstrBuilder MIB;
11159 
11160   // Transfer the remainder of BB and its successor edges to sinkMBB.
11161   sinkMBB->splice(sinkMBB->begin(), MBB,
11162                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11163   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11164 
11165   // Note that the structure of the jmp_buf used here is not compatible
11166   // with that used by libc, and is not designed to be. Specifically, it
11167   // stores only those 'reserved' registers that LLVM does not otherwise
11168   // understand how to spill. Also, by convention, by the time this
11169   // intrinsic is called, Clang has already stored the frame address in the
11170   // first slot of the buffer and stack address in the third. Following the
11171   // X86 target code, we'll store the jump address in the second slot. We also
11172   // need to save the TOC pointer (R2) to handle jumps between shared
11173   // libraries, and that will be stored in the fourth slot. The thread
11174   // identifier (R13) is not affected.
11175 
11176   // thisMBB:
11177   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11178   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11179   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11180 
11181   // Prepare IP either in reg.
11182   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11183   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11184   Register BufReg = MI.getOperand(1).getReg();
11185 
11186   if (Subtarget.is64BitELFABI()) {
11187     setUsesTOCBasePtr(*MBB->getParent());
11188     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11189               .addReg(PPC::X2)
11190               .addImm(TOCOffset)
11191               .addReg(BufReg)
11192               .cloneMemRefs(MI);
11193   }
11194 
11195   // Naked functions never have a base pointer, and so we use r1. For all
11196   // other functions, this decision must be delayed until during PEI.
11197   unsigned BaseReg;
11198   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11199     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11200   else
11201     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11202 
11203   MIB = BuildMI(*thisMBB, MI, DL,
11204                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11205             .addReg(BaseReg)
11206             .addImm(BPOffset)
11207             .addReg(BufReg)
11208             .cloneMemRefs(MI);
11209 
11210   // Setup
11211   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11212   MIB.addRegMask(TRI->getNoPreservedMask());
11213 
11214   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11215 
11216   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11217           .addMBB(mainMBB);
11218   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11219 
11220   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11221   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11222 
11223   // mainMBB:
11224   //  mainDstReg = 0
11225   MIB =
11226       BuildMI(mainMBB, DL,
11227               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11228 
11229   // Store IP
11230   if (Subtarget.isPPC64()) {
11231     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11232             .addReg(LabelReg)
11233             .addImm(LabelOffset)
11234             .addReg(BufReg);
11235   } else {
11236     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11237             .addReg(LabelReg)
11238             .addImm(LabelOffset)
11239             .addReg(BufReg);
11240   }
11241   MIB.cloneMemRefs(MI);
11242 
11243   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11244   mainMBB->addSuccessor(sinkMBB);
11245 
11246   // sinkMBB:
11247   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11248           TII->get(PPC::PHI), DstReg)
11249     .addReg(mainDstReg).addMBB(mainMBB)
11250     .addReg(restoreDstReg).addMBB(thisMBB);
11251 
11252   MI.eraseFromParent();
11253   return sinkMBB;
11254 }
11255 
11256 MachineBasicBlock *
11257 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11258                                      MachineBasicBlock *MBB) const {
11259   DebugLoc DL = MI.getDebugLoc();
11260   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11261 
11262   MachineFunction *MF = MBB->getParent();
11263   MachineRegisterInfo &MRI = MF->getRegInfo();
11264 
11265   MVT PVT = getPointerTy(MF->getDataLayout());
11266   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11267          "Invalid Pointer Size!");
11268 
11269   const TargetRegisterClass *RC =
11270     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11271   Register Tmp = MRI.createVirtualRegister(RC);
11272   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11273   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11274   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11275   unsigned BP =
11276       (PVT == MVT::i64)
11277           ? PPC::X30
11278           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11279                                                               : PPC::R30);
11280 
11281   MachineInstrBuilder MIB;
11282 
11283   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11284   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11285   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11286   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11287 
11288   Register BufReg = MI.getOperand(0).getReg();
11289 
11290   // Reload FP (the jumped-to function may not have had a
11291   // frame pointer, and if so, then its r31 will be restored
11292   // as necessary).
11293   if (PVT == MVT::i64) {
11294     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11295             .addImm(0)
11296             .addReg(BufReg);
11297   } else {
11298     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11299             .addImm(0)
11300             .addReg(BufReg);
11301   }
11302   MIB.cloneMemRefs(MI);
11303 
11304   // Reload IP
11305   if (PVT == MVT::i64) {
11306     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11307             .addImm(LabelOffset)
11308             .addReg(BufReg);
11309   } else {
11310     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11311             .addImm(LabelOffset)
11312             .addReg(BufReg);
11313   }
11314   MIB.cloneMemRefs(MI);
11315 
11316   // Reload SP
11317   if (PVT == MVT::i64) {
11318     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11319             .addImm(SPOffset)
11320             .addReg(BufReg);
11321   } else {
11322     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11323             .addImm(SPOffset)
11324             .addReg(BufReg);
11325   }
11326   MIB.cloneMemRefs(MI);
11327 
11328   // Reload BP
11329   if (PVT == MVT::i64) {
11330     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11331             .addImm(BPOffset)
11332             .addReg(BufReg);
11333   } else {
11334     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11335             .addImm(BPOffset)
11336             .addReg(BufReg);
11337   }
11338   MIB.cloneMemRefs(MI);
11339 
11340   // Reload TOC
11341   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11342     setUsesTOCBasePtr(*MBB->getParent());
11343     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11344               .addImm(TOCOffset)
11345               .addReg(BufReg)
11346               .cloneMemRefs(MI);
11347   }
11348 
11349   // Jump
11350   BuildMI(*MBB, MI, DL,
11351           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11352   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11353 
11354   MI.eraseFromParent();
11355   return MBB;
11356 }
11357 
11358 MachineBasicBlock *
11359 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11360                                                MachineBasicBlock *BB) const {
11361   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11362       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11363     if (Subtarget.is64BitELFABI() &&
11364         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11365       // Call lowering should have added an r2 operand to indicate a dependence
11366       // on the TOC base pointer value. It can't however, because there is no
11367       // way to mark the dependence as implicit there, and so the stackmap code
11368       // will confuse it with a regular operand. Instead, add the dependence
11369       // here.
11370       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11371     }
11372 
11373     return emitPatchPoint(MI, BB);
11374   }
11375 
11376   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11377       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11378     return emitEHSjLjSetJmp(MI, BB);
11379   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11380              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11381     return emitEHSjLjLongJmp(MI, BB);
11382   }
11383 
11384   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11385 
11386   // To "insert" these instructions we actually have to insert their
11387   // control-flow patterns.
11388   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11389   MachineFunction::iterator It = ++BB->getIterator();
11390 
11391   MachineFunction *F = BB->getParent();
11392 
11393   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11394       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11395       MI.getOpcode() == PPC::SELECT_I8) {
11396     SmallVector<MachineOperand, 2> Cond;
11397     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11398         MI.getOpcode() == PPC::SELECT_CC_I8)
11399       Cond.push_back(MI.getOperand(4));
11400     else
11401       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11402     Cond.push_back(MI.getOperand(1));
11403 
11404     DebugLoc dl = MI.getDebugLoc();
11405     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11406                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11407   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11408              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11409              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11410              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11411              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11412              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11413              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11414              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11415              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11416              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11417              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11418              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11419              MI.getOpcode() == PPC::SELECT_F4 ||
11420              MI.getOpcode() == PPC::SELECT_F8 ||
11421              MI.getOpcode() == PPC::SELECT_F16 ||
11422              MI.getOpcode() == PPC::SELECT_QFRC ||
11423              MI.getOpcode() == PPC::SELECT_QSRC ||
11424              MI.getOpcode() == PPC::SELECT_QBRC ||
11425              MI.getOpcode() == PPC::SELECT_SPE ||
11426              MI.getOpcode() == PPC::SELECT_SPE4 ||
11427              MI.getOpcode() == PPC::SELECT_VRRC ||
11428              MI.getOpcode() == PPC::SELECT_VSFRC ||
11429              MI.getOpcode() == PPC::SELECT_VSSRC ||
11430              MI.getOpcode() == PPC::SELECT_VSRC) {
11431     // The incoming instruction knows the destination vreg to set, the
11432     // condition code register to branch on, the true/false values to
11433     // select between, and a branch opcode to use.
11434 
11435     //  thisMBB:
11436     //  ...
11437     //   TrueVal = ...
11438     //   cmpTY ccX, r1, r2
11439     //   bCC copy1MBB
11440     //   fallthrough --> copy0MBB
11441     MachineBasicBlock *thisMBB = BB;
11442     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11443     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11444     DebugLoc dl = MI.getDebugLoc();
11445     F->insert(It, copy0MBB);
11446     F->insert(It, sinkMBB);
11447 
11448     // Transfer the remainder of BB and its successor edges to sinkMBB.
11449     sinkMBB->splice(sinkMBB->begin(), BB,
11450                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11451     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11452 
11453     // Next, add the true and fallthrough blocks as its successors.
11454     BB->addSuccessor(copy0MBB);
11455     BB->addSuccessor(sinkMBB);
11456 
11457     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11458         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11459         MI.getOpcode() == PPC::SELECT_F16 ||
11460         MI.getOpcode() == PPC::SELECT_SPE4 ||
11461         MI.getOpcode() == PPC::SELECT_SPE ||
11462         MI.getOpcode() == PPC::SELECT_QFRC ||
11463         MI.getOpcode() == PPC::SELECT_QSRC ||
11464         MI.getOpcode() == PPC::SELECT_QBRC ||
11465         MI.getOpcode() == PPC::SELECT_VRRC ||
11466         MI.getOpcode() == PPC::SELECT_VSFRC ||
11467         MI.getOpcode() == PPC::SELECT_VSSRC ||
11468         MI.getOpcode() == PPC::SELECT_VSRC) {
11469       BuildMI(BB, dl, TII->get(PPC::BC))
11470           .addReg(MI.getOperand(1).getReg())
11471           .addMBB(sinkMBB);
11472     } else {
11473       unsigned SelectPred = MI.getOperand(4).getImm();
11474       BuildMI(BB, dl, TII->get(PPC::BCC))
11475           .addImm(SelectPred)
11476           .addReg(MI.getOperand(1).getReg())
11477           .addMBB(sinkMBB);
11478     }
11479 
11480     //  copy0MBB:
11481     //   %FalseValue = ...
11482     //   # fallthrough to sinkMBB
11483     BB = copy0MBB;
11484 
11485     // Update machine-CFG edges
11486     BB->addSuccessor(sinkMBB);
11487 
11488     //  sinkMBB:
11489     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11490     //  ...
11491     BB = sinkMBB;
11492     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11493         .addReg(MI.getOperand(3).getReg())
11494         .addMBB(copy0MBB)
11495         .addReg(MI.getOperand(2).getReg())
11496         .addMBB(thisMBB);
11497   } else if (MI.getOpcode() == PPC::ReadTB) {
11498     // To read the 64-bit time-base register on a 32-bit target, we read the
11499     // two halves. Should the counter have wrapped while it was being read, we
11500     // need to try again.
11501     // ...
11502     // readLoop:
11503     // mfspr Rx,TBU # load from TBU
11504     // mfspr Ry,TB  # load from TB
11505     // mfspr Rz,TBU # load from TBU
11506     // cmpw crX,Rx,Rz # check if 'old'='new'
11507     // bne readLoop   # branch if they're not equal
11508     // ...
11509 
11510     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11511     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11512     DebugLoc dl = MI.getDebugLoc();
11513     F->insert(It, readMBB);
11514     F->insert(It, sinkMBB);
11515 
11516     // Transfer the remainder of BB and its successor edges to sinkMBB.
11517     sinkMBB->splice(sinkMBB->begin(), BB,
11518                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11519     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11520 
11521     BB->addSuccessor(readMBB);
11522     BB = readMBB;
11523 
11524     MachineRegisterInfo &RegInfo = F->getRegInfo();
11525     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11526     Register LoReg = MI.getOperand(0).getReg();
11527     Register HiReg = MI.getOperand(1).getReg();
11528 
11529     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11530     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11531     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11532 
11533     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11534 
11535     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11536         .addReg(HiReg)
11537         .addReg(ReadAgainReg);
11538     BuildMI(BB, dl, TII->get(PPC::BCC))
11539         .addImm(PPC::PRED_NE)
11540         .addReg(CmpReg)
11541         .addMBB(readMBB);
11542 
11543     BB->addSuccessor(readMBB);
11544     BB->addSuccessor(sinkMBB);
11545   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11546     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11547   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11548     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11549   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11550     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11551   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11552     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11553 
11554   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11555     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11556   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11557     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11558   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11559     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11560   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11561     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11562 
11563   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11564     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11565   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11566     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11567   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11568     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11569   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11570     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11571 
11572   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11573     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11574   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11575     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11576   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11577     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11578   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11579     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11580 
11581   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11582     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11583   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11584     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11585   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11586     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11587   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11588     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11589 
11590   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11591     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11592   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11593     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11594   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11595     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11596   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11597     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11598 
11599   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11600     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11601   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11602     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11603   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11604     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11605   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11606     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11607 
11608   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11609     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11610   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11611     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11612   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11613     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11614   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11615     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11616 
11617   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11618     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11619   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11620     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11621   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11622     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11623   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11624     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11625 
11626   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11627     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11628   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11629     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11630   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11631     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11632   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11633     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11634 
11635   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11636     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11637   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11638     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11639   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11640     BB = EmitAtomicBinary(MI, BB, 4, 0);
11641   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11642     BB = EmitAtomicBinary(MI, BB, 8, 0);
11643   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11644            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11645            (Subtarget.hasPartwordAtomics() &&
11646             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11647            (Subtarget.hasPartwordAtomics() &&
11648             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11649     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11650 
11651     auto LoadMnemonic = PPC::LDARX;
11652     auto StoreMnemonic = PPC::STDCX;
11653     switch (MI.getOpcode()) {
11654     default:
11655       llvm_unreachable("Compare and swap of unknown size");
11656     case PPC::ATOMIC_CMP_SWAP_I8:
11657       LoadMnemonic = PPC::LBARX;
11658       StoreMnemonic = PPC::STBCX;
11659       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11660       break;
11661     case PPC::ATOMIC_CMP_SWAP_I16:
11662       LoadMnemonic = PPC::LHARX;
11663       StoreMnemonic = PPC::STHCX;
11664       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11665       break;
11666     case PPC::ATOMIC_CMP_SWAP_I32:
11667       LoadMnemonic = PPC::LWARX;
11668       StoreMnemonic = PPC::STWCX;
11669       break;
11670     case PPC::ATOMIC_CMP_SWAP_I64:
11671       LoadMnemonic = PPC::LDARX;
11672       StoreMnemonic = PPC::STDCX;
11673       break;
11674     }
11675     Register dest = MI.getOperand(0).getReg();
11676     Register ptrA = MI.getOperand(1).getReg();
11677     Register ptrB = MI.getOperand(2).getReg();
11678     Register oldval = MI.getOperand(3).getReg();
11679     Register newval = MI.getOperand(4).getReg();
11680     DebugLoc dl = MI.getDebugLoc();
11681 
11682     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11683     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11684     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11685     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11686     F->insert(It, loop1MBB);
11687     F->insert(It, loop2MBB);
11688     F->insert(It, midMBB);
11689     F->insert(It, exitMBB);
11690     exitMBB->splice(exitMBB->begin(), BB,
11691                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11692     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11693 
11694     //  thisMBB:
11695     //   ...
11696     //   fallthrough --> loopMBB
11697     BB->addSuccessor(loop1MBB);
11698 
11699     // loop1MBB:
11700     //   l[bhwd]arx dest, ptr
11701     //   cmp[wd] dest, oldval
11702     //   bne- midMBB
11703     // loop2MBB:
11704     //   st[bhwd]cx. newval, ptr
11705     //   bne- loopMBB
11706     //   b exitBB
11707     // midMBB:
11708     //   st[bhwd]cx. dest, ptr
11709     // exitBB:
11710     BB = loop1MBB;
11711     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11712     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11713         .addReg(oldval)
11714         .addReg(dest);
11715     BuildMI(BB, dl, TII->get(PPC::BCC))
11716         .addImm(PPC::PRED_NE)
11717         .addReg(PPC::CR0)
11718         .addMBB(midMBB);
11719     BB->addSuccessor(loop2MBB);
11720     BB->addSuccessor(midMBB);
11721 
11722     BB = loop2MBB;
11723     BuildMI(BB, dl, TII->get(StoreMnemonic))
11724         .addReg(newval)
11725         .addReg(ptrA)
11726         .addReg(ptrB);
11727     BuildMI(BB, dl, TII->get(PPC::BCC))
11728         .addImm(PPC::PRED_NE)
11729         .addReg(PPC::CR0)
11730         .addMBB(loop1MBB);
11731     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11732     BB->addSuccessor(loop1MBB);
11733     BB->addSuccessor(exitMBB);
11734 
11735     BB = midMBB;
11736     BuildMI(BB, dl, TII->get(StoreMnemonic))
11737         .addReg(dest)
11738         .addReg(ptrA)
11739         .addReg(ptrB);
11740     BB->addSuccessor(exitMBB);
11741 
11742     //  exitMBB:
11743     //   ...
11744     BB = exitMBB;
11745   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11746              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11747     // We must use 64-bit registers for addresses when targeting 64-bit,
11748     // since we're actually doing arithmetic on them.  Other registers
11749     // can be 32-bit.
11750     bool is64bit = Subtarget.isPPC64();
11751     bool isLittleEndian = Subtarget.isLittleEndian();
11752     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11753 
11754     Register dest = MI.getOperand(0).getReg();
11755     Register ptrA = MI.getOperand(1).getReg();
11756     Register ptrB = MI.getOperand(2).getReg();
11757     Register oldval = MI.getOperand(3).getReg();
11758     Register newval = MI.getOperand(4).getReg();
11759     DebugLoc dl = MI.getDebugLoc();
11760 
11761     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11762     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11763     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11764     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11765     F->insert(It, loop1MBB);
11766     F->insert(It, loop2MBB);
11767     F->insert(It, midMBB);
11768     F->insert(It, exitMBB);
11769     exitMBB->splice(exitMBB->begin(), BB,
11770                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11771     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11772 
11773     MachineRegisterInfo &RegInfo = F->getRegInfo();
11774     const TargetRegisterClass *RC =
11775         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11776     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11777 
11778     Register PtrReg = RegInfo.createVirtualRegister(RC);
11779     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11780     Register ShiftReg =
11781         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11782     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11783     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11784     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11785     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11786     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11787     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11788     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11789     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11790     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11791     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11792     Register Ptr1Reg;
11793     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11794     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11795     //  thisMBB:
11796     //   ...
11797     //   fallthrough --> loopMBB
11798     BB->addSuccessor(loop1MBB);
11799 
11800     // The 4-byte load must be aligned, while a char or short may be
11801     // anywhere in the word.  Hence all this nasty bookkeeping code.
11802     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11803     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11804     //   xori shift, shift1, 24 [16]
11805     //   rlwinm ptr, ptr1, 0, 0, 29
11806     //   slw newval2, newval, shift
11807     //   slw oldval2, oldval,shift
11808     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11809     //   slw mask, mask2, shift
11810     //   and newval3, newval2, mask
11811     //   and oldval3, oldval2, mask
11812     // loop1MBB:
11813     //   lwarx tmpDest, ptr
11814     //   and tmp, tmpDest, mask
11815     //   cmpw tmp, oldval3
11816     //   bne- midMBB
11817     // loop2MBB:
11818     //   andc tmp2, tmpDest, mask
11819     //   or tmp4, tmp2, newval3
11820     //   stwcx. tmp4, ptr
11821     //   bne- loop1MBB
11822     //   b exitBB
11823     // midMBB:
11824     //   stwcx. tmpDest, ptr
11825     // exitBB:
11826     //   srw dest, tmpDest, shift
11827     if (ptrA != ZeroReg) {
11828       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11829       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11830           .addReg(ptrA)
11831           .addReg(ptrB);
11832     } else {
11833       Ptr1Reg = ptrB;
11834     }
11835 
11836     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11837     // mode.
11838     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11839         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11840         .addImm(3)
11841         .addImm(27)
11842         .addImm(is8bit ? 28 : 27);
11843     if (!isLittleEndian)
11844       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11845           .addReg(Shift1Reg)
11846           .addImm(is8bit ? 24 : 16);
11847     if (is64bit)
11848       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11849           .addReg(Ptr1Reg)
11850           .addImm(0)
11851           .addImm(61);
11852     else
11853       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11854           .addReg(Ptr1Reg)
11855           .addImm(0)
11856           .addImm(0)
11857           .addImm(29);
11858     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11859         .addReg(newval)
11860         .addReg(ShiftReg);
11861     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11862         .addReg(oldval)
11863         .addReg(ShiftReg);
11864     if (is8bit)
11865       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11866     else {
11867       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11868       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11869           .addReg(Mask3Reg)
11870           .addImm(65535);
11871     }
11872     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11873         .addReg(Mask2Reg)
11874         .addReg(ShiftReg);
11875     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11876         .addReg(NewVal2Reg)
11877         .addReg(MaskReg);
11878     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11879         .addReg(OldVal2Reg)
11880         .addReg(MaskReg);
11881 
11882     BB = loop1MBB;
11883     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11884         .addReg(ZeroReg)
11885         .addReg(PtrReg);
11886     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11887         .addReg(TmpDestReg)
11888         .addReg(MaskReg);
11889     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11890         .addReg(TmpReg)
11891         .addReg(OldVal3Reg);
11892     BuildMI(BB, dl, TII->get(PPC::BCC))
11893         .addImm(PPC::PRED_NE)
11894         .addReg(PPC::CR0)
11895         .addMBB(midMBB);
11896     BB->addSuccessor(loop2MBB);
11897     BB->addSuccessor(midMBB);
11898 
11899     BB = loop2MBB;
11900     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11901         .addReg(TmpDestReg)
11902         .addReg(MaskReg);
11903     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11904         .addReg(Tmp2Reg)
11905         .addReg(NewVal3Reg);
11906     BuildMI(BB, dl, TII->get(PPC::STWCX))
11907         .addReg(Tmp4Reg)
11908         .addReg(ZeroReg)
11909         .addReg(PtrReg);
11910     BuildMI(BB, dl, TII->get(PPC::BCC))
11911         .addImm(PPC::PRED_NE)
11912         .addReg(PPC::CR0)
11913         .addMBB(loop1MBB);
11914     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11915     BB->addSuccessor(loop1MBB);
11916     BB->addSuccessor(exitMBB);
11917 
11918     BB = midMBB;
11919     BuildMI(BB, dl, TII->get(PPC::STWCX))
11920         .addReg(TmpDestReg)
11921         .addReg(ZeroReg)
11922         .addReg(PtrReg);
11923     BB->addSuccessor(exitMBB);
11924 
11925     //  exitMBB:
11926     //   ...
11927     BB = exitMBB;
11928     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11929         .addReg(TmpReg)
11930         .addReg(ShiftReg);
11931   } else if (MI.getOpcode() == PPC::FADDrtz) {
11932     // This pseudo performs an FADD with rounding mode temporarily forced
11933     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11934     // is not modeled at the SelectionDAG level.
11935     Register Dest = MI.getOperand(0).getReg();
11936     Register Src1 = MI.getOperand(1).getReg();
11937     Register Src2 = MI.getOperand(2).getReg();
11938     DebugLoc dl = MI.getDebugLoc();
11939 
11940     MachineRegisterInfo &RegInfo = F->getRegInfo();
11941     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11942 
11943     // Save FPSCR value.
11944     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11945 
11946     // Set rounding mode to round-to-zero.
11947     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11948     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11949 
11950     // Perform addition.
11951     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11952 
11953     // Restore FPSCR value.
11954     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11955   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11956              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11957              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11958              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11959     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11960                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11961                           ? PPC::ANDI8_rec
11962                           : PPC::ANDI_rec;
11963     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11964                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11965 
11966     MachineRegisterInfo &RegInfo = F->getRegInfo();
11967     Register Dest = RegInfo.createVirtualRegister(
11968         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11969 
11970     DebugLoc Dl = MI.getDebugLoc();
11971     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11972         .addReg(MI.getOperand(1).getReg())
11973         .addImm(1);
11974     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11975             MI.getOperand(0).getReg())
11976         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11977   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11978     DebugLoc Dl = MI.getDebugLoc();
11979     MachineRegisterInfo &RegInfo = F->getRegInfo();
11980     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11981     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11982     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11983             MI.getOperand(0).getReg())
11984         .addReg(CRReg);
11985   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11986     DebugLoc Dl = MI.getDebugLoc();
11987     unsigned Imm = MI.getOperand(1).getImm();
11988     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11989     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11990             MI.getOperand(0).getReg())
11991         .addReg(PPC::CR0EQ);
11992   } else if (MI.getOpcode() == PPC::SETRNDi) {
11993     DebugLoc dl = MI.getDebugLoc();
11994     Register OldFPSCRReg = MI.getOperand(0).getReg();
11995 
11996     // Save FPSCR value.
11997     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11998 
11999     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12000     // the following settings:
12001     //   00 Round to nearest
12002     //   01 Round to 0
12003     //   10 Round to +inf
12004     //   11 Round to -inf
12005 
12006     // When the operand is immediate, using the two least significant bits of
12007     // the immediate to set the bits 62:63 of FPSCR.
12008     unsigned Mode = MI.getOperand(1).getImm();
12009     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12010       .addImm(31);
12011 
12012     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12013       .addImm(30);
12014   } else if (MI.getOpcode() == PPC::SETRND) {
12015     DebugLoc dl = MI.getDebugLoc();
12016 
12017     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12018     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12019     // If the target doesn't have DirectMove, we should use stack to do the
12020     // conversion, because the target doesn't have the instructions like mtvsrd
12021     // or mfvsrd to do this conversion directly.
12022     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12023       if (Subtarget.hasDirectMove()) {
12024         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12025           .addReg(SrcReg);
12026       } else {
12027         // Use stack to do the register copy.
12028         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12029         MachineRegisterInfo &RegInfo = F->getRegInfo();
12030         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12031         if (RC == &PPC::F8RCRegClass) {
12032           // Copy register from F8RCRegClass to G8RCRegclass.
12033           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12034                  "Unsupported RegClass.");
12035 
12036           StoreOp = PPC::STFD;
12037           LoadOp = PPC::LD;
12038         } else {
12039           // Copy register from G8RCRegClass to F8RCRegclass.
12040           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12041                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12042                  "Unsupported RegClass.");
12043         }
12044 
12045         MachineFrameInfo &MFI = F->getFrameInfo();
12046         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12047 
12048         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12049           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12050           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12051           MFI.getObjectAlignment(FrameIdx));
12052 
12053         // Store the SrcReg into the stack.
12054         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12055           .addReg(SrcReg)
12056           .addImm(0)
12057           .addFrameIndex(FrameIdx)
12058           .addMemOperand(MMOStore);
12059 
12060         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12061           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12062           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12063           MFI.getObjectAlignment(FrameIdx));
12064 
12065         // Load from the stack where SrcReg is stored, and save to DestReg,
12066         // so we have done the RegClass conversion from RegClass::SrcReg to
12067         // RegClass::DestReg.
12068         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12069           .addImm(0)
12070           .addFrameIndex(FrameIdx)
12071           .addMemOperand(MMOLoad);
12072       }
12073     };
12074 
12075     Register OldFPSCRReg = MI.getOperand(0).getReg();
12076 
12077     // Save FPSCR value.
12078     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12079 
12080     // When the operand is gprc register, use two least significant bits of the
12081     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12082     //
12083     // copy OldFPSCRTmpReg, OldFPSCRReg
12084     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12085     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12086     // copy NewFPSCRReg, NewFPSCRTmpReg
12087     // mtfsf 255, NewFPSCRReg
12088     MachineOperand SrcOp = MI.getOperand(1);
12089     MachineRegisterInfo &RegInfo = F->getRegInfo();
12090     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12091 
12092     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12093 
12094     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12095     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12096 
12097     // The first operand of INSERT_SUBREG should be a register which has
12098     // subregisters, we only care about its RegClass, so we should use an
12099     // IMPLICIT_DEF register.
12100     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12101     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12102       .addReg(ImDefReg)
12103       .add(SrcOp)
12104       .addImm(1);
12105 
12106     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12107     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12108       .addReg(OldFPSCRTmpReg)
12109       .addReg(ExtSrcReg)
12110       .addImm(0)
12111       .addImm(62);
12112 
12113     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12114     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12115 
12116     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12117     // bits of FPSCR.
12118     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12119       .addImm(255)
12120       .addReg(NewFPSCRReg)
12121       .addImm(0)
12122       .addImm(0);
12123   } else {
12124     llvm_unreachable("Unexpected instr type to insert");
12125   }
12126 
12127   MI.eraseFromParent(); // The pseudo instruction is gone now.
12128   return BB;
12129 }
12130 
12131 //===----------------------------------------------------------------------===//
12132 // Target Optimization Hooks
12133 //===----------------------------------------------------------------------===//
12134 
12135 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12136   // For the estimates, convergence is quadratic, so we essentially double the
12137   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12138   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12139   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12140   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12141   if (VT.getScalarType() == MVT::f64)
12142     RefinementSteps++;
12143   return RefinementSteps;
12144 }
12145 
12146 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12147                                            int Enabled, int &RefinementSteps,
12148                                            bool &UseOneConstNR,
12149                                            bool Reciprocal) const {
12150   EVT VT = Operand.getValueType();
12151   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12152       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12153       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12154       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12155       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12156       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12157     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12158       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12159 
12160     // The Newton-Raphson computation with a single constant does not provide
12161     // enough accuracy on some CPUs.
12162     UseOneConstNR = !Subtarget.needsTwoConstNR();
12163     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12164   }
12165   return SDValue();
12166 }
12167 
12168 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12169                                             int Enabled,
12170                                             int &RefinementSteps) const {
12171   EVT VT = Operand.getValueType();
12172   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12173       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12174       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12175       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12176       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12177       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12178     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12179       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12180     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12181   }
12182   return SDValue();
12183 }
12184 
12185 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12186   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12187   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12188   // enabled for division), this functionality is redundant with the default
12189   // combiner logic (once the division -> reciprocal/multiply transformation
12190   // has taken place). As a result, this matters more for older cores than for
12191   // newer ones.
12192 
12193   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12194   // reciprocal if there are two or more FDIVs (for embedded cores with only
12195   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12196   switch (Subtarget.getCPUDirective()) {
12197   default:
12198     return 3;
12199   case PPC::DIR_440:
12200   case PPC::DIR_A2:
12201   case PPC::DIR_E500:
12202   case PPC::DIR_E500mc:
12203   case PPC::DIR_E5500:
12204     return 2;
12205   }
12206 }
12207 
12208 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12209 // collapsed, and so we need to look through chains of them.
12210 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12211                                      int64_t& Offset, SelectionDAG &DAG) {
12212   if (DAG.isBaseWithConstantOffset(Loc)) {
12213     Base = Loc.getOperand(0);
12214     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12215 
12216     // The base might itself be a base plus an offset, and if so, accumulate
12217     // that as well.
12218     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12219   }
12220 }
12221 
12222 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12223                             unsigned Bytes, int Dist,
12224                             SelectionDAG &DAG) {
12225   if (VT.getSizeInBits() / 8 != Bytes)
12226     return false;
12227 
12228   SDValue BaseLoc = Base->getBasePtr();
12229   if (Loc.getOpcode() == ISD::FrameIndex) {
12230     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12231       return false;
12232     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12233     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12234     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12235     int FS  = MFI.getObjectSize(FI);
12236     int BFS = MFI.getObjectSize(BFI);
12237     if (FS != BFS || FS != (int)Bytes) return false;
12238     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12239   }
12240 
12241   SDValue Base1 = Loc, Base2 = BaseLoc;
12242   int64_t Offset1 = 0, Offset2 = 0;
12243   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12244   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12245   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12246     return true;
12247 
12248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12249   const GlobalValue *GV1 = nullptr;
12250   const GlobalValue *GV2 = nullptr;
12251   Offset1 = 0;
12252   Offset2 = 0;
12253   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12254   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12255   if (isGA1 && isGA2 && GV1 == GV2)
12256     return Offset1 == (Offset2 + Dist*Bytes);
12257   return false;
12258 }
12259 
12260 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12261 // not enforce equality of the chain operands.
12262 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12263                             unsigned Bytes, int Dist,
12264                             SelectionDAG &DAG) {
12265   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12266     EVT VT = LS->getMemoryVT();
12267     SDValue Loc = LS->getBasePtr();
12268     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12269   }
12270 
12271   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12272     EVT VT;
12273     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12274     default: return false;
12275     case Intrinsic::ppc_qpx_qvlfd:
12276     case Intrinsic::ppc_qpx_qvlfda:
12277       VT = MVT::v4f64;
12278       break;
12279     case Intrinsic::ppc_qpx_qvlfs:
12280     case Intrinsic::ppc_qpx_qvlfsa:
12281       VT = MVT::v4f32;
12282       break;
12283     case Intrinsic::ppc_qpx_qvlfcd:
12284     case Intrinsic::ppc_qpx_qvlfcda:
12285       VT = MVT::v2f64;
12286       break;
12287     case Intrinsic::ppc_qpx_qvlfcs:
12288     case Intrinsic::ppc_qpx_qvlfcsa:
12289       VT = MVT::v2f32;
12290       break;
12291     case Intrinsic::ppc_qpx_qvlfiwa:
12292     case Intrinsic::ppc_qpx_qvlfiwz:
12293     case Intrinsic::ppc_altivec_lvx:
12294     case Intrinsic::ppc_altivec_lvxl:
12295     case Intrinsic::ppc_vsx_lxvw4x:
12296     case Intrinsic::ppc_vsx_lxvw4x_be:
12297       VT = MVT::v4i32;
12298       break;
12299     case Intrinsic::ppc_vsx_lxvd2x:
12300     case Intrinsic::ppc_vsx_lxvd2x_be:
12301       VT = MVT::v2f64;
12302       break;
12303     case Intrinsic::ppc_altivec_lvebx:
12304       VT = MVT::i8;
12305       break;
12306     case Intrinsic::ppc_altivec_lvehx:
12307       VT = MVT::i16;
12308       break;
12309     case Intrinsic::ppc_altivec_lvewx:
12310       VT = MVT::i32;
12311       break;
12312     }
12313 
12314     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12315   }
12316 
12317   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12318     EVT VT;
12319     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12320     default: return false;
12321     case Intrinsic::ppc_qpx_qvstfd:
12322     case Intrinsic::ppc_qpx_qvstfda:
12323       VT = MVT::v4f64;
12324       break;
12325     case Intrinsic::ppc_qpx_qvstfs:
12326     case Intrinsic::ppc_qpx_qvstfsa:
12327       VT = MVT::v4f32;
12328       break;
12329     case Intrinsic::ppc_qpx_qvstfcd:
12330     case Intrinsic::ppc_qpx_qvstfcda:
12331       VT = MVT::v2f64;
12332       break;
12333     case Intrinsic::ppc_qpx_qvstfcs:
12334     case Intrinsic::ppc_qpx_qvstfcsa:
12335       VT = MVT::v2f32;
12336       break;
12337     case Intrinsic::ppc_qpx_qvstfiw:
12338     case Intrinsic::ppc_qpx_qvstfiwa:
12339     case Intrinsic::ppc_altivec_stvx:
12340     case Intrinsic::ppc_altivec_stvxl:
12341     case Intrinsic::ppc_vsx_stxvw4x:
12342       VT = MVT::v4i32;
12343       break;
12344     case Intrinsic::ppc_vsx_stxvd2x:
12345       VT = MVT::v2f64;
12346       break;
12347     case Intrinsic::ppc_vsx_stxvw4x_be:
12348       VT = MVT::v4i32;
12349       break;
12350     case Intrinsic::ppc_vsx_stxvd2x_be:
12351       VT = MVT::v2f64;
12352       break;
12353     case Intrinsic::ppc_altivec_stvebx:
12354       VT = MVT::i8;
12355       break;
12356     case Intrinsic::ppc_altivec_stvehx:
12357       VT = MVT::i16;
12358       break;
12359     case Intrinsic::ppc_altivec_stvewx:
12360       VT = MVT::i32;
12361       break;
12362     }
12363 
12364     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12365   }
12366 
12367   return false;
12368 }
12369 
12370 // Return true is there is a nearyby consecutive load to the one provided
12371 // (regardless of alignment). We search up and down the chain, looking though
12372 // token factors and other loads (but nothing else). As a result, a true result
12373 // indicates that it is safe to create a new consecutive load adjacent to the
12374 // load provided.
12375 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12376   SDValue Chain = LD->getChain();
12377   EVT VT = LD->getMemoryVT();
12378 
12379   SmallSet<SDNode *, 16> LoadRoots;
12380   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12381   SmallSet<SDNode *, 16> Visited;
12382 
12383   // First, search up the chain, branching to follow all token-factor operands.
12384   // If we find a consecutive load, then we're done, otherwise, record all
12385   // nodes just above the top-level loads and token factors.
12386   while (!Queue.empty()) {
12387     SDNode *ChainNext = Queue.pop_back_val();
12388     if (!Visited.insert(ChainNext).second)
12389       continue;
12390 
12391     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12392       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12393         return true;
12394 
12395       if (!Visited.count(ChainLD->getChain().getNode()))
12396         Queue.push_back(ChainLD->getChain().getNode());
12397     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12398       for (const SDUse &O : ChainNext->ops())
12399         if (!Visited.count(O.getNode()))
12400           Queue.push_back(O.getNode());
12401     } else
12402       LoadRoots.insert(ChainNext);
12403   }
12404 
12405   // Second, search down the chain, starting from the top-level nodes recorded
12406   // in the first phase. These top-level nodes are the nodes just above all
12407   // loads and token factors. Starting with their uses, recursively look though
12408   // all loads (just the chain uses) and token factors to find a consecutive
12409   // load.
12410   Visited.clear();
12411   Queue.clear();
12412 
12413   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12414        IE = LoadRoots.end(); I != IE; ++I) {
12415     Queue.push_back(*I);
12416 
12417     while (!Queue.empty()) {
12418       SDNode *LoadRoot = Queue.pop_back_val();
12419       if (!Visited.insert(LoadRoot).second)
12420         continue;
12421 
12422       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12423         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12424           return true;
12425 
12426       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12427            UE = LoadRoot->use_end(); UI != UE; ++UI)
12428         if (((isa<MemSDNode>(*UI) &&
12429             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12430             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12431           Queue.push_back(*UI);
12432     }
12433   }
12434 
12435   return false;
12436 }
12437 
12438 /// This function is called when we have proved that a SETCC node can be replaced
12439 /// by subtraction (and other supporting instructions) so that the result of
12440 /// comparison is kept in a GPR instead of CR. This function is purely for
12441 /// codegen purposes and has some flags to guide the codegen process.
12442 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12443                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12444   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12445 
12446   // Zero extend the operands to the largest legal integer. Originally, they
12447   // must be of a strictly smaller size.
12448   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12449                          DAG.getConstant(Size, DL, MVT::i32));
12450   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12451                          DAG.getConstant(Size, DL, MVT::i32));
12452 
12453   // Swap if needed. Depends on the condition code.
12454   if (Swap)
12455     std::swap(Op0, Op1);
12456 
12457   // Subtract extended integers.
12458   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12459 
12460   // Move the sign bit to the least significant position and zero out the rest.
12461   // Now the least significant bit carries the result of original comparison.
12462   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12463                              DAG.getConstant(Size - 1, DL, MVT::i32));
12464   auto Final = Shifted;
12465 
12466   // Complement the result if needed. Based on the condition code.
12467   if (Complement)
12468     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12469                         DAG.getConstant(1, DL, MVT::i64));
12470 
12471   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12472 }
12473 
12474 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12475                                                   DAGCombinerInfo &DCI) const {
12476   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12477 
12478   SelectionDAG &DAG = DCI.DAG;
12479   SDLoc DL(N);
12480 
12481   // Size of integers being compared has a critical role in the following
12482   // analysis, so we prefer to do this when all types are legal.
12483   if (!DCI.isAfterLegalizeDAG())
12484     return SDValue();
12485 
12486   // If all users of SETCC extend its value to a legal integer type
12487   // then we replace SETCC with a subtraction
12488   for (SDNode::use_iterator UI = N->use_begin(),
12489        UE = N->use_end(); UI != UE; ++UI) {
12490     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12491       return SDValue();
12492   }
12493 
12494   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12495   auto OpSize = N->getOperand(0).getValueSizeInBits();
12496 
12497   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12498 
12499   if (OpSize < Size) {
12500     switch (CC) {
12501     default: break;
12502     case ISD::SETULT:
12503       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12504     case ISD::SETULE:
12505       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12506     case ISD::SETUGT:
12507       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12508     case ISD::SETUGE:
12509       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12510     }
12511   }
12512 
12513   return SDValue();
12514 }
12515 
12516 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12517                                                   DAGCombinerInfo &DCI) const {
12518   SelectionDAG &DAG = DCI.DAG;
12519   SDLoc dl(N);
12520 
12521   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12522   // If we're tracking CR bits, we need to be careful that we don't have:
12523   //   trunc(binary-ops(zext(x), zext(y)))
12524   // or
12525   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12526   // such that we're unnecessarily moving things into GPRs when it would be
12527   // better to keep them in CR bits.
12528 
12529   // Note that trunc here can be an actual i1 trunc, or can be the effective
12530   // truncation that comes from a setcc or select_cc.
12531   if (N->getOpcode() == ISD::TRUNCATE &&
12532       N->getValueType(0) != MVT::i1)
12533     return SDValue();
12534 
12535   if (N->getOperand(0).getValueType() != MVT::i32 &&
12536       N->getOperand(0).getValueType() != MVT::i64)
12537     return SDValue();
12538 
12539   if (N->getOpcode() == ISD::SETCC ||
12540       N->getOpcode() == ISD::SELECT_CC) {
12541     // If we're looking at a comparison, then we need to make sure that the
12542     // high bits (all except for the first) don't matter the result.
12543     ISD::CondCode CC =
12544       cast<CondCodeSDNode>(N->getOperand(
12545         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12546     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12547 
12548     if (ISD::isSignedIntSetCC(CC)) {
12549       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12550           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12551         return SDValue();
12552     } else if (ISD::isUnsignedIntSetCC(CC)) {
12553       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12554                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12555           !DAG.MaskedValueIsZero(N->getOperand(1),
12556                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12557         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12558                                              : SDValue());
12559     } else {
12560       // This is neither a signed nor an unsigned comparison, just make sure
12561       // that the high bits are equal.
12562       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12563       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12564 
12565       // We don't really care about what is known about the first bit (if
12566       // anything), so clear it in all masks prior to comparing them.
12567       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12568       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12569 
12570       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12571         return SDValue();
12572     }
12573   }
12574 
12575   // We now know that the higher-order bits are irrelevant, we just need to
12576   // make sure that all of the intermediate operations are bit operations, and
12577   // all inputs are extensions.
12578   if (N->getOperand(0).getOpcode() != ISD::AND &&
12579       N->getOperand(0).getOpcode() != ISD::OR  &&
12580       N->getOperand(0).getOpcode() != ISD::XOR &&
12581       N->getOperand(0).getOpcode() != ISD::SELECT &&
12582       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12583       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12584       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12585       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12586       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12587     return SDValue();
12588 
12589   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12590       N->getOperand(1).getOpcode() != ISD::AND &&
12591       N->getOperand(1).getOpcode() != ISD::OR  &&
12592       N->getOperand(1).getOpcode() != ISD::XOR &&
12593       N->getOperand(1).getOpcode() != ISD::SELECT &&
12594       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12595       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12596       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12597       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12598       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12599     return SDValue();
12600 
12601   SmallVector<SDValue, 4> Inputs;
12602   SmallVector<SDValue, 8> BinOps, PromOps;
12603   SmallPtrSet<SDNode *, 16> Visited;
12604 
12605   for (unsigned i = 0; i < 2; ++i) {
12606     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12607           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12608           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12609           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12610         isa<ConstantSDNode>(N->getOperand(i)))
12611       Inputs.push_back(N->getOperand(i));
12612     else
12613       BinOps.push_back(N->getOperand(i));
12614 
12615     if (N->getOpcode() == ISD::TRUNCATE)
12616       break;
12617   }
12618 
12619   // Visit all inputs, collect all binary operations (and, or, xor and
12620   // select) that are all fed by extensions.
12621   while (!BinOps.empty()) {
12622     SDValue BinOp = BinOps.back();
12623     BinOps.pop_back();
12624 
12625     if (!Visited.insert(BinOp.getNode()).second)
12626       continue;
12627 
12628     PromOps.push_back(BinOp);
12629 
12630     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12631       // The condition of the select is not promoted.
12632       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12633         continue;
12634       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12635         continue;
12636 
12637       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12638             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12639             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12640            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12641           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12642         Inputs.push_back(BinOp.getOperand(i));
12643       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12644                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12645                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12646                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12647                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12648                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12649                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12650                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12651                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12652         BinOps.push_back(BinOp.getOperand(i));
12653       } else {
12654         // We have an input that is not an extension or another binary
12655         // operation; we'll abort this transformation.
12656         return SDValue();
12657       }
12658     }
12659   }
12660 
12661   // Make sure that this is a self-contained cluster of operations (which
12662   // is not quite the same thing as saying that everything has only one
12663   // use).
12664   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12665     if (isa<ConstantSDNode>(Inputs[i]))
12666       continue;
12667 
12668     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12669                               UE = Inputs[i].getNode()->use_end();
12670          UI != UE; ++UI) {
12671       SDNode *User = *UI;
12672       if (User != N && !Visited.count(User))
12673         return SDValue();
12674 
12675       // Make sure that we're not going to promote the non-output-value
12676       // operand(s) or SELECT or SELECT_CC.
12677       // FIXME: Although we could sometimes handle this, and it does occur in
12678       // practice that one of the condition inputs to the select is also one of
12679       // the outputs, we currently can't deal with this.
12680       if (User->getOpcode() == ISD::SELECT) {
12681         if (User->getOperand(0) == Inputs[i])
12682           return SDValue();
12683       } else if (User->getOpcode() == ISD::SELECT_CC) {
12684         if (User->getOperand(0) == Inputs[i] ||
12685             User->getOperand(1) == Inputs[i])
12686           return SDValue();
12687       }
12688     }
12689   }
12690 
12691   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12692     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12693                               UE = PromOps[i].getNode()->use_end();
12694          UI != UE; ++UI) {
12695       SDNode *User = *UI;
12696       if (User != N && !Visited.count(User))
12697         return SDValue();
12698 
12699       // Make sure that we're not going to promote the non-output-value
12700       // operand(s) or SELECT or SELECT_CC.
12701       // FIXME: Although we could sometimes handle this, and it does occur in
12702       // practice that one of the condition inputs to the select is also one of
12703       // the outputs, we currently can't deal with this.
12704       if (User->getOpcode() == ISD::SELECT) {
12705         if (User->getOperand(0) == PromOps[i])
12706           return SDValue();
12707       } else if (User->getOpcode() == ISD::SELECT_CC) {
12708         if (User->getOperand(0) == PromOps[i] ||
12709             User->getOperand(1) == PromOps[i])
12710           return SDValue();
12711       }
12712     }
12713   }
12714 
12715   // Replace all inputs with the extension operand.
12716   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12717     // Constants may have users outside the cluster of to-be-promoted nodes,
12718     // and so we need to replace those as we do the promotions.
12719     if (isa<ConstantSDNode>(Inputs[i]))
12720       continue;
12721     else
12722       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12723   }
12724 
12725   std::list<HandleSDNode> PromOpHandles;
12726   for (auto &PromOp : PromOps)
12727     PromOpHandles.emplace_back(PromOp);
12728 
12729   // Replace all operations (these are all the same, but have a different
12730   // (i1) return type). DAG.getNode will validate that the types of
12731   // a binary operator match, so go through the list in reverse so that
12732   // we've likely promoted both operands first. Any intermediate truncations or
12733   // extensions disappear.
12734   while (!PromOpHandles.empty()) {
12735     SDValue PromOp = PromOpHandles.back().getValue();
12736     PromOpHandles.pop_back();
12737 
12738     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12739         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12740         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12741         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12742       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12743           PromOp.getOperand(0).getValueType() != MVT::i1) {
12744         // The operand is not yet ready (see comment below).
12745         PromOpHandles.emplace_front(PromOp);
12746         continue;
12747       }
12748 
12749       SDValue RepValue = PromOp.getOperand(0);
12750       if (isa<ConstantSDNode>(RepValue))
12751         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12752 
12753       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12754       continue;
12755     }
12756 
12757     unsigned C;
12758     switch (PromOp.getOpcode()) {
12759     default:             C = 0; break;
12760     case ISD::SELECT:    C = 1; break;
12761     case ISD::SELECT_CC: C = 2; break;
12762     }
12763 
12764     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12765          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12766         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12767          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12768       // The to-be-promoted operands of this node have not yet been
12769       // promoted (this should be rare because we're going through the
12770       // list backward, but if one of the operands has several users in
12771       // this cluster of to-be-promoted nodes, it is possible).
12772       PromOpHandles.emplace_front(PromOp);
12773       continue;
12774     }
12775 
12776     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12777                                 PromOp.getNode()->op_end());
12778 
12779     // If there are any constant inputs, make sure they're replaced now.
12780     for (unsigned i = 0; i < 2; ++i)
12781       if (isa<ConstantSDNode>(Ops[C+i]))
12782         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12783 
12784     DAG.ReplaceAllUsesOfValueWith(PromOp,
12785       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12786   }
12787 
12788   // Now we're left with the initial truncation itself.
12789   if (N->getOpcode() == ISD::TRUNCATE)
12790     return N->getOperand(0);
12791 
12792   // Otherwise, this is a comparison. The operands to be compared have just
12793   // changed type (to i1), but everything else is the same.
12794   return SDValue(N, 0);
12795 }
12796 
12797 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12798                                                   DAGCombinerInfo &DCI) const {
12799   SelectionDAG &DAG = DCI.DAG;
12800   SDLoc dl(N);
12801 
12802   // If we're tracking CR bits, we need to be careful that we don't have:
12803   //   zext(binary-ops(trunc(x), trunc(y)))
12804   // or
12805   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12806   // such that we're unnecessarily moving things into CR bits that can more
12807   // efficiently stay in GPRs. Note that if we're not certain that the high
12808   // bits are set as required by the final extension, we still may need to do
12809   // some masking to get the proper behavior.
12810 
12811   // This same functionality is important on PPC64 when dealing with
12812   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12813   // the return values of functions. Because it is so similar, it is handled
12814   // here as well.
12815 
12816   if (N->getValueType(0) != MVT::i32 &&
12817       N->getValueType(0) != MVT::i64)
12818     return SDValue();
12819 
12820   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12821         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12822     return SDValue();
12823 
12824   if (N->getOperand(0).getOpcode() != ISD::AND &&
12825       N->getOperand(0).getOpcode() != ISD::OR  &&
12826       N->getOperand(0).getOpcode() != ISD::XOR &&
12827       N->getOperand(0).getOpcode() != ISD::SELECT &&
12828       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12829     return SDValue();
12830 
12831   SmallVector<SDValue, 4> Inputs;
12832   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12833   SmallPtrSet<SDNode *, 16> Visited;
12834 
12835   // Visit all inputs, collect all binary operations (and, or, xor and
12836   // select) that are all fed by truncations.
12837   while (!BinOps.empty()) {
12838     SDValue BinOp = BinOps.back();
12839     BinOps.pop_back();
12840 
12841     if (!Visited.insert(BinOp.getNode()).second)
12842       continue;
12843 
12844     PromOps.push_back(BinOp);
12845 
12846     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12847       // The condition of the select is not promoted.
12848       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12849         continue;
12850       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12851         continue;
12852 
12853       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12854           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12855         Inputs.push_back(BinOp.getOperand(i));
12856       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12857                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12858                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12859                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12860                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12861         BinOps.push_back(BinOp.getOperand(i));
12862       } else {
12863         // We have an input that is not a truncation or another binary
12864         // operation; we'll abort this transformation.
12865         return SDValue();
12866       }
12867     }
12868   }
12869 
12870   // The operands of a select that must be truncated when the select is
12871   // promoted because the operand is actually part of the to-be-promoted set.
12872   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12873 
12874   // Make sure that this is a self-contained cluster of operations (which
12875   // is not quite the same thing as saying that everything has only one
12876   // use).
12877   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12878     if (isa<ConstantSDNode>(Inputs[i]))
12879       continue;
12880 
12881     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12882                               UE = Inputs[i].getNode()->use_end();
12883          UI != UE; ++UI) {
12884       SDNode *User = *UI;
12885       if (User != N && !Visited.count(User))
12886         return SDValue();
12887 
12888       // If we're going to promote the non-output-value operand(s) or SELECT or
12889       // SELECT_CC, record them for truncation.
12890       if (User->getOpcode() == ISD::SELECT) {
12891         if (User->getOperand(0) == Inputs[i])
12892           SelectTruncOp[0].insert(std::make_pair(User,
12893                                     User->getOperand(0).getValueType()));
12894       } else if (User->getOpcode() == ISD::SELECT_CC) {
12895         if (User->getOperand(0) == Inputs[i])
12896           SelectTruncOp[0].insert(std::make_pair(User,
12897                                     User->getOperand(0).getValueType()));
12898         if (User->getOperand(1) == Inputs[i])
12899           SelectTruncOp[1].insert(std::make_pair(User,
12900                                     User->getOperand(1).getValueType()));
12901       }
12902     }
12903   }
12904 
12905   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12906     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12907                               UE = PromOps[i].getNode()->use_end();
12908          UI != UE; ++UI) {
12909       SDNode *User = *UI;
12910       if (User != N && !Visited.count(User))
12911         return SDValue();
12912 
12913       // If we're going to promote the non-output-value operand(s) or SELECT or
12914       // SELECT_CC, record them for truncation.
12915       if (User->getOpcode() == ISD::SELECT) {
12916         if (User->getOperand(0) == PromOps[i])
12917           SelectTruncOp[0].insert(std::make_pair(User,
12918                                     User->getOperand(0).getValueType()));
12919       } else if (User->getOpcode() == ISD::SELECT_CC) {
12920         if (User->getOperand(0) == PromOps[i])
12921           SelectTruncOp[0].insert(std::make_pair(User,
12922                                     User->getOperand(0).getValueType()));
12923         if (User->getOperand(1) == PromOps[i])
12924           SelectTruncOp[1].insert(std::make_pair(User,
12925                                     User->getOperand(1).getValueType()));
12926       }
12927     }
12928   }
12929 
12930   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12931   bool ReallyNeedsExt = false;
12932   if (N->getOpcode() != ISD::ANY_EXTEND) {
12933     // If all of the inputs are not already sign/zero extended, then
12934     // we'll still need to do that at the end.
12935     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12936       if (isa<ConstantSDNode>(Inputs[i]))
12937         continue;
12938 
12939       unsigned OpBits =
12940         Inputs[i].getOperand(0).getValueSizeInBits();
12941       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12942 
12943       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12944            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12945                                   APInt::getHighBitsSet(OpBits,
12946                                                         OpBits-PromBits))) ||
12947           (N->getOpcode() == ISD::SIGN_EXTEND &&
12948            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12949              (OpBits-(PromBits-1)))) {
12950         ReallyNeedsExt = true;
12951         break;
12952       }
12953     }
12954   }
12955 
12956   // Replace all inputs, either with the truncation operand, or a
12957   // truncation or extension to the final output type.
12958   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12959     // Constant inputs need to be replaced with the to-be-promoted nodes that
12960     // use them because they might have users outside of the cluster of
12961     // promoted nodes.
12962     if (isa<ConstantSDNode>(Inputs[i]))
12963       continue;
12964 
12965     SDValue InSrc = Inputs[i].getOperand(0);
12966     if (Inputs[i].getValueType() == N->getValueType(0))
12967       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12968     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12969       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12970         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12971     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12972       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12973         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12974     else
12975       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12976         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12977   }
12978 
12979   std::list<HandleSDNode> PromOpHandles;
12980   for (auto &PromOp : PromOps)
12981     PromOpHandles.emplace_back(PromOp);
12982 
12983   // Replace all operations (these are all the same, but have a different
12984   // (promoted) return type). DAG.getNode will validate that the types of
12985   // a binary operator match, so go through the list in reverse so that
12986   // we've likely promoted both operands first.
12987   while (!PromOpHandles.empty()) {
12988     SDValue PromOp = PromOpHandles.back().getValue();
12989     PromOpHandles.pop_back();
12990 
12991     unsigned C;
12992     switch (PromOp.getOpcode()) {
12993     default:             C = 0; break;
12994     case ISD::SELECT:    C = 1; break;
12995     case ISD::SELECT_CC: C = 2; break;
12996     }
12997 
12998     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12999          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13000         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13001          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13002       // The to-be-promoted operands of this node have not yet been
13003       // promoted (this should be rare because we're going through the
13004       // list backward, but if one of the operands has several users in
13005       // this cluster of to-be-promoted nodes, it is possible).
13006       PromOpHandles.emplace_front(PromOp);
13007       continue;
13008     }
13009 
13010     // For SELECT and SELECT_CC nodes, we do a similar check for any
13011     // to-be-promoted comparison inputs.
13012     if (PromOp.getOpcode() == ISD::SELECT ||
13013         PromOp.getOpcode() == ISD::SELECT_CC) {
13014       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13015            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13016           (SelectTruncOp[1].count(PromOp.getNode()) &&
13017            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13018         PromOpHandles.emplace_front(PromOp);
13019         continue;
13020       }
13021     }
13022 
13023     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13024                                 PromOp.getNode()->op_end());
13025 
13026     // If this node has constant inputs, then they'll need to be promoted here.
13027     for (unsigned i = 0; i < 2; ++i) {
13028       if (!isa<ConstantSDNode>(Ops[C+i]))
13029         continue;
13030       if (Ops[C+i].getValueType() == N->getValueType(0))
13031         continue;
13032 
13033       if (N->getOpcode() == ISD::SIGN_EXTEND)
13034         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13035       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13036         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13037       else
13038         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13039     }
13040 
13041     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13042     // truncate them again to the original value type.
13043     if (PromOp.getOpcode() == ISD::SELECT ||
13044         PromOp.getOpcode() == ISD::SELECT_CC) {
13045       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13046       if (SI0 != SelectTruncOp[0].end())
13047         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13048       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13049       if (SI1 != SelectTruncOp[1].end())
13050         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13051     }
13052 
13053     DAG.ReplaceAllUsesOfValueWith(PromOp,
13054       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13055   }
13056 
13057   // Now we're left with the initial extension itself.
13058   if (!ReallyNeedsExt)
13059     return N->getOperand(0);
13060 
13061   // To zero extend, just mask off everything except for the first bit (in the
13062   // i1 case).
13063   if (N->getOpcode() == ISD::ZERO_EXTEND)
13064     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13065                        DAG.getConstant(APInt::getLowBitsSet(
13066                                          N->getValueSizeInBits(0), PromBits),
13067                                        dl, N->getValueType(0)));
13068 
13069   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13070          "Invalid extension type");
13071   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13072   SDValue ShiftCst =
13073       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13074   return DAG.getNode(
13075       ISD::SRA, dl, N->getValueType(0),
13076       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13077       ShiftCst);
13078 }
13079 
13080 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13081                                         DAGCombinerInfo &DCI) const {
13082   assert(N->getOpcode() == ISD::SETCC &&
13083          "Should be called with a SETCC node");
13084 
13085   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13086   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13087     SDValue LHS = N->getOperand(0);
13088     SDValue RHS = N->getOperand(1);
13089 
13090     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13091     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13092         LHS.hasOneUse())
13093       std::swap(LHS, RHS);
13094 
13095     // x == 0-y --> x+y == 0
13096     // x != 0-y --> x+y != 0
13097     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13098         RHS.hasOneUse()) {
13099       SDLoc DL(N);
13100       SelectionDAG &DAG = DCI.DAG;
13101       EVT VT = N->getValueType(0);
13102       EVT OpVT = LHS.getValueType();
13103       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13104       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13105     }
13106   }
13107 
13108   return DAGCombineTruncBoolExt(N, DCI);
13109 }
13110 
13111 // Is this an extending load from an f32 to an f64?
13112 static bool isFPExtLoad(SDValue Op) {
13113   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13114     return LD->getExtensionType() == ISD::EXTLOAD &&
13115       Op.getValueType() == MVT::f64;
13116   return false;
13117 }
13118 
13119 /// Reduces the number of fp-to-int conversion when building a vector.
13120 ///
13121 /// If this vector is built out of floating to integer conversions,
13122 /// transform it to a vector built out of floating point values followed by a
13123 /// single floating to integer conversion of the vector.
13124 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13125 /// becomes (fptosi (build_vector ($A, $B, ...)))
13126 SDValue PPCTargetLowering::
13127 combineElementTruncationToVectorTruncation(SDNode *N,
13128                                            DAGCombinerInfo &DCI) const {
13129   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13130          "Should be called with a BUILD_VECTOR node");
13131 
13132   SelectionDAG &DAG = DCI.DAG;
13133   SDLoc dl(N);
13134 
13135   SDValue FirstInput = N->getOperand(0);
13136   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13137          "The input operand must be an fp-to-int conversion.");
13138 
13139   // This combine happens after legalization so the fp_to_[su]i nodes are
13140   // already converted to PPCSISD nodes.
13141   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13142   if (FirstConversion == PPCISD::FCTIDZ ||
13143       FirstConversion == PPCISD::FCTIDUZ ||
13144       FirstConversion == PPCISD::FCTIWZ ||
13145       FirstConversion == PPCISD::FCTIWUZ) {
13146     bool IsSplat = true;
13147     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13148       FirstConversion == PPCISD::FCTIWUZ;
13149     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13150     SmallVector<SDValue, 4> Ops;
13151     EVT TargetVT = N->getValueType(0);
13152     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13153       SDValue NextOp = N->getOperand(i);
13154       if (NextOp.getOpcode() != PPCISD::MFVSR)
13155         return SDValue();
13156       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13157       if (NextConversion != FirstConversion)
13158         return SDValue();
13159       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13160       // This is not valid if the input was originally double precision. It is
13161       // also not profitable to do unless this is an extending load in which
13162       // case doing this combine will allow us to combine consecutive loads.
13163       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13164         return SDValue();
13165       if (N->getOperand(i) != FirstInput)
13166         IsSplat = false;
13167     }
13168 
13169     // If this is a splat, we leave it as-is since there will be only a single
13170     // fp-to-int conversion followed by a splat of the integer. This is better
13171     // for 32-bit and smaller ints and neutral for 64-bit ints.
13172     if (IsSplat)
13173       return SDValue();
13174 
13175     // Now that we know we have the right type of node, get its operands
13176     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13177       SDValue In = N->getOperand(i).getOperand(0);
13178       if (Is32Bit) {
13179         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13180         // here, we know that all inputs are extending loads so this is safe).
13181         if (In.isUndef())
13182           Ops.push_back(DAG.getUNDEF(SrcVT));
13183         else {
13184           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13185                                       MVT::f32, In.getOperand(0),
13186                                       DAG.getIntPtrConstant(1, dl));
13187           Ops.push_back(Trunc);
13188         }
13189       } else
13190         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13191     }
13192 
13193     unsigned Opcode;
13194     if (FirstConversion == PPCISD::FCTIDZ ||
13195         FirstConversion == PPCISD::FCTIWZ)
13196       Opcode = ISD::FP_TO_SINT;
13197     else
13198       Opcode = ISD::FP_TO_UINT;
13199 
13200     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13201     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13202     return DAG.getNode(Opcode, dl, TargetVT, BV);
13203   }
13204   return SDValue();
13205 }
13206 
13207 /// Reduce the number of loads when building a vector.
13208 ///
13209 /// Building a vector out of multiple loads can be converted to a load
13210 /// of the vector type if the loads are consecutive. If the loads are
13211 /// consecutive but in descending order, a shuffle is added at the end
13212 /// to reorder the vector.
13213 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13214   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13215          "Should be called with a BUILD_VECTOR node");
13216 
13217   SDLoc dl(N);
13218 
13219   // Return early for non byte-sized type, as they can't be consecutive.
13220   if (!N->getValueType(0).getVectorElementType().isByteSized())
13221     return SDValue();
13222 
13223   bool InputsAreConsecutiveLoads = true;
13224   bool InputsAreReverseConsecutive = true;
13225   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13226   SDValue FirstInput = N->getOperand(0);
13227   bool IsRoundOfExtLoad = false;
13228 
13229   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13230       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13231     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13232     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13233   }
13234   // Not a build vector of (possibly fp_rounded) loads.
13235   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13236       N->getNumOperands() == 1)
13237     return SDValue();
13238 
13239   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13240     // If any inputs are fp_round(extload), they all must be.
13241     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13242       return SDValue();
13243 
13244     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13245       N->getOperand(i);
13246     if (NextInput.getOpcode() != ISD::LOAD)
13247       return SDValue();
13248 
13249     SDValue PreviousInput =
13250       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13251     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13252     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13253 
13254     // If any inputs are fp_round(extload), they all must be.
13255     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13256       return SDValue();
13257 
13258     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13259       InputsAreConsecutiveLoads = false;
13260     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13261       InputsAreReverseConsecutive = false;
13262 
13263     // Exit early if the loads are neither consecutive nor reverse consecutive.
13264     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13265       return SDValue();
13266   }
13267 
13268   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13269          "The loads cannot be both consecutive and reverse consecutive.");
13270 
13271   SDValue FirstLoadOp =
13272     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13273   SDValue LastLoadOp =
13274     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13275                        N->getOperand(N->getNumOperands()-1);
13276 
13277   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13278   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13279   if (InputsAreConsecutiveLoads) {
13280     assert(LD1 && "Input needs to be a LoadSDNode.");
13281     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13282                        LD1->getBasePtr(), LD1->getPointerInfo(),
13283                        LD1->getAlignment());
13284   }
13285   if (InputsAreReverseConsecutive) {
13286     assert(LDL && "Input needs to be a LoadSDNode.");
13287     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13288                                LDL->getBasePtr(), LDL->getPointerInfo(),
13289                                LDL->getAlignment());
13290     SmallVector<int, 16> Ops;
13291     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13292       Ops.push_back(i);
13293 
13294     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13295                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13296   }
13297   return SDValue();
13298 }
13299 
13300 // This function adds the required vector_shuffle needed to get
13301 // the elements of the vector extract in the correct position
13302 // as specified by the CorrectElems encoding.
13303 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13304                                       SDValue Input, uint64_t Elems,
13305                                       uint64_t CorrectElems) {
13306   SDLoc dl(N);
13307 
13308   unsigned NumElems = Input.getValueType().getVectorNumElements();
13309   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13310 
13311   // Knowing the element indices being extracted from the original
13312   // vector and the order in which they're being inserted, just put
13313   // them at element indices required for the instruction.
13314   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13315     if (DAG.getDataLayout().isLittleEndian())
13316       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13317     else
13318       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13319     CorrectElems = CorrectElems >> 8;
13320     Elems = Elems >> 8;
13321   }
13322 
13323   SDValue Shuffle =
13324       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13325                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13326 
13327   EVT VT = N->getValueType(0);
13328   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13329 
13330   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13331                                Input.getValueType().getVectorElementType(),
13332                                VT.getVectorNumElements());
13333   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13334                      DAG.getValueType(ExtVT));
13335 }
13336 
13337 // Look for build vector patterns where input operands come from sign
13338 // extended vector_extract elements of specific indices. If the correct indices
13339 // aren't used, add a vector shuffle to fix up the indices and create
13340 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13341 // during instruction selection.
13342 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13343   // This array encodes the indices that the vector sign extend instructions
13344   // extract from when extending from one type to another for both BE and LE.
13345   // The right nibble of each byte corresponds to the LE incides.
13346   // and the left nibble of each byte corresponds to the BE incides.
13347   // For example: 0x3074B8FC  byte->word
13348   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13349   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13350   // For example: 0x000070F8  byte->double word
13351   // For LE: the allowed indices are: 0x0,0x8
13352   // For BE: the allowed indices are: 0x7,0xF
13353   uint64_t TargetElems[] = {
13354       0x3074B8FC, // b->w
13355       0x000070F8, // b->d
13356       0x10325476, // h->w
13357       0x00003074, // h->d
13358       0x00001032, // w->d
13359   };
13360 
13361   uint64_t Elems = 0;
13362   int Index;
13363   SDValue Input;
13364 
13365   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13366     if (!Op)
13367       return false;
13368     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13369         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13370       return false;
13371 
13372     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13373     // of the right width.
13374     SDValue Extract = Op.getOperand(0);
13375     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13376       Extract = Extract.getOperand(0);
13377     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13378       return false;
13379 
13380     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13381     if (!ExtOp)
13382       return false;
13383 
13384     Index = ExtOp->getZExtValue();
13385     if (Input && Input != Extract.getOperand(0))
13386       return false;
13387 
13388     if (!Input)
13389       Input = Extract.getOperand(0);
13390 
13391     Elems = Elems << 8;
13392     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13393     Elems |= Index;
13394 
13395     return true;
13396   };
13397 
13398   // If the build vector operands aren't sign extended vector extracts,
13399   // of the same input vector, then return.
13400   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13401     if (!isSExtOfVecExtract(N->getOperand(i))) {
13402       return SDValue();
13403     }
13404   }
13405 
13406   // If the vector extract indicies are not correct, add the appropriate
13407   // vector_shuffle.
13408   int TgtElemArrayIdx;
13409   int InputSize = Input.getValueType().getScalarSizeInBits();
13410   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13411   if (InputSize + OutputSize == 40)
13412     TgtElemArrayIdx = 0;
13413   else if (InputSize + OutputSize == 72)
13414     TgtElemArrayIdx = 1;
13415   else if (InputSize + OutputSize == 48)
13416     TgtElemArrayIdx = 2;
13417   else if (InputSize + OutputSize == 80)
13418     TgtElemArrayIdx = 3;
13419   else if (InputSize + OutputSize == 96)
13420     TgtElemArrayIdx = 4;
13421   else
13422     return SDValue();
13423 
13424   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13425   CorrectElems = DAG.getDataLayout().isLittleEndian()
13426                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13427                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13428   if (Elems != CorrectElems) {
13429     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13430   }
13431 
13432   // Regular lowering will catch cases where a shuffle is not needed.
13433   return SDValue();
13434 }
13435 
13436 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13437                                                  DAGCombinerInfo &DCI) const {
13438   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13439          "Should be called with a BUILD_VECTOR node");
13440 
13441   SelectionDAG &DAG = DCI.DAG;
13442   SDLoc dl(N);
13443 
13444   if (!Subtarget.hasVSX())
13445     return SDValue();
13446 
13447   // The target independent DAG combiner will leave a build_vector of
13448   // float-to-int conversions intact. We can generate MUCH better code for
13449   // a float-to-int conversion of a vector of floats.
13450   SDValue FirstInput = N->getOperand(0);
13451   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13452     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13453     if (Reduced)
13454       return Reduced;
13455   }
13456 
13457   // If we're building a vector out of consecutive loads, just load that
13458   // vector type.
13459   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13460   if (Reduced)
13461     return Reduced;
13462 
13463   // If we're building a vector out of extended elements from another vector
13464   // we have P9 vector integer extend instructions. The code assumes legal
13465   // input types (i.e. it can't handle things like v4i16) so do not run before
13466   // legalization.
13467   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13468     Reduced = combineBVOfVecSExt(N, DAG);
13469     if (Reduced)
13470       return Reduced;
13471   }
13472 
13473 
13474   if (N->getValueType(0) != MVT::v2f64)
13475     return SDValue();
13476 
13477   // Looking for:
13478   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13479   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13480       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13481     return SDValue();
13482   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13483       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13484     return SDValue();
13485   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13486     return SDValue();
13487 
13488   SDValue Ext1 = FirstInput.getOperand(0);
13489   SDValue Ext2 = N->getOperand(1).getOperand(0);
13490   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13491      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13492     return SDValue();
13493 
13494   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13495   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13496   if (!Ext1Op || !Ext2Op)
13497     return SDValue();
13498   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13499       Ext1.getOperand(0) != Ext2.getOperand(0))
13500     return SDValue();
13501 
13502   int FirstElem = Ext1Op->getZExtValue();
13503   int SecondElem = Ext2Op->getZExtValue();
13504   int SubvecIdx;
13505   if (FirstElem == 0 && SecondElem == 1)
13506     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13507   else if (FirstElem == 2 && SecondElem == 3)
13508     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13509   else
13510     return SDValue();
13511 
13512   SDValue SrcVec = Ext1.getOperand(0);
13513   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13514     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13515   return DAG.getNode(NodeType, dl, MVT::v2f64,
13516                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13517 }
13518 
13519 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13520                                               DAGCombinerInfo &DCI) const {
13521   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13522           N->getOpcode() == ISD::UINT_TO_FP) &&
13523          "Need an int -> FP conversion node here");
13524 
13525   if (useSoftFloat() || !Subtarget.has64BitSupport())
13526     return SDValue();
13527 
13528   SelectionDAG &DAG = DCI.DAG;
13529   SDLoc dl(N);
13530   SDValue Op(N, 0);
13531 
13532   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13533   // from the hardware.
13534   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13535     return SDValue();
13536   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13537       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13538     return SDValue();
13539 
13540   SDValue FirstOperand(Op.getOperand(0));
13541   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13542     (FirstOperand.getValueType() == MVT::i8 ||
13543      FirstOperand.getValueType() == MVT::i16);
13544   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13545     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13546     bool DstDouble = Op.getValueType() == MVT::f64;
13547     unsigned ConvOp = Signed ?
13548       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13549       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13550     SDValue WidthConst =
13551       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13552                             dl, false);
13553     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13554     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13555     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13556                                          DAG.getVTList(MVT::f64, MVT::Other),
13557                                          Ops, MVT::i8, LDN->getMemOperand());
13558 
13559     // For signed conversion, we need to sign-extend the value in the VSR
13560     if (Signed) {
13561       SDValue ExtOps[] = { Ld, WidthConst };
13562       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13563       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13564     } else
13565       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13566   }
13567 
13568 
13569   // For i32 intermediate values, unfortunately, the conversion functions
13570   // leave the upper 32 bits of the value are undefined. Within the set of
13571   // scalar instructions, we have no method for zero- or sign-extending the
13572   // value. Thus, we cannot handle i32 intermediate values here.
13573   if (Op.getOperand(0).getValueType() == MVT::i32)
13574     return SDValue();
13575 
13576   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13577          "UINT_TO_FP is supported only with FPCVT");
13578 
13579   // If we have FCFIDS, then use it when converting to single-precision.
13580   // Otherwise, convert to double-precision and then round.
13581   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13582                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13583                                                             : PPCISD::FCFIDS)
13584                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13585                                                             : PPCISD::FCFID);
13586   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13587                   ? MVT::f32
13588                   : MVT::f64;
13589 
13590   // If we're converting from a float, to an int, and back to a float again,
13591   // then we don't need the store/load pair at all.
13592   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13593        Subtarget.hasFPCVT()) ||
13594       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13595     SDValue Src = Op.getOperand(0).getOperand(0);
13596     if (Src.getValueType() == MVT::f32) {
13597       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13598       DCI.AddToWorklist(Src.getNode());
13599     } else if (Src.getValueType() != MVT::f64) {
13600       // Make sure that we don't pick up a ppc_fp128 source value.
13601       return SDValue();
13602     }
13603 
13604     unsigned FCTOp =
13605       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13606                                                         PPCISD::FCTIDUZ;
13607 
13608     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13609     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13610 
13611     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13612       FP = DAG.getNode(ISD::FP_ROUND, dl,
13613                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13614       DCI.AddToWorklist(FP.getNode());
13615     }
13616 
13617     return FP;
13618   }
13619 
13620   return SDValue();
13621 }
13622 
13623 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13624 // builtins) into loads with swaps.
13625 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13626                                               DAGCombinerInfo &DCI) const {
13627   SelectionDAG &DAG = DCI.DAG;
13628   SDLoc dl(N);
13629   SDValue Chain;
13630   SDValue Base;
13631   MachineMemOperand *MMO;
13632 
13633   switch (N->getOpcode()) {
13634   default:
13635     llvm_unreachable("Unexpected opcode for little endian VSX load");
13636   case ISD::LOAD: {
13637     LoadSDNode *LD = cast<LoadSDNode>(N);
13638     Chain = LD->getChain();
13639     Base = LD->getBasePtr();
13640     MMO = LD->getMemOperand();
13641     // If the MMO suggests this isn't a load of a full vector, leave
13642     // things alone.  For a built-in, we have to make the change for
13643     // correctness, so if there is a size problem that will be a bug.
13644     if (MMO->getSize() < 16)
13645       return SDValue();
13646     break;
13647   }
13648   case ISD::INTRINSIC_W_CHAIN: {
13649     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13650     Chain = Intrin->getChain();
13651     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13652     // us what we want. Get operand 2 instead.
13653     Base = Intrin->getOperand(2);
13654     MMO = Intrin->getMemOperand();
13655     break;
13656   }
13657   }
13658 
13659   MVT VecTy = N->getValueType(0).getSimpleVT();
13660 
13661   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13662   // aligned and the type is a vector with elements up to 4 bytes
13663   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13664       && VecTy.getScalarSizeInBits() <= 32 ) {
13665     return SDValue();
13666   }
13667 
13668   SDValue LoadOps[] = { Chain, Base };
13669   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13670                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13671                                          LoadOps, MVT::v2f64, MMO);
13672 
13673   DCI.AddToWorklist(Load.getNode());
13674   Chain = Load.getValue(1);
13675   SDValue Swap = DAG.getNode(
13676       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13677   DCI.AddToWorklist(Swap.getNode());
13678 
13679   // Add a bitcast if the resulting load type doesn't match v2f64.
13680   if (VecTy != MVT::v2f64) {
13681     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13682     DCI.AddToWorklist(N.getNode());
13683     // Package {bitcast value, swap's chain} to match Load's shape.
13684     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13685                        N, Swap.getValue(1));
13686   }
13687 
13688   return Swap;
13689 }
13690 
13691 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13692 // builtins) into stores with swaps.
13693 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13694                                                DAGCombinerInfo &DCI) const {
13695   SelectionDAG &DAG = DCI.DAG;
13696   SDLoc dl(N);
13697   SDValue Chain;
13698   SDValue Base;
13699   unsigned SrcOpnd;
13700   MachineMemOperand *MMO;
13701 
13702   switch (N->getOpcode()) {
13703   default:
13704     llvm_unreachable("Unexpected opcode for little endian VSX store");
13705   case ISD::STORE: {
13706     StoreSDNode *ST = cast<StoreSDNode>(N);
13707     Chain = ST->getChain();
13708     Base = ST->getBasePtr();
13709     MMO = ST->getMemOperand();
13710     SrcOpnd = 1;
13711     // If the MMO suggests this isn't a store of a full vector, leave
13712     // things alone.  For a built-in, we have to make the change for
13713     // correctness, so if there is a size problem that will be a bug.
13714     if (MMO->getSize() < 16)
13715       return SDValue();
13716     break;
13717   }
13718   case ISD::INTRINSIC_VOID: {
13719     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13720     Chain = Intrin->getChain();
13721     // Intrin->getBasePtr() oddly does not get what we want.
13722     Base = Intrin->getOperand(3);
13723     MMO = Intrin->getMemOperand();
13724     SrcOpnd = 2;
13725     break;
13726   }
13727   }
13728 
13729   SDValue Src = N->getOperand(SrcOpnd);
13730   MVT VecTy = Src.getValueType().getSimpleVT();
13731 
13732   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13733   // aligned and the type is a vector with elements up to 4 bytes
13734   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13735       && VecTy.getScalarSizeInBits() <= 32 ) {
13736     return SDValue();
13737   }
13738 
13739   // All stores are done as v2f64 and possible bit cast.
13740   if (VecTy != MVT::v2f64) {
13741     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13742     DCI.AddToWorklist(Src.getNode());
13743   }
13744 
13745   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13746                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13747   DCI.AddToWorklist(Swap.getNode());
13748   Chain = Swap.getValue(1);
13749   SDValue StoreOps[] = { Chain, Swap, Base };
13750   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13751                                           DAG.getVTList(MVT::Other),
13752                                           StoreOps, VecTy, MMO);
13753   DCI.AddToWorklist(Store.getNode());
13754   return Store;
13755 }
13756 
13757 // Handle DAG combine for STORE (FP_TO_INT F).
13758 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13759                                                DAGCombinerInfo &DCI) const {
13760 
13761   SelectionDAG &DAG = DCI.DAG;
13762   SDLoc dl(N);
13763   unsigned Opcode = N->getOperand(1).getOpcode();
13764 
13765   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13766          && "Not a FP_TO_INT Instruction!");
13767 
13768   SDValue Val = N->getOperand(1).getOperand(0);
13769   EVT Op1VT = N->getOperand(1).getValueType();
13770   EVT ResVT = Val.getValueType();
13771 
13772   // Floating point types smaller than 32 bits are not legal on Power.
13773   if (ResVT.getScalarSizeInBits() < 32)
13774     return SDValue();
13775 
13776   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13777   bool ValidTypeForStoreFltAsInt =
13778         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13779          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13780 
13781   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13782       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13783     return SDValue();
13784 
13785   // Extend f32 values to f64
13786   if (ResVT.getScalarSizeInBits() == 32) {
13787     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13788     DCI.AddToWorklist(Val.getNode());
13789   }
13790 
13791   // Set signed or unsigned conversion opcode.
13792   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13793                           PPCISD::FP_TO_SINT_IN_VSR :
13794                           PPCISD::FP_TO_UINT_IN_VSR;
13795 
13796   Val = DAG.getNode(ConvOpcode,
13797                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13798   DCI.AddToWorklist(Val.getNode());
13799 
13800   // Set number of bytes being converted.
13801   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13802   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13803                     DAG.getIntPtrConstant(ByteSize, dl, false),
13804                     DAG.getValueType(Op1VT) };
13805 
13806   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13807           DAG.getVTList(MVT::Other), Ops,
13808           cast<StoreSDNode>(N)->getMemoryVT(),
13809           cast<StoreSDNode>(N)->getMemOperand());
13810 
13811   DCI.AddToWorklist(Val.getNode());
13812   return Val;
13813 }
13814 
13815 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13816                                                 LSBaseSDNode *LSBase,
13817                                                 DAGCombinerInfo &DCI) const {
13818   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13819         "Not a reverse memop pattern!");
13820 
13821   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13822     auto Mask = SVN->getMask();
13823     int i = 0;
13824     auto I = Mask.rbegin();
13825     auto E = Mask.rend();
13826 
13827     for (; I != E; ++I) {
13828       if (*I != i)
13829         return false;
13830       i++;
13831     }
13832     return true;
13833   };
13834 
13835   SelectionDAG &DAG = DCI.DAG;
13836   EVT VT = SVN->getValueType(0);
13837 
13838   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13839     return SDValue();
13840 
13841   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13842   // See comment in PPCVSXSwapRemoval.cpp.
13843   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13844   if (!Subtarget.hasP9Vector())
13845     return SDValue();
13846 
13847   if(!IsElementReverse(SVN))
13848     return SDValue();
13849 
13850   if (LSBase->getOpcode() == ISD::LOAD) {
13851     SDLoc dl(SVN);
13852     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13853     return DAG.getMemIntrinsicNode(
13854         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13855         LSBase->getMemoryVT(), LSBase->getMemOperand());
13856   }
13857 
13858   if (LSBase->getOpcode() == ISD::STORE) {
13859     SDLoc dl(LSBase);
13860     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13861                           LSBase->getBasePtr()};
13862     return DAG.getMemIntrinsicNode(
13863         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13864         LSBase->getMemoryVT(), LSBase->getMemOperand());
13865   }
13866 
13867   llvm_unreachable("Expected a load or store node here");
13868 }
13869 
13870 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13871                                              DAGCombinerInfo &DCI) const {
13872   SelectionDAG &DAG = DCI.DAG;
13873   SDLoc dl(N);
13874   switch (N->getOpcode()) {
13875   default: break;
13876   case ISD::ADD:
13877     return combineADD(N, DCI);
13878   case ISD::SHL:
13879     return combineSHL(N, DCI);
13880   case ISD::SRA:
13881     return combineSRA(N, DCI);
13882   case ISD::SRL:
13883     return combineSRL(N, DCI);
13884   case ISD::MUL:
13885     return combineMUL(N, DCI);
13886   case PPCISD::SHL:
13887     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13888         return N->getOperand(0);
13889     break;
13890   case PPCISD::SRL:
13891     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13892         return N->getOperand(0);
13893     break;
13894   case PPCISD::SRA:
13895     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13896       if (C->isNullValue() ||   //  0 >>s V -> 0.
13897           C->isAllOnesValue())    // -1 >>s V -> -1.
13898         return N->getOperand(0);
13899     }
13900     break;
13901   case ISD::SIGN_EXTEND:
13902   case ISD::ZERO_EXTEND:
13903   case ISD::ANY_EXTEND:
13904     return DAGCombineExtBoolTrunc(N, DCI);
13905   case ISD::TRUNCATE:
13906     return combineTRUNCATE(N, DCI);
13907   case ISD::SETCC:
13908     if (SDValue CSCC = combineSetCC(N, DCI))
13909       return CSCC;
13910     LLVM_FALLTHROUGH;
13911   case ISD::SELECT_CC:
13912     return DAGCombineTruncBoolExt(N, DCI);
13913   case ISD::SINT_TO_FP:
13914   case ISD::UINT_TO_FP:
13915     return combineFPToIntToFP(N, DCI);
13916   case ISD::VECTOR_SHUFFLE:
13917     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13918       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13919       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13920     }
13921     break;
13922   case ISD::STORE: {
13923 
13924     EVT Op1VT = N->getOperand(1).getValueType();
13925     unsigned Opcode = N->getOperand(1).getOpcode();
13926 
13927     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13928       SDValue Val= combineStoreFPToInt(N, DCI);
13929       if (Val)
13930         return Val;
13931     }
13932 
13933     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13934       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13935       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13936       if (Val)
13937         return Val;
13938     }
13939 
13940     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13941     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13942         N->getOperand(1).getNode()->hasOneUse() &&
13943         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13944          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13945 
13946       // STBRX can only handle simple types and it makes no sense to store less
13947       // two bytes in byte-reversed order.
13948       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13949       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13950         break;
13951 
13952       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13953       // Do an any-extend to 32-bits if this is a half-word input.
13954       if (BSwapOp.getValueType() == MVT::i16)
13955         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13956 
13957       // If the type of BSWAP operand is wider than stored memory width
13958       // it need to be shifted to the right side before STBRX.
13959       if (Op1VT.bitsGT(mVT)) {
13960         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13961         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13962                               DAG.getConstant(Shift, dl, MVT::i32));
13963         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13964         if (Op1VT == MVT::i64)
13965           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13966       }
13967 
13968       SDValue Ops[] = {
13969         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13970       };
13971       return
13972         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13973                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13974                                 cast<StoreSDNode>(N)->getMemOperand());
13975     }
13976 
13977     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13978     // So it can increase the chance of CSE constant construction.
13979     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13980         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13981       // Need to sign-extended to 64-bits to handle negative values.
13982       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13983       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13984                                     MemVT.getSizeInBits());
13985       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13986 
13987       // DAG.getTruncStore() can't be used here because it doesn't accept
13988       // the general (base + offset) addressing mode.
13989       // So we use UpdateNodeOperands and setTruncatingStore instead.
13990       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13991                              N->getOperand(3));
13992       cast<StoreSDNode>(N)->setTruncatingStore(true);
13993       return SDValue(N, 0);
13994     }
13995 
13996     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13997     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13998     if (Op1VT.isSimple()) {
13999       MVT StoreVT = Op1VT.getSimpleVT();
14000       if (Subtarget.needsSwapsForVSXMemOps() &&
14001           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14002            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14003         return expandVSXStoreForLE(N, DCI);
14004     }
14005     break;
14006   }
14007   case ISD::LOAD: {
14008     LoadSDNode *LD = cast<LoadSDNode>(N);
14009     EVT VT = LD->getValueType(0);
14010 
14011     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14012     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14013     if (VT.isSimple()) {
14014       MVT LoadVT = VT.getSimpleVT();
14015       if (Subtarget.needsSwapsForVSXMemOps() &&
14016           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14017            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14018         return expandVSXLoadForLE(N, DCI);
14019     }
14020 
14021     // We sometimes end up with a 64-bit integer load, from which we extract
14022     // two single-precision floating-point numbers. This happens with
14023     // std::complex<float>, and other similar structures, because of the way we
14024     // canonicalize structure copies. However, if we lack direct moves,
14025     // then the final bitcasts from the extracted integer values to the
14026     // floating-point numbers turn into store/load pairs. Even with direct moves,
14027     // just loading the two floating-point numbers is likely better.
14028     auto ReplaceTwoFloatLoad = [&]() {
14029       if (VT != MVT::i64)
14030         return false;
14031 
14032       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14033           LD->isVolatile())
14034         return false;
14035 
14036       //  We're looking for a sequence like this:
14037       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14038       //      t16: i64 = srl t13, Constant:i32<32>
14039       //    t17: i32 = truncate t16
14040       //  t18: f32 = bitcast t17
14041       //    t19: i32 = truncate t13
14042       //  t20: f32 = bitcast t19
14043 
14044       if (!LD->hasNUsesOfValue(2, 0))
14045         return false;
14046 
14047       auto UI = LD->use_begin();
14048       while (UI.getUse().getResNo() != 0) ++UI;
14049       SDNode *Trunc = *UI++;
14050       while (UI.getUse().getResNo() != 0) ++UI;
14051       SDNode *RightShift = *UI;
14052       if (Trunc->getOpcode() != ISD::TRUNCATE)
14053         std::swap(Trunc, RightShift);
14054 
14055       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14056           Trunc->getValueType(0) != MVT::i32 ||
14057           !Trunc->hasOneUse())
14058         return false;
14059       if (RightShift->getOpcode() != ISD::SRL ||
14060           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14061           RightShift->getConstantOperandVal(1) != 32 ||
14062           !RightShift->hasOneUse())
14063         return false;
14064 
14065       SDNode *Trunc2 = *RightShift->use_begin();
14066       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14067           Trunc2->getValueType(0) != MVT::i32 ||
14068           !Trunc2->hasOneUse())
14069         return false;
14070 
14071       SDNode *Bitcast = *Trunc->use_begin();
14072       SDNode *Bitcast2 = *Trunc2->use_begin();
14073 
14074       if (Bitcast->getOpcode() != ISD::BITCAST ||
14075           Bitcast->getValueType(0) != MVT::f32)
14076         return false;
14077       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14078           Bitcast2->getValueType(0) != MVT::f32)
14079         return false;
14080 
14081       if (Subtarget.isLittleEndian())
14082         std::swap(Bitcast, Bitcast2);
14083 
14084       // Bitcast has the second float (in memory-layout order) and Bitcast2
14085       // has the first one.
14086 
14087       SDValue BasePtr = LD->getBasePtr();
14088       if (LD->isIndexed()) {
14089         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14090                "Non-pre-inc AM on PPC?");
14091         BasePtr =
14092           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14093                       LD->getOffset());
14094       }
14095 
14096       auto MMOFlags =
14097           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14098       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14099                                       LD->getPointerInfo(), LD->getAlignment(),
14100                                       MMOFlags, LD->getAAInfo());
14101       SDValue AddPtr =
14102         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14103                     BasePtr, DAG.getIntPtrConstant(4, dl));
14104       SDValue FloatLoad2 = DAG.getLoad(
14105           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14106           LD->getPointerInfo().getWithOffset(4),
14107           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14108 
14109       if (LD->isIndexed()) {
14110         // Note that DAGCombine should re-form any pre-increment load(s) from
14111         // what is produced here if that makes sense.
14112         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14113       }
14114 
14115       DCI.CombineTo(Bitcast2, FloatLoad);
14116       DCI.CombineTo(Bitcast, FloatLoad2);
14117 
14118       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14119                                     SDValue(FloatLoad2.getNode(), 1));
14120       return true;
14121     };
14122 
14123     if (ReplaceTwoFloatLoad())
14124       return SDValue(N, 0);
14125 
14126     EVT MemVT = LD->getMemoryVT();
14127     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14128     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14129     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14130     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14131     if (LD->isUnindexed() && VT.isVector() &&
14132         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14133           // P8 and later hardware should just use LOAD.
14134           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14135                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14136          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14137           LD->getAlignment() >= ScalarABIAlignment)) &&
14138         LD->getAlignment() < ABIAlignment) {
14139       // This is a type-legal unaligned Altivec or QPX load.
14140       SDValue Chain = LD->getChain();
14141       SDValue Ptr = LD->getBasePtr();
14142       bool isLittleEndian = Subtarget.isLittleEndian();
14143 
14144       // This implements the loading of unaligned vectors as described in
14145       // the venerable Apple Velocity Engine overview. Specifically:
14146       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14147       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14148       //
14149       // The general idea is to expand a sequence of one or more unaligned
14150       // loads into an alignment-based permutation-control instruction (lvsl
14151       // or lvsr), a series of regular vector loads (which always truncate
14152       // their input address to an aligned address), and a series of
14153       // permutations.  The results of these permutations are the requested
14154       // loaded values.  The trick is that the last "extra" load is not taken
14155       // from the address you might suspect (sizeof(vector) bytes after the
14156       // last requested load), but rather sizeof(vector) - 1 bytes after the
14157       // last requested vector. The point of this is to avoid a page fault if
14158       // the base address happened to be aligned. This works because if the
14159       // base address is aligned, then adding less than a full vector length
14160       // will cause the last vector in the sequence to be (re)loaded.
14161       // Otherwise, the next vector will be fetched as you might suspect was
14162       // necessary.
14163 
14164       // We might be able to reuse the permutation generation from
14165       // a different base address offset from this one by an aligned amount.
14166       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14167       // optimization later.
14168       Intrinsic::ID Intr, IntrLD, IntrPerm;
14169       MVT PermCntlTy, PermTy, LDTy;
14170       if (Subtarget.hasAltivec()) {
14171         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14172                                  Intrinsic::ppc_altivec_lvsl;
14173         IntrLD = Intrinsic::ppc_altivec_lvx;
14174         IntrPerm = Intrinsic::ppc_altivec_vperm;
14175         PermCntlTy = MVT::v16i8;
14176         PermTy = MVT::v4i32;
14177         LDTy = MVT::v4i32;
14178       } else {
14179         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14180                                        Intrinsic::ppc_qpx_qvlpcls;
14181         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14182                                        Intrinsic::ppc_qpx_qvlfs;
14183         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14184         PermCntlTy = MVT::v4f64;
14185         PermTy = MVT::v4f64;
14186         LDTy = MemVT.getSimpleVT();
14187       }
14188 
14189       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14190 
14191       // Create the new MMO for the new base load. It is like the original MMO,
14192       // but represents an area in memory almost twice the vector size centered
14193       // on the original address. If the address is unaligned, we might start
14194       // reading up to (sizeof(vector)-1) bytes below the address of the
14195       // original unaligned load.
14196       MachineFunction &MF = DAG.getMachineFunction();
14197       MachineMemOperand *BaseMMO =
14198         MF.getMachineMemOperand(LD->getMemOperand(),
14199                                 -(long)MemVT.getStoreSize()+1,
14200                                 2*MemVT.getStoreSize()-1);
14201 
14202       // Create the new base load.
14203       SDValue LDXIntID =
14204           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14205       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14206       SDValue BaseLoad =
14207         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14208                                 DAG.getVTList(PermTy, MVT::Other),
14209                                 BaseLoadOps, LDTy, BaseMMO);
14210 
14211       // Note that the value of IncOffset (which is provided to the next
14212       // load's pointer info offset value, and thus used to calculate the
14213       // alignment), and the value of IncValue (which is actually used to
14214       // increment the pointer value) are different! This is because we
14215       // require the next load to appear to be aligned, even though it
14216       // is actually offset from the base pointer by a lesser amount.
14217       int IncOffset = VT.getSizeInBits() / 8;
14218       int IncValue = IncOffset;
14219 
14220       // Walk (both up and down) the chain looking for another load at the real
14221       // (aligned) offset (the alignment of the other load does not matter in
14222       // this case). If found, then do not use the offset reduction trick, as
14223       // that will prevent the loads from being later combined (as they would
14224       // otherwise be duplicates).
14225       if (!findConsecutiveLoad(LD, DAG))
14226         --IncValue;
14227 
14228       SDValue Increment =
14229           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14230       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14231 
14232       MachineMemOperand *ExtraMMO =
14233         MF.getMachineMemOperand(LD->getMemOperand(),
14234                                 1, 2*MemVT.getStoreSize()-1);
14235       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14236       SDValue ExtraLoad =
14237         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14238                                 DAG.getVTList(PermTy, MVT::Other),
14239                                 ExtraLoadOps, LDTy, ExtraMMO);
14240 
14241       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14242         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14243 
14244       // Because vperm has a big-endian bias, we must reverse the order
14245       // of the input vectors and complement the permute control vector
14246       // when generating little endian code.  We have already handled the
14247       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14248       // and ExtraLoad here.
14249       SDValue Perm;
14250       if (isLittleEndian)
14251         Perm = BuildIntrinsicOp(IntrPerm,
14252                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14253       else
14254         Perm = BuildIntrinsicOp(IntrPerm,
14255                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14256 
14257       if (VT != PermTy)
14258         Perm = Subtarget.hasAltivec() ?
14259                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14260                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14261                                DAG.getTargetConstant(1, dl, MVT::i64));
14262                                // second argument is 1 because this rounding
14263                                // is always exact.
14264 
14265       // The output of the permutation is our loaded result, the TokenFactor is
14266       // our new chain.
14267       DCI.CombineTo(N, Perm, TF);
14268       return SDValue(N, 0);
14269     }
14270     }
14271     break;
14272     case ISD::INTRINSIC_WO_CHAIN: {
14273       bool isLittleEndian = Subtarget.isLittleEndian();
14274       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14275       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14276                                            : Intrinsic::ppc_altivec_lvsl);
14277       if ((IID == Intr ||
14278            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14279            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14280         N->getOperand(1)->getOpcode() == ISD::ADD) {
14281         SDValue Add = N->getOperand(1);
14282 
14283         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14284                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14285 
14286         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14287                                   APInt::getAllOnesValue(Bits /* alignment */)
14288                                       .zext(Add.getScalarValueSizeInBits()))) {
14289           SDNode *BasePtr = Add->getOperand(0).getNode();
14290           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14291                                     UE = BasePtr->use_end();
14292                UI != UE; ++UI) {
14293             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14294                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14295               // We've found another LVSL/LVSR, and this address is an aligned
14296               // multiple of that one. The results will be the same, so use the
14297               // one we've just found instead.
14298 
14299               return SDValue(*UI, 0);
14300             }
14301           }
14302         }
14303 
14304         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14305           SDNode *BasePtr = Add->getOperand(0).getNode();
14306           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14307                UE = BasePtr->use_end(); UI != UE; ++UI) {
14308             if (UI->getOpcode() == ISD::ADD &&
14309                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14310                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14311                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14312                 (1ULL << Bits) == 0) {
14313               SDNode *OtherAdd = *UI;
14314               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14315                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14316                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14317                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14318                   return SDValue(*VI, 0);
14319                 }
14320               }
14321             }
14322           }
14323         }
14324       }
14325 
14326       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14327       // Expose the vabsduw/h/b opportunity for down stream
14328       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14329           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14330            IID == Intrinsic::ppc_altivec_vmaxsh ||
14331            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14332         SDValue V1 = N->getOperand(1);
14333         SDValue V2 = N->getOperand(2);
14334         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14335              V1.getSimpleValueType() == MVT::v8i16 ||
14336              V1.getSimpleValueType() == MVT::v16i8) &&
14337             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14338           // (0-a, a)
14339           if (V1.getOpcode() == ISD::SUB &&
14340               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14341               V1.getOperand(1) == V2) {
14342             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14343           }
14344           // (a, 0-a)
14345           if (V2.getOpcode() == ISD::SUB &&
14346               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14347               V2.getOperand(1) == V1) {
14348             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14349           }
14350           // (x-y, y-x)
14351           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14352               V1.getOperand(0) == V2.getOperand(1) &&
14353               V1.getOperand(1) == V2.getOperand(0)) {
14354             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14355           }
14356         }
14357       }
14358     }
14359 
14360     break;
14361   case ISD::INTRINSIC_W_CHAIN:
14362     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14363     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14364     if (Subtarget.needsSwapsForVSXMemOps()) {
14365       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14366       default:
14367         break;
14368       case Intrinsic::ppc_vsx_lxvw4x:
14369       case Intrinsic::ppc_vsx_lxvd2x:
14370         return expandVSXLoadForLE(N, DCI);
14371       }
14372     }
14373     break;
14374   case ISD::INTRINSIC_VOID:
14375     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14376     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14377     if (Subtarget.needsSwapsForVSXMemOps()) {
14378       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14379       default:
14380         break;
14381       case Intrinsic::ppc_vsx_stxvw4x:
14382       case Intrinsic::ppc_vsx_stxvd2x:
14383         return expandVSXStoreForLE(N, DCI);
14384       }
14385     }
14386     break;
14387   case ISD::BSWAP:
14388     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14389     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14390         N->getOperand(0).hasOneUse() &&
14391         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14392          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14393           N->getValueType(0) == MVT::i64))) {
14394       SDValue Load = N->getOperand(0);
14395       LoadSDNode *LD = cast<LoadSDNode>(Load);
14396       // Create the byte-swapping load.
14397       SDValue Ops[] = {
14398         LD->getChain(),    // Chain
14399         LD->getBasePtr(),  // Ptr
14400         DAG.getValueType(N->getValueType(0)) // VT
14401       };
14402       SDValue BSLoad =
14403         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14404                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14405                                               MVT::i64 : MVT::i32, MVT::Other),
14406                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14407 
14408       // If this is an i16 load, insert the truncate.
14409       SDValue ResVal = BSLoad;
14410       if (N->getValueType(0) == MVT::i16)
14411         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14412 
14413       // First, combine the bswap away.  This makes the value produced by the
14414       // load dead.
14415       DCI.CombineTo(N, ResVal);
14416 
14417       // Next, combine the load away, we give it a bogus result value but a real
14418       // chain result.  The result value is dead because the bswap is dead.
14419       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14420 
14421       // Return N so it doesn't get rechecked!
14422       return SDValue(N, 0);
14423     }
14424     break;
14425   case PPCISD::VCMP:
14426     // If a VCMPo node already exists with exactly the same operands as this
14427     // node, use its result instead of this node (VCMPo computes both a CR6 and
14428     // a normal output).
14429     //
14430     if (!N->getOperand(0).hasOneUse() &&
14431         !N->getOperand(1).hasOneUse() &&
14432         !N->getOperand(2).hasOneUse()) {
14433 
14434       // Scan all of the users of the LHS, looking for VCMPo's that match.
14435       SDNode *VCMPoNode = nullptr;
14436 
14437       SDNode *LHSN = N->getOperand(0).getNode();
14438       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14439            UI != E; ++UI)
14440         if (UI->getOpcode() == PPCISD::VCMPo &&
14441             UI->getOperand(1) == N->getOperand(1) &&
14442             UI->getOperand(2) == N->getOperand(2) &&
14443             UI->getOperand(0) == N->getOperand(0)) {
14444           VCMPoNode = *UI;
14445           break;
14446         }
14447 
14448       // If there is no VCMPo node, or if the flag value has a single use, don't
14449       // transform this.
14450       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14451         break;
14452 
14453       // Look at the (necessarily single) use of the flag value.  If it has a
14454       // chain, this transformation is more complex.  Note that multiple things
14455       // could use the value result, which we should ignore.
14456       SDNode *FlagUser = nullptr;
14457       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14458            FlagUser == nullptr; ++UI) {
14459         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14460         SDNode *User = *UI;
14461         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14462           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14463             FlagUser = User;
14464             break;
14465           }
14466         }
14467       }
14468 
14469       // If the user is a MFOCRF instruction, we know this is safe.
14470       // Otherwise we give up for right now.
14471       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14472         return SDValue(VCMPoNode, 0);
14473     }
14474     break;
14475   case ISD::BRCOND: {
14476     SDValue Cond = N->getOperand(1);
14477     SDValue Target = N->getOperand(2);
14478 
14479     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14480         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14481           Intrinsic::loop_decrement) {
14482 
14483       // We now need to make the intrinsic dead (it cannot be instruction
14484       // selected).
14485       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14486       assert(Cond.getNode()->hasOneUse() &&
14487              "Counter decrement has more than one use");
14488 
14489       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14490                          N->getOperand(0), Target);
14491     }
14492   }
14493   break;
14494   case ISD::BR_CC: {
14495     // If this is a branch on an altivec predicate comparison, lower this so
14496     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14497     // lowering is done pre-legalize, because the legalizer lowers the predicate
14498     // compare down to code that is difficult to reassemble.
14499     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14500     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14501 
14502     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14503     // value. If so, pass-through the AND to get to the intrinsic.
14504     if (LHS.getOpcode() == ISD::AND &&
14505         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14506         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14507           Intrinsic::loop_decrement &&
14508         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14509         !isNullConstant(LHS.getOperand(1)))
14510       LHS = LHS.getOperand(0);
14511 
14512     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14513         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14514           Intrinsic::loop_decrement &&
14515         isa<ConstantSDNode>(RHS)) {
14516       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14517              "Counter decrement comparison is not EQ or NE");
14518 
14519       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14520       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14521                     (CC == ISD::SETNE && !Val);
14522 
14523       // We now need to make the intrinsic dead (it cannot be instruction
14524       // selected).
14525       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14526       assert(LHS.getNode()->hasOneUse() &&
14527              "Counter decrement has more than one use");
14528 
14529       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14530                          N->getOperand(0), N->getOperand(4));
14531     }
14532 
14533     int CompareOpc;
14534     bool isDot;
14535 
14536     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14537         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14538         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14539       assert(isDot && "Can't compare against a vector result!");
14540 
14541       // If this is a comparison against something other than 0/1, then we know
14542       // that the condition is never/always true.
14543       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14544       if (Val != 0 && Val != 1) {
14545         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14546           return N->getOperand(0);
14547         // Always !=, turn it into an unconditional branch.
14548         return DAG.getNode(ISD::BR, dl, MVT::Other,
14549                            N->getOperand(0), N->getOperand(4));
14550       }
14551 
14552       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14553 
14554       // Create the PPCISD altivec 'dot' comparison node.
14555       SDValue Ops[] = {
14556         LHS.getOperand(2),  // LHS of compare
14557         LHS.getOperand(3),  // RHS of compare
14558         DAG.getConstant(CompareOpc, dl, MVT::i32)
14559       };
14560       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14561       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14562 
14563       // Unpack the result based on how the target uses it.
14564       PPC::Predicate CompOpc;
14565       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14566       default:  // Can't happen, don't crash on invalid number though.
14567       case 0:   // Branch on the value of the EQ bit of CR6.
14568         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14569         break;
14570       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14571         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14572         break;
14573       case 2:   // Branch on the value of the LT bit of CR6.
14574         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14575         break;
14576       case 3:   // Branch on the inverted value of the LT bit of CR6.
14577         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14578         break;
14579       }
14580 
14581       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14582                          DAG.getConstant(CompOpc, dl, MVT::i32),
14583                          DAG.getRegister(PPC::CR6, MVT::i32),
14584                          N->getOperand(4), CompNode.getValue(1));
14585     }
14586     break;
14587   }
14588   case ISD::BUILD_VECTOR:
14589     return DAGCombineBuildVector(N, DCI);
14590   case ISD::ABS:
14591     return combineABS(N, DCI);
14592   case ISD::VSELECT:
14593     return combineVSelect(N, DCI);
14594   }
14595 
14596   return SDValue();
14597 }
14598 
14599 SDValue
14600 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14601                                  SelectionDAG &DAG,
14602                                  SmallVectorImpl<SDNode *> &Created) const {
14603   // fold (sdiv X, pow2)
14604   EVT VT = N->getValueType(0);
14605   if (VT == MVT::i64 && !Subtarget.isPPC64())
14606     return SDValue();
14607   if ((VT != MVT::i32 && VT != MVT::i64) ||
14608       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14609     return SDValue();
14610 
14611   SDLoc DL(N);
14612   SDValue N0 = N->getOperand(0);
14613 
14614   bool IsNegPow2 = (-Divisor).isPowerOf2();
14615   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14616   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14617 
14618   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14619   Created.push_back(Op.getNode());
14620 
14621   if (IsNegPow2) {
14622     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14623     Created.push_back(Op.getNode());
14624   }
14625 
14626   return Op;
14627 }
14628 
14629 //===----------------------------------------------------------------------===//
14630 // Inline Assembly Support
14631 //===----------------------------------------------------------------------===//
14632 
14633 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14634                                                       KnownBits &Known,
14635                                                       const APInt &DemandedElts,
14636                                                       const SelectionDAG &DAG,
14637                                                       unsigned Depth) const {
14638   Known.resetAll();
14639   switch (Op.getOpcode()) {
14640   default: break;
14641   case PPCISD::LBRX: {
14642     // lhbrx is known to have the top bits cleared out.
14643     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14644       Known.Zero = 0xFFFF0000;
14645     break;
14646   }
14647   case ISD::INTRINSIC_WO_CHAIN: {
14648     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14649     default: break;
14650     case Intrinsic::ppc_altivec_vcmpbfp_p:
14651     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14652     case Intrinsic::ppc_altivec_vcmpequb_p:
14653     case Intrinsic::ppc_altivec_vcmpequh_p:
14654     case Intrinsic::ppc_altivec_vcmpequw_p:
14655     case Intrinsic::ppc_altivec_vcmpequd_p:
14656     case Intrinsic::ppc_altivec_vcmpgefp_p:
14657     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14658     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14659     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14660     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14661     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14662     case Intrinsic::ppc_altivec_vcmpgtub_p:
14663     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14664     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14665     case Intrinsic::ppc_altivec_vcmpgtud_p:
14666       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14667       break;
14668     }
14669   }
14670   }
14671 }
14672 
14673 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14674   switch (Subtarget.getCPUDirective()) {
14675   default: break;
14676   case PPC::DIR_970:
14677   case PPC::DIR_PWR4:
14678   case PPC::DIR_PWR5:
14679   case PPC::DIR_PWR5X:
14680   case PPC::DIR_PWR6:
14681   case PPC::DIR_PWR6X:
14682   case PPC::DIR_PWR7:
14683   case PPC::DIR_PWR8:
14684   case PPC::DIR_PWR9:
14685   case PPC::DIR_PWR_FUTURE: {
14686     if (!ML)
14687       break;
14688 
14689     if (!DisableInnermostLoopAlign32) {
14690       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14691       // so that we can decrease cache misses and branch-prediction misses.
14692       // Actual alignment of the loop will depend on the hotness check and other
14693       // logic in alignBlocks.
14694       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14695         return Align(32);
14696     }
14697 
14698     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14699 
14700     // For small loops (between 5 and 8 instructions), align to a 32-byte
14701     // boundary so that the entire loop fits in one instruction-cache line.
14702     uint64_t LoopSize = 0;
14703     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14704       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14705         LoopSize += TII->getInstSizeInBytes(*J);
14706         if (LoopSize > 32)
14707           break;
14708       }
14709 
14710     if (LoopSize > 16 && LoopSize <= 32)
14711       return Align(32);
14712 
14713     break;
14714   }
14715   }
14716 
14717   return TargetLowering::getPrefLoopAlignment(ML);
14718 }
14719 
14720 /// getConstraintType - Given a constraint, return the type of
14721 /// constraint it is for this target.
14722 PPCTargetLowering::ConstraintType
14723 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14724   if (Constraint.size() == 1) {
14725     switch (Constraint[0]) {
14726     default: break;
14727     case 'b':
14728     case 'r':
14729     case 'f':
14730     case 'd':
14731     case 'v':
14732     case 'y':
14733       return C_RegisterClass;
14734     case 'Z':
14735       // FIXME: While Z does indicate a memory constraint, it specifically
14736       // indicates an r+r address (used in conjunction with the 'y' modifier
14737       // in the replacement string). Currently, we're forcing the base
14738       // register to be r0 in the asm printer (which is interpreted as zero)
14739       // and forming the complete address in the second register. This is
14740       // suboptimal.
14741       return C_Memory;
14742     }
14743   } else if (Constraint == "wc") { // individual CR bits.
14744     return C_RegisterClass;
14745   } else if (Constraint == "wa" || Constraint == "wd" ||
14746              Constraint == "wf" || Constraint == "ws" ||
14747              Constraint == "wi" || Constraint == "ww") {
14748     return C_RegisterClass; // VSX registers.
14749   }
14750   return TargetLowering::getConstraintType(Constraint);
14751 }
14752 
14753 /// Examine constraint type and operand type and determine a weight value.
14754 /// This object must already have been set up with the operand type
14755 /// and the current alternative constraint selected.
14756 TargetLowering::ConstraintWeight
14757 PPCTargetLowering::getSingleConstraintMatchWeight(
14758     AsmOperandInfo &info, const char *constraint) const {
14759   ConstraintWeight weight = CW_Invalid;
14760   Value *CallOperandVal = info.CallOperandVal;
14761     // If we don't have a value, we can't do a match,
14762     // but allow it at the lowest weight.
14763   if (!CallOperandVal)
14764     return CW_Default;
14765   Type *type = CallOperandVal->getType();
14766 
14767   // Look at the constraint type.
14768   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14769     return CW_Register; // an individual CR bit.
14770   else if ((StringRef(constraint) == "wa" ||
14771             StringRef(constraint) == "wd" ||
14772             StringRef(constraint) == "wf") &&
14773            type->isVectorTy())
14774     return CW_Register;
14775   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14776     return CW_Register; // just hold 64-bit integers data.
14777   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14778     return CW_Register;
14779   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14780     return CW_Register;
14781 
14782   switch (*constraint) {
14783   default:
14784     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14785     break;
14786   case 'b':
14787     if (type->isIntegerTy())
14788       weight = CW_Register;
14789     break;
14790   case 'f':
14791     if (type->isFloatTy())
14792       weight = CW_Register;
14793     break;
14794   case 'd':
14795     if (type->isDoubleTy())
14796       weight = CW_Register;
14797     break;
14798   case 'v':
14799     if (type->isVectorTy())
14800       weight = CW_Register;
14801     break;
14802   case 'y':
14803     weight = CW_Register;
14804     break;
14805   case 'Z':
14806     weight = CW_Memory;
14807     break;
14808   }
14809   return weight;
14810 }
14811 
14812 std::pair<unsigned, const TargetRegisterClass *>
14813 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14814                                                 StringRef Constraint,
14815                                                 MVT VT) const {
14816   if (Constraint.size() == 1) {
14817     // GCC RS6000 Constraint Letters
14818     switch (Constraint[0]) {
14819     case 'b':   // R1-R31
14820       if (VT == MVT::i64 && Subtarget.isPPC64())
14821         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14822       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14823     case 'r':   // R0-R31
14824       if (VT == MVT::i64 && Subtarget.isPPC64())
14825         return std::make_pair(0U, &PPC::G8RCRegClass);
14826       return std::make_pair(0U, &PPC::GPRCRegClass);
14827     // 'd' and 'f' constraints are both defined to be "the floating point
14828     // registers", where one is for 32-bit and the other for 64-bit. We don't
14829     // really care overly much here so just give them all the same reg classes.
14830     case 'd':
14831     case 'f':
14832       if (Subtarget.hasSPE()) {
14833         if (VT == MVT::f32 || VT == MVT::i32)
14834           return std::make_pair(0U, &PPC::GPRCRegClass);
14835         if (VT == MVT::f64 || VT == MVT::i64)
14836           return std::make_pair(0U, &PPC::SPERCRegClass);
14837       } else {
14838         if (VT == MVT::f32 || VT == MVT::i32)
14839           return std::make_pair(0U, &PPC::F4RCRegClass);
14840         if (VT == MVT::f64 || VT == MVT::i64)
14841           return std::make_pair(0U, &PPC::F8RCRegClass);
14842         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14843           return std::make_pair(0U, &PPC::QFRCRegClass);
14844         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14845           return std::make_pair(0U, &PPC::QSRCRegClass);
14846       }
14847       break;
14848     case 'v':
14849       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14850         return std::make_pair(0U, &PPC::QFRCRegClass);
14851       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14852         return std::make_pair(0U, &PPC::QSRCRegClass);
14853       if (Subtarget.hasAltivec())
14854         return std::make_pair(0U, &PPC::VRRCRegClass);
14855       break;
14856     case 'y':   // crrc
14857       return std::make_pair(0U, &PPC::CRRCRegClass);
14858     }
14859   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14860     // An individual CR bit.
14861     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14862   } else if ((Constraint == "wa" || Constraint == "wd" ||
14863              Constraint == "wf" || Constraint == "wi") &&
14864              Subtarget.hasVSX()) {
14865     return std::make_pair(0U, &PPC::VSRCRegClass);
14866   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14867     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14868       return std::make_pair(0U, &PPC::VSSRCRegClass);
14869     else
14870       return std::make_pair(0U, &PPC::VSFRCRegClass);
14871   }
14872 
14873   // If we name a VSX register, we can't defer to the base class because it
14874   // will not recognize the correct register (their names will be VSL{0-31}
14875   // and V{0-31} so they won't match). So we match them here.
14876   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14877     int VSNum = atoi(Constraint.data() + 3);
14878     assert(VSNum >= 0 && VSNum <= 63 &&
14879            "Attempted to access a vsr out of range");
14880     if (VSNum < 32)
14881       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14882     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14883   }
14884   std::pair<unsigned, const TargetRegisterClass *> R =
14885       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14886 
14887   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14888   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14889   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14890   // register.
14891   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14892   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14893   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14894       PPC::GPRCRegClass.contains(R.first))
14895     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14896                             PPC::sub_32, &PPC::G8RCRegClass),
14897                           &PPC::G8RCRegClass);
14898 
14899   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14900   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14901     R.first = PPC::CR0;
14902     R.second = &PPC::CRRCRegClass;
14903   }
14904 
14905   return R;
14906 }
14907 
14908 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14909 /// vector.  If it is invalid, don't add anything to Ops.
14910 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14911                                                      std::string &Constraint,
14912                                                      std::vector<SDValue>&Ops,
14913                                                      SelectionDAG &DAG) const {
14914   SDValue Result;
14915 
14916   // Only support length 1 constraints.
14917   if (Constraint.length() > 1) return;
14918 
14919   char Letter = Constraint[0];
14920   switch (Letter) {
14921   default: break;
14922   case 'I':
14923   case 'J':
14924   case 'K':
14925   case 'L':
14926   case 'M':
14927   case 'N':
14928   case 'O':
14929   case 'P': {
14930     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14931     if (!CST) return; // Must be an immediate to match.
14932     SDLoc dl(Op);
14933     int64_t Value = CST->getSExtValue();
14934     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14935                          // numbers are printed as such.
14936     switch (Letter) {
14937     default: llvm_unreachable("Unknown constraint letter!");
14938     case 'I':  // "I" is a signed 16-bit constant.
14939       if (isInt<16>(Value))
14940         Result = DAG.getTargetConstant(Value, dl, TCVT);
14941       break;
14942     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14943       if (isShiftedUInt<16, 16>(Value))
14944         Result = DAG.getTargetConstant(Value, dl, TCVT);
14945       break;
14946     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14947       if (isShiftedInt<16, 16>(Value))
14948         Result = DAG.getTargetConstant(Value, dl, TCVT);
14949       break;
14950     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14951       if (isUInt<16>(Value))
14952         Result = DAG.getTargetConstant(Value, dl, TCVT);
14953       break;
14954     case 'M':  // "M" is a constant that is greater than 31.
14955       if (Value > 31)
14956         Result = DAG.getTargetConstant(Value, dl, TCVT);
14957       break;
14958     case 'N':  // "N" is a positive constant that is an exact power of two.
14959       if (Value > 0 && isPowerOf2_64(Value))
14960         Result = DAG.getTargetConstant(Value, dl, TCVT);
14961       break;
14962     case 'O':  // "O" is the constant zero.
14963       if (Value == 0)
14964         Result = DAG.getTargetConstant(Value, dl, TCVT);
14965       break;
14966     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14967       if (isInt<16>(-Value))
14968         Result = DAG.getTargetConstant(Value, dl, TCVT);
14969       break;
14970     }
14971     break;
14972   }
14973   }
14974 
14975   if (Result.getNode()) {
14976     Ops.push_back(Result);
14977     return;
14978   }
14979 
14980   // Handle standard constraint letters.
14981   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14982 }
14983 
14984 // isLegalAddressingMode - Return true if the addressing mode represented
14985 // by AM is legal for this target, for a load/store of the specified type.
14986 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14987                                               const AddrMode &AM, Type *Ty,
14988                                               unsigned AS, Instruction *I) const {
14989   // PPC does not allow r+i addressing modes for vectors!
14990   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14991     return false;
14992 
14993   // PPC allows a sign-extended 16-bit immediate field.
14994   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14995     return false;
14996 
14997   // No global is ever allowed as a base.
14998   if (AM.BaseGV)
14999     return false;
15000 
15001   // PPC only support r+r,
15002   switch (AM.Scale) {
15003   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15004     break;
15005   case 1:
15006     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15007       return false;
15008     // Otherwise we have r+r or r+i.
15009     break;
15010   case 2:
15011     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15012       return false;
15013     // Allow 2*r as r+r.
15014     break;
15015   default:
15016     // No other scales are supported.
15017     return false;
15018   }
15019 
15020   return true;
15021 }
15022 
15023 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15024                                            SelectionDAG &DAG) const {
15025   MachineFunction &MF = DAG.getMachineFunction();
15026   MachineFrameInfo &MFI = MF.getFrameInfo();
15027   MFI.setReturnAddressIsTaken(true);
15028 
15029   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15030     return SDValue();
15031 
15032   SDLoc dl(Op);
15033   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15034 
15035   // Make sure the function does not optimize away the store of the RA to
15036   // the stack.
15037   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15038   FuncInfo->setLRStoreRequired();
15039   bool isPPC64 = Subtarget.isPPC64();
15040   auto PtrVT = getPointerTy(MF.getDataLayout());
15041 
15042   if (Depth > 0) {
15043     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15044     SDValue Offset =
15045         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15046                         isPPC64 ? MVT::i64 : MVT::i32);
15047     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15048                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15049                        MachinePointerInfo());
15050   }
15051 
15052   // Just load the return address off the stack.
15053   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15054   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15055                      MachinePointerInfo());
15056 }
15057 
15058 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15059                                           SelectionDAG &DAG) const {
15060   SDLoc dl(Op);
15061   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15062 
15063   MachineFunction &MF = DAG.getMachineFunction();
15064   MachineFrameInfo &MFI = MF.getFrameInfo();
15065   MFI.setFrameAddressIsTaken(true);
15066 
15067   EVT PtrVT = getPointerTy(MF.getDataLayout());
15068   bool isPPC64 = PtrVT == MVT::i64;
15069 
15070   // Naked functions never have a frame pointer, and so we use r1. For all
15071   // other functions, this decision must be delayed until during PEI.
15072   unsigned FrameReg;
15073   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15074     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15075   else
15076     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15077 
15078   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15079                                          PtrVT);
15080   while (Depth--)
15081     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15082                             FrameAddr, MachinePointerInfo());
15083   return FrameAddr;
15084 }
15085 
15086 // FIXME? Maybe this could be a TableGen attribute on some registers and
15087 // this table could be generated automatically from RegInfo.
15088 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15089                                               const MachineFunction &MF) const {
15090   bool isPPC64 = Subtarget.isPPC64();
15091 
15092   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15093   if (!is64Bit && VT != LLT::scalar(32))
15094     report_fatal_error("Invalid register global variable type");
15095 
15096   Register Reg = StringSwitch<Register>(RegName)
15097                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15098                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15099                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15100                      .Default(Register());
15101 
15102   if (Reg)
15103     return Reg;
15104   report_fatal_error("Invalid register name global variable");
15105 }
15106 
15107 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15108   // 32-bit SVR4 ABI access everything as got-indirect.
15109   if (Subtarget.is32BitELFABI())
15110     return true;
15111 
15112   // AIX accesses everything indirectly through the TOC, which is similar to
15113   // the GOT.
15114   if (Subtarget.isAIXABI())
15115     return true;
15116 
15117   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15118   // If it is small or large code model, module locals are accessed
15119   // indirectly by loading their address from .toc/.got.
15120   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15121     return true;
15122 
15123   // JumpTable and BlockAddress are accessed as got-indirect.
15124   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15125     return true;
15126 
15127   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15128     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15129 
15130   return false;
15131 }
15132 
15133 bool
15134 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15135   // The PowerPC target isn't yet aware of offsets.
15136   return false;
15137 }
15138 
15139 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15140                                            const CallInst &I,
15141                                            MachineFunction &MF,
15142                                            unsigned Intrinsic) const {
15143   switch (Intrinsic) {
15144   case Intrinsic::ppc_qpx_qvlfd:
15145   case Intrinsic::ppc_qpx_qvlfs:
15146   case Intrinsic::ppc_qpx_qvlfcd:
15147   case Intrinsic::ppc_qpx_qvlfcs:
15148   case Intrinsic::ppc_qpx_qvlfiwa:
15149   case Intrinsic::ppc_qpx_qvlfiwz:
15150   case Intrinsic::ppc_altivec_lvx:
15151   case Intrinsic::ppc_altivec_lvxl:
15152   case Intrinsic::ppc_altivec_lvebx:
15153   case Intrinsic::ppc_altivec_lvehx:
15154   case Intrinsic::ppc_altivec_lvewx:
15155   case Intrinsic::ppc_vsx_lxvd2x:
15156   case Intrinsic::ppc_vsx_lxvw4x: {
15157     EVT VT;
15158     switch (Intrinsic) {
15159     case Intrinsic::ppc_altivec_lvebx:
15160       VT = MVT::i8;
15161       break;
15162     case Intrinsic::ppc_altivec_lvehx:
15163       VT = MVT::i16;
15164       break;
15165     case Intrinsic::ppc_altivec_lvewx:
15166       VT = MVT::i32;
15167       break;
15168     case Intrinsic::ppc_vsx_lxvd2x:
15169       VT = MVT::v2f64;
15170       break;
15171     case Intrinsic::ppc_qpx_qvlfd:
15172       VT = MVT::v4f64;
15173       break;
15174     case Intrinsic::ppc_qpx_qvlfs:
15175       VT = MVT::v4f32;
15176       break;
15177     case Intrinsic::ppc_qpx_qvlfcd:
15178       VT = MVT::v2f64;
15179       break;
15180     case Intrinsic::ppc_qpx_qvlfcs:
15181       VT = MVT::v2f32;
15182       break;
15183     default:
15184       VT = MVT::v4i32;
15185       break;
15186     }
15187 
15188     Info.opc = ISD::INTRINSIC_W_CHAIN;
15189     Info.memVT = VT;
15190     Info.ptrVal = I.getArgOperand(0);
15191     Info.offset = -VT.getStoreSize()+1;
15192     Info.size = 2*VT.getStoreSize()-1;
15193     Info.align = Align(1);
15194     Info.flags = MachineMemOperand::MOLoad;
15195     return true;
15196   }
15197   case Intrinsic::ppc_qpx_qvlfda:
15198   case Intrinsic::ppc_qpx_qvlfsa:
15199   case Intrinsic::ppc_qpx_qvlfcda:
15200   case Intrinsic::ppc_qpx_qvlfcsa:
15201   case Intrinsic::ppc_qpx_qvlfiwaa:
15202   case Intrinsic::ppc_qpx_qvlfiwza: {
15203     EVT VT;
15204     switch (Intrinsic) {
15205     case Intrinsic::ppc_qpx_qvlfda:
15206       VT = MVT::v4f64;
15207       break;
15208     case Intrinsic::ppc_qpx_qvlfsa:
15209       VT = MVT::v4f32;
15210       break;
15211     case Intrinsic::ppc_qpx_qvlfcda:
15212       VT = MVT::v2f64;
15213       break;
15214     case Intrinsic::ppc_qpx_qvlfcsa:
15215       VT = MVT::v2f32;
15216       break;
15217     default:
15218       VT = MVT::v4i32;
15219       break;
15220     }
15221 
15222     Info.opc = ISD::INTRINSIC_W_CHAIN;
15223     Info.memVT = VT;
15224     Info.ptrVal = I.getArgOperand(0);
15225     Info.offset = 0;
15226     Info.size = VT.getStoreSize();
15227     Info.align = Align(1);
15228     Info.flags = MachineMemOperand::MOLoad;
15229     return true;
15230   }
15231   case Intrinsic::ppc_qpx_qvstfd:
15232   case Intrinsic::ppc_qpx_qvstfs:
15233   case Intrinsic::ppc_qpx_qvstfcd:
15234   case Intrinsic::ppc_qpx_qvstfcs:
15235   case Intrinsic::ppc_qpx_qvstfiw:
15236   case Intrinsic::ppc_altivec_stvx:
15237   case Intrinsic::ppc_altivec_stvxl:
15238   case Intrinsic::ppc_altivec_stvebx:
15239   case Intrinsic::ppc_altivec_stvehx:
15240   case Intrinsic::ppc_altivec_stvewx:
15241   case Intrinsic::ppc_vsx_stxvd2x:
15242   case Intrinsic::ppc_vsx_stxvw4x: {
15243     EVT VT;
15244     switch (Intrinsic) {
15245     case Intrinsic::ppc_altivec_stvebx:
15246       VT = MVT::i8;
15247       break;
15248     case Intrinsic::ppc_altivec_stvehx:
15249       VT = MVT::i16;
15250       break;
15251     case Intrinsic::ppc_altivec_stvewx:
15252       VT = MVT::i32;
15253       break;
15254     case Intrinsic::ppc_vsx_stxvd2x:
15255       VT = MVT::v2f64;
15256       break;
15257     case Intrinsic::ppc_qpx_qvstfd:
15258       VT = MVT::v4f64;
15259       break;
15260     case Intrinsic::ppc_qpx_qvstfs:
15261       VT = MVT::v4f32;
15262       break;
15263     case Intrinsic::ppc_qpx_qvstfcd:
15264       VT = MVT::v2f64;
15265       break;
15266     case Intrinsic::ppc_qpx_qvstfcs:
15267       VT = MVT::v2f32;
15268       break;
15269     default:
15270       VT = MVT::v4i32;
15271       break;
15272     }
15273 
15274     Info.opc = ISD::INTRINSIC_VOID;
15275     Info.memVT = VT;
15276     Info.ptrVal = I.getArgOperand(1);
15277     Info.offset = -VT.getStoreSize()+1;
15278     Info.size = 2*VT.getStoreSize()-1;
15279     Info.align = Align(1);
15280     Info.flags = MachineMemOperand::MOStore;
15281     return true;
15282   }
15283   case Intrinsic::ppc_qpx_qvstfda:
15284   case Intrinsic::ppc_qpx_qvstfsa:
15285   case Intrinsic::ppc_qpx_qvstfcda:
15286   case Intrinsic::ppc_qpx_qvstfcsa:
15287   case Intrinsic::ppc_qpx_qvstfiwa: {
15288     EVT VT;
15289     switch (Intrinsic) {
15290     case Intrinsic::ppc_qpx_qvstfda:
15291       VT = MVT::v4f64;
15292       break;
15293     case Intrinsic::ppc_qpx_qvstfsa:
15294       VT = MVT::v4f32;
15295       break;
15296     case Intrinsic::ppc_qpx_qvstfcda:
15297       VT = MVT::v2f64;
15298       break;
15299     case Intrinsic::ppc_qpx_qvstfcsa:
15300       VT = MVT::v2f32;
15301       break;
15302     default:
15303       VT = MVT::v4i32;
15304       break;
15305     }
15306 
15307     Info.opc = ISD::INTRINSIC_VOID;
15308     Info.memVT = VT;
15309     Info.ptrVal = I.getArgOperand(1);
15310     Info.offset = 0;
15311     Info.size = VT.getStoreSize();
15312     Info.align = Align(1);
15313     Info.flags = MachineMemOperand::MOStore;
15314     return true;
15315   }
15316   default:
15317     break;
15318   }
15319 
15320   return false;
15321 }
15322 
15323 /// It returns EVT::Other if the type should be determined using generic
15324 /// target-independent logic.
15325 EVT PPCTargetLowering::getOptimalMemOpType(
15326     const MemOp &Op, const AttributeList &FuncAttributes) const {
15327   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15328     // When expanding a memset, require at least two QPX instructions to cover
15329     // the cost of loading the value to be stored from the constant pool.
15330     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15331         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15332         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15333       return MVT::v4f64;
15334     }
15335 
15336     // We should use Altivec/VSX loads and stores when available. For unaligned
15337     // addresses, unaligned VSX loads are only fast starting with the P8.
15338     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15339         (Op.isAligned(Align(16)) ||
15340          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15341       return MVT::v4i32;
15342   }
15343 
15344   if (Subtarget.isPPC64()) {
15345     return MVT::i64;
15346   }
15347 
15348   return MVT::i32;
15349 }
15350 
15351 /// Returns true if it is beneficial to convert a load of a constant
15352 /// to just the constant itself.
15353 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15354                                                           Type *Ty) const {
15355   assert(Ty->isIntegerTy());
15356 
15357   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15358   return !(BitSize == 0 || BitSize > 64);
15359 }
15360 
15361 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15362   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15363     return false;
15364   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15365   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15366   return NumBits1 == 64 && NumBits2 == 32;
15367 }
15368 
15369 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15370   if (!VT1.isInteger() || !VT2.isInteger())
15371     return false;
15372   unsigned NumBits1 = VT1.getSizeInBits();
15373   unsigned NumBits2 = VT2.getSizeInBits();
15374   return NumBits1 == 64 && NumBits2 == 32;
15375 }
15376 
15377 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15378   // Generally speaking, zexts are not free, but they are free when they can be
15379   // folded with other operations.
15380   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15381     EVT MemVT = LD->getMemoryVT();
15382     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15383          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15384         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15385          LD->getExtensionType() == ISD::ZEXTLOAD))
15386       return true;
15387   }
15388 
15389   // FIXME: Add other cases...
15390   //  - 32-bit shifts with a zext to i64
15391   //  - zext after ctlz, bswap, etc.
15392   //  - zext after and by a constant mask
15393 
15394   return TargetLowering::isZExtFree(Val, VT2);
15395 }
15396 
15397 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15398   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15399          "invalid fpext types");
15400   // Extending to float128 is not free.
15401   if (DestVT == MVT::f128)
15402     return false;
15403   return true;
15404 }
15405 
15406 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15407   return isInt<16>(Imm) || isUInt<16>(Imm);
15408 }
15409 
15410 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15411   return isInt<16>(Imm) || isUInt<16>(Imm);
15412 }
15413 
15414 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15415                                                        unsigned,
15416                                                        unsigned,
15417                                                        MachineMemOperand::Flags,
15418                                                        bool *Fast) const {
15419   if (DisablePPCUnaligned)
15420     return false;
15421 
15422   // PowerPC supports unaligned memory access for simple non-vector types.
15423   // Although accessing unaligned addresses is not as efficient as accessing
15424   // aligned addresses, it is generally more efficient than manual expansion,
15425   // and generally only traps for software emulation when crossing page
15426   // boundaries.
15427 
15428   if (!VT.isSimple())
15429     return false;
15430 
15431   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15432     return false;
15433 
15434   if (VT.getSimpleVT().isVector()) {
15435     if (Subtarget.hasVSX()) {
15436       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15437           VT != MVT::v4f32 && VT != MVT::v4i32)
15438         return false;
15439     } else {
15440       return false;
15441     }
15442   }
15443 
15444   if (VT == MVT::ppcf128)
15445     return false;
15446 
15447   if (Fast)
15448     *Fast = true;
15449 
15450   return true;
15451 }
15452 
15453 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15454                                                    EVT VT) const {
15455   return isFMAFasterThanFMulAndFAdd(
15456       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15457 }
15458 
15459 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15460                                                    Type *Ty) const {
15461   switch (Ty->getScalarType()->getTypeID()) {
15462   case Type::FloatTyID:
15463   case Type::DoubleTyID:
15464     return true;
15465   case Type::FP128TyID:
15466     return EnableQuadPrecision && Subtarget.hasP9Vector();
15467   default:
15468     return false;
15469   }
15470 }
15471 
15472 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15473 // FIXME: add more patterns which are profitable to hoist.
15474 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15475   if (I->getOpcode() != Instruction::FMul)
15476     return true;
15477 
15478   if (!I->hasOneUse())
15479     return true;
15480 
15481   Instruction *User = I->user_back();
15482   assert(User && "A single use instruction with no uses.");
15483 
15484   if (User->getOpcode() != Instruction::FSub &&
15485       User->getOpcode() != Instruction::FAdd)
15486     return true;
15487 
15488   const TargetOptions &Options = getTargetMachine().Options;
15489   const Function *F = I->getFunction();
15490   const DataLayout &DL = F->getParent()->getDataLayout();
15491   Type *Ty = User->getOperand(0)->getType();
15492 
15493   return !(
15494       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15495       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15496       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15497 }
15498 
15499 const MCPhysReg *
15500 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15501   // LR is a callee-save register, but we must treat it as clobbered by any call
15502   // site. Hence we include LR in the scratch registers, which are in turn added
15503   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15504   // to CTR, which is used by any indirect call.
15505   static const MCPhysReg ScratchRegs[] = {
15506     PPC::X12, PPC::LR8, PPC::CTR8, 0
15507   };
15508 
15509   return ScratchRegs;
15510 }
15511 
15512 unsigned PPCTargetLowering::getExceptionPointerRegister(
15513     const Constant *PersonalityFn) const {
15514   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15515 }
15516 
15517 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15518     const Constant *PersonalityFn) const {
15519   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15520 }
15521 
15522 bool
15523 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15524                      EVT VT , unsigned DefinedValues) const {
15525   if (VT == MVT::v2i64)
15526     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15527 
15528   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15529     return true;
15530 
15531   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15532 }
15533 
15534 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15535   if (DisableILPPref || Subtarget.enableMachineScheduler())
15536     return TargetLowering::getSchedulingPreference(N);
15537 
15538   return Sched::ILP;
15539 }
15540 
15541 // Create a fast isel object.
15542 FastISel *
15543 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15544                                   const TargetLibraryInfo *LibInfo) const {
15545   return PPC::createFastISel(FuncInfo, LibInfo);
15546 }
15547 
15548 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15549   if (!Subtarget.isPPC64()) return;
15550 
15551   // Update IsSplitCSR in PPCFunctionInfo
15552   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15553   PFI->setIsSplitCSR(true);
15554 }
15555 
15556 void PPCTargetLowering::insertCopiesSplitCSR(
15557   MachineBasicBlock *Entry,
15558   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15559   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15560   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15561   if (!IStart)
15562     return;
15563 
15564   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15565   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15566   MachineBasicBlock::iterator MBBI = Entry->begin();
15567   for (const MCPhysReg *I = IStart; *I; ++I) {
15568     const TargetRegisterClass *RC = nullptr;
15569     if (PPC::G8RCRegClass.contains(*I))
15570       RC = &PPC::G8RCRegClass;
15571     else if (PPC::F8RCRegClass.contains(*I))
15572       RC = &PPC::F8RCRegClass;
15573     else if (PPC::CRRCRegClass.contains(*I))
15574       RC = &PPC::CRRCRegClass;
15575     else if (PPC::VRRCRegClass.contains(*I))
15576       RC = &PPC::VRRCRegClass;
15577     else
15578       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15579 
15580     Register NewVR = MRI->createVirtualRegister(RC);
15581     // Create copy from CSR to a virtual register.
15582     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15583     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15584     // nounwind. If we want to generalize this later, we may need to emit
15585     // CFI pseudo-instructions.
15586     assert(Entry->getParent()->getFunction().hasFnAttribute(
15587              Attribute::NoUnwind) &&
15588            "Function should be nounwind in insertCopiesSplitCSR!");
15589     Entry->addLiveIn(*I);
15590     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15591       .addReg(*I);
15592 
15593     // Insert the copy-back instructions right before the terminator.
15594     for (auto *Exit : Exits)
15595       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15596               TII->get(TargetOpcode::COPY), *I)
15597         .addReg(NewVR);
15598   }
15599 }
15600 
15601 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15602 bool PPCTargetLowering::useLoadStackGuardNode() const {
15603   if (!Subtarget.isTargetLinux())
15604     return TargetLowering::useLoadStackGuardNode();
15605   return true;
15606 }
15607 
15608 // Override to disable global variable loading on Linux.
15609 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15610   if (!Subtarget.isTargetLinux())
15611     return TargetLowering::insertSSPDeclarations(M);
15612 }
15613 
15614 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15615                                      bool ForCodeSize) const {
15616   if (!VT.isSimple() || !Subtarget.hasVSX())
15617     return false;
15618 
15619   switch(VT.getSimpleVT().SimpleTy) {
15620   default:
15621     // For FP types that are currently not supported by PPC backend, return
15622     // false. Examples: f16, f80.
15623     return false;
15624   case MVT::f32:
15625   case MVT::f64:
15626   case MVT::ppcf128:
15627     return Imm.isPosZero();
15628   }
15629 }
15630 
15631 // For vector shift operation op, fold
15632 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15633 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15634                                   SelectionDAG &DAG) {
15635   SDValue N0 = N->getOperand(0);
15636   SDValue N1 = N->getOperand(1);
15637   EVT VT = N0.getValueType();
15638   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15639   unsigned Opcode = N->getOpcode();
15640   unsigned TargetOpcode;
15641 
15642   switch (Opcode) {
15643   default:
15644     llvm_unreachable("Unexpected shift operation");
15645   case ISD::SHL:
15646     TargetOpcode = PPCISD::SHL;
15647     break;
15648   case ISD::SRL:
15649     TargetOpcode = PPCISD::SRL;
15650     break;
15651   case ISD::SRA:
15652     TargetOpcode = PPCISD::SRA;
15653     break;
15654   }
15655 
15656   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15657       N1->getOpcode() == ISD::AND)
15658     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15659       if (Mask->getZExtValue() == OpSizeInBits - 1)
15660         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15661 
15662   return SDValue();
15663 }
15664 
15665 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15666   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15667     return Value;
15668 
15669   SDValue N0 = N->getOperand(0);
15670   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15671   if (!Subtarget.isISA3_0() ||
15672       N0.getOpcode() != ISD::SIGN_EXTEND ||
15673       N0.getOperand(0).getValueType() != MVT::i32 ||
15674       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15675     return SDValue();
15676 
15677   // We can't save an operation here if the value is already extended, and
15678   // the existing shift is easier to combine.
15679   SDValue ExtsSrc = N0.getOperand(0);
15680   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15681       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15682     return SDValue();
15683 
15684   SDLoc DL(N0);
15685   SDValue ShiftBy = SDValue(CN1, 0);
15686   // We want the shift amount to be i32 on the extswli, but the shift could
15687   // have an i64.
15688   if (ShiftBy.getValueType() == MVT::i64)
15689     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15690 
15691   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15692                          ShiftBy);
15693 }
15694 
15695 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15696   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15697     return Value;
15698 
15699   return SDValue();
15700 }
15701 
15702 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15703   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15704     return Value;
15705 
15706   return SDValue();
15707 }
15708 
15709 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15710 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15711 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15712 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15713 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15714                                  const PPCSubtarget &Subtarget) {
15715   if (!Subtarget.isPPC64())
15716     return SDValue();
15717 
15718   SDValue LHS = N->getOperand(0);
15719   SDValue RHS = N->getOperand(1);
15720 
15721   auto isZextOfCompareWithConstant = [](SDValue Op) {
15722     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15723         Op.getValueType() != MVT::i64)
15724       return false;
15725 
15726     SDValue Cmp = Op.getOperand(0);
15727     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15728         Cmp.getOperand(0).getValueType() != MVT::i64)
15729       return false;
15730 
15731     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15732       int64_t NegConstant = 0 - Constant->getSExtValue();
15733       // Due to the limitations of the addi instruction,
15734       // -C is required to be [-32768, 32767].
15735       return isInt<16>(NegConstant);
15736     }
15737 
15738     return false;
15739   };
15740 
15741   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15742   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15743 
15744   // If there is a pattern, canonicalize a zext operand to the RHS.
15745   if (LHSHasPattern && !RHSHasPattern)
15746     std::swap(LHS, RHS);
15747   else if (!LHSHasPattern && !RHSHasPattern)
15748     return SDValue();
15749 
15750   SDLoc DL(N);
15751   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15752   SDValue Cmp = RHS.getOperand(0);
15753   SDValue Z = Cmp.getOperand(0);
15754   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15755 
15756   assert(Constant && "Constant Should not be a null pointer.");
15757   int64_t NegConstant = 0 - Constant->getSExtValue();
15758 
15759   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15760   default: break;
15761   case ISD::SETNE: {
15762     //                                 when C == 0
15763     //                             --> addze X, (addic Z, -1).carry
15764     //                            /
15765     // add X, (zext(setne Z, C))--
15766     //                            \    when -32768 <= -C <= 32767 && C != 0
15767     //                             --> addze X, (addic (addi Z, -C), -1).carry
15768     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15769                               DAG.getConstant(NegConstant, DL, MVT::i64));
15770     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15771     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15772                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15773     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15774                        SDValue(Addc.getNode(), 1));
15775     }
15776   case ISD::SETEQ: {
15777     //                                 when C == 0
15778     //                             --> addze X, (subfic Z, 0).carry
15779     //                            /
15780     // add X, (zext(sete  Z, C))--
15781     //                            \    when -32768 <= -C <= 32767 && C != 0
15782     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15783     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15784                               DAG.getConstant(NegConstant, DL, MVT::i64));
15785     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15786     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15787                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15788     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15789                        SDValue(Subc.getNode(), 1));
15790     }
15791   }
15792 
15793   return SDValue();
15794 }
15795 
15796 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15797   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15798     return Value;
15799 
15800   return SDValue();
15801 }
15802 
15803 // Detect TRUNCATE operations on bitcasts of float128 values.
15804 // What we are looking for here is the situtation where we extract a subset
15805 // of bits from a 128 bit float.
15806 // This can be of two forms:
15807 // 1) BITCAST of f128 feeding TRUNCATE
15808 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15809 // The reason this is required is because we do not have a legal i128 type
15810 // and so we want to prevent having to store the f128 and then reload part
15811 // of it.
15812 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15813                                            DAGCombinerInfo &DCI) const {
15814   // If we are using CRBits then try that first.
15815   if (Subtarget.useCRBits()) {
15816     // Check if CRBits did anything and return that if it did.
15817     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15818       return CRTruncValue;
15819   }
15820 
15821   SDLoc dl(N);
15822   SDValue Op0 = N->getOperand(0);
15823 
15824   // Looking for a truncate of i128 to i64.
15825   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15826     return SDValue();
15827 
15828   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15829 
15830   // SRL feeding TRUNCATE.
15831   if (Op0.getOpcode() == ISD::SRL) {
15832     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15833     // The right shift has to be by 64 bits.
15834     if (!ConstNode || ConstNode->getZExtValue() != 64)
15835       return SDValue();
15836 
15837     // Switch the element number to extract.
15838     EltToExtract = EltToExtract ? 0 : 1;
15839     // Update Op0 past the SRL.
15840     Op0 = Op0.getOperand(0);
15841   }
15842 
15843   // BITCAST feeding a TRUNCATE possibly via SRL.
15844   if (Op0.getOpcode() == ISD::BITCAST &&
15845       Op0.getValueType() == MVT::i128 &&
15846       Op0.getOperand(0).getValueType() == MVT::f128) {
15847     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15848     return DCI.DAG.getNode(
15849         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15850         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15851   }
15852   return SDValue();
15853 }
15854 
15855 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15856   SelectionDAG &DAG = DCI.DAG;
15857 
15858   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15859   if (!ConstOpOrElement)
15860     return SDValue();
15861 
15862   // An imul is usually smaller than the alternative sequence for legal type.
15863   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15864       isOperationLegal(ISD::MUL, N->getValueType(0)))
15865     return SDValue();
15866 
15867   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15868     switch (this->Subtarget.getCPUDirective()) {
15869     default:
15870       // TODO: enhance the condition for subtarget before pwr8
15871       return false;
15872     case PPC::DIR_PWR8:
15873       //  type        mul     add    shl
15874       // scalar        4       1      1
15875       // vector        7       2      2
15876       return true;
15877     case PPC::DIR_PWR9:
15878     case PPC::DIR_PWR_FUTURE:
15879       //  type        mul     add    shl
15880       // scalar        5       2      2
15881       // vector        7       2      2
15882 
15883       // The cycle RATIO of related operations are showed as a table above.
15884       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15885       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15886       // are 4, it is always profitable; but for 3 instrs patterns
15887       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15888       // So we should only do it for vector type.
15889       return IsAddOne && IsNeg ? VT.isVector() : true;
15890     }
15891   };
15892 
15893   EVT VT = N->getValueType(0);
15894   SDLoc DL(N);
15895 
15896   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15897   bool IsNeg = MulAmt.isNegative();
15898   APInt MulAmtAbs = MulAmt.abs();
15899 
15900   if ((MulAmtAbs - 1).isPowerOf2()) {
15901     // (mul x, 2^N + 1) => (add (shl x, N), x)
15902     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15903 
15904     if (!IsProfitable(IsNeg, true, VT))
15905       return SDValue();
15906 
15907     SDValue Op0 = N->getOperand(0);
15908     SDValue Op1 =
15909         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15910                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15911     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15912 
15913     if (!IsNeg)
15914       return Res;
15915 
15916     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15917   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15918     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15919     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15920 
15921     if (!IsProfitable(IsNeg, false, VT))
15922       return SDValue();
15923 
15924     SDValue Op0 = N->getOperand(0);
15925     SDValue Op1 =
15926         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15927                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15928 
15929     if (!IsNeg)
15930       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15931     else
15932       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15933 
15934   } else {
15935     return SDValue();
15936   }
15937 }
15938 
15939 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15940   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15941   if (!Subtarget.is64BitELFABI())
15942     return false;
15943 
15944   // If not a tail call then no need to proceed.
15945   if (!CI->isTailCall())
15946     return false;
15947 
15948   // If sibling calls have been disabled and tail-calls aren't guaranteed
15949   // there is no reason to duplicate.
15950   auto &TM = getTargetMachine();
15951   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15952     return false;
15953 
15954   // Can't tail call a function called indirectly, or if it has variadic args.
15955   const Function *Callee = CI->getCalledFunction();
15956   if (!Callee || Callee->isVarArg())
15957     return false;
15958 
15959   // Make sure the callee and caller calling conventions are eligible for tco.
15960   const Function *Caller = CI->getParent()->getParent();
15961   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15962                                            CI->getCallingConv()))
15963       return false;
15964 
15965   // If the function is local then we have a good chance at tail-calling it
15966   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15967 }
15968 
15969 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15970   if (!Subtarget.hasVSX())
15971     return false;
15972   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15973     return true;
15974   return VT == MVT::f32 || VT == MVT::f64 ||
15975     VT == MVT::v4f32 || VT == MVT::v2f64;
15976 }
15977 
15978 bool PPCTargetLowering::
15979 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15980   const Value *Mask = AndI.getOperand(1);
15981   // If the mask is suitable for andi. or andis. we should sink the and.
15982   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15983     // Can't handle constants wider than 64-bits.
15984     if (CI->getBitWidth() > 64)
15985       return false;
15986     int64_t ConstVal = CI->getZExtValue();
15987     return isUInt<16>(ConstVal) ||
15988       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15989   }
15990 
15991   // For non-constant masks, we can always use the record-form and.
15992   return true;
15993 }
15994 
15995 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15996 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15997 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15998 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15999 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16000 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16001   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16002   assert(Subtarget.hasP9Altivec() &&
16003          "Only combine this when P9 altivec supported!");
16004   EVT VT = N->getValueType(0);
16005   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16006     return SDValue();
16007 
16008   SelectionDAG &DAG = DCI.DAG;
16009   SDLoc dl(N);
16010   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16011     // Even for signed integers, if it's known to be positive (as signed
16012     // integer) due to zero-extended inputs.
16013     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16014     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16015     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16016          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16017         (SubOpcd1 == ISD::ZERO_EXTEND ||
16018          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16019       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16020                          N->getOperand(0)->getOperand(0),
16021                          N->getOperand(0)->getOperand(1),
16022                          DAG.getTargetConstant(0, dl, MVT::i32));
16023     }
16024 
16025     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16026     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16027         N->getOperand(0).hasOneUse()) {
16028       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16029                          N->getOperand(0)->getOperand(0),
16030                          N->getOperand(0)->getOperand(1),
16031                          DAG.getTargetConstant(1, dl, MVT::i32));
16032     }
16033   }
16034 
16035   return SDValue();
16036 }
16037 
16038 // For type v4i32/v8ii16/v16i8, transform
16039 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16040 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16041 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16042 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16043 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16044                                           DAGCombinerInfo &DCI) const {
16045   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16046   assert(Subtarget.hasP9Altivec() &&
16047          "Only combine this when P9 altivec supported!");
16048 
16049   SelectionDAG &DAG = DCI.DAG;
16050   SDLoc dl(N);
16051   SDValue Cond = N->getOperand(0);
16052   SDValue TrueOpnd = N->getOperand(1);
16053   SDValue FalseOpnd = N->getOperand(2);
16054   EVT VT = N->getOperand(1).getValueType();
16055 
16056   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16057       FalseOpnd.getOpcode() != ISD::SUB)
16058     return SDValue();
16059 
16060   // ABSD only available for type v4i32/v8i16/v16i8
16061   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16062     return SDValue();
16063 
16064   // At least to save one more dependent computation
16065   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16066     return SDValue();
16067 
16068   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16069 
16070   // Can only handle unsigned comparison here
16071   switch (CC) {
16072   default:
16073     return SDValue();
16074   case ISD::SETUGT:
16075   case ISD::SETUGE:
16076     break;
16077   case ISD::SETULT:
16078   case ISD::SETULE:
16079     std::swap(TrueOpnd, FalseOpnd);
16080     break;
16081   }
16082 
16083   SDValue CmpOpnd1 = Cond.getOperand(0);
16084   SDValue CmpOpnd2 = Cond.getOperand(1);
16085 
16086   // SETCC CmpOpnd1 CmpOpnd2 cond
16087   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16088   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16089   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16090       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16091       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16092       FalseOpnd.getOperand(1) == CmpOpnd1) {
16093     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16094                        CmpOpnd1, CmpOpnd2,
16095                        DAG.getTargetConstant(0, dl, MVT::i32));
16096   }
16097 
16098   return SDValue();
16099 }
16100