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   if (Subtarget.isISA3_0()) {
171     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
172     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
174     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
175   } else {
176     // No extending loads from f16 or HW conversions back and forth.
177     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
178     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
179     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
180     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
181     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
182     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
183     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
184     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
185   }
186 
187   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
188 
189   // PowerPC has pre-inc load and store's.
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
200   if (!Subtarget.hasSPE()) {
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
202     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
204     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
205   }
206 
207   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
208   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
209   for (MVT VT : ScalarIntVTs) {
210     setOperationAction(ISD::ADDC, VT, Legal);
211     setOperationAction(ISD::ADDE, VT, Legal);
212     setOperationAction(ISD::SUBC, VT, Legal);
213     setOperationAction(ISD::SUBE, VT, Legal);
214   }
215 
216   if (Subtarget.useCRBits()) {
217     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
218 
219     if (isPPC64 || Subtarget.hasFPCVT()) {
220       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
221       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
222                          isPPC64 ? MVT::i64 : MVT::i32);
223       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
224       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
225                         isPPC64 ? MVT::i64 : MVT::i32);
226     } else {
227       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
228       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
229     }
230 
231     // PowerPC does not support direct load/store of condition registers.
232     setOperationAction(ISD::LOAD, MVT::i1, Custom);
233     setOperationAction(ISD::STORE, MVT::i1, Custom);
234 
235     // FIXME: Remove this once the ANDI glue bug is fixed:
236     if (ANDIGlueBug)
237       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
238 
239     for (MVT VT : MVT::integer_valuetypes()) {
240       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
241       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
242       setTruncStoreAction(VT, MVT::i1, Expand);
243     }
244 
245     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
246   }
247 
248   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
249   // PPC (the libcall is not available).
250   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
251   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
252 
253   // We do not currently implement these libm ops for PowerPC.
254   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
255   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
256   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
257   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
258   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
259   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
260 
261   // PowerPC has no SREM/UREM instructions unless we are on P9
262   // On P9 we may use a hardware instruction to compute the remainder.
263   // The instructions are not legalized directly because in the cases where the
264   // result of both the remainder and the division is required it is more
265   // efficient to compute the remainder from the result of the division rather
266   // than use the remainder instruction.
267   if (Subtarget.isISA3_0()) {
268     setOperationAction(ISD::SREM, MVT::i32, Custom);
269     setOperationAction(ISD::UREM, MVT::i32, Custom);
270     setOperationAction(ISD::SREM, MVT::i64, Custom);
271     setOperationAction(ISD::UREM, MVT::i64, Custom);
272   } else {
273     setOperationAction(ISD::SREM, MVT::i32, Expand);
274     setOperationAction(ISD::UREM, MVT::i32, Expand);
275     setOperationAction(ISD::SREM, MVT::i64, Expand);
276     setOperationAction(ISD::UREM, MVT::i64, Expand);
277   }
278 
279   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
280   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
282   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
284   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
288 
289   // Handle constrained floating-point operations of scalar.
290   // TODO: Handle SPE specific operation.
291   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
292   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
293   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
295 
296   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
297   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
298   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
299   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
300 
301   // We don't support sin/cos/sqrt/fmod/pow
302   setOperationAction(ISD::FSIN , MVT::f64, Expand);
303   setOperationAction(ISD::FCOS , MVT::f64, Expand);
304   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
305   setOperationAction(ISD::FREM , MVT::f64, Expand);
306   setOperationAction(ISD::FPOW , MVT::f64, Expand);
307   setOperationAction(ISD::FSIN , MVT::f32, Expand);
308   setOperationAction(ISD::FCOS , MVT::f32, Expand);
309   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
310   setOperationAction(ISD::FREM , MVT::f32, Expand);
311   setOperationAction(ISD::FPOW , MVT::f32, Expand);
312   if (Subtarget.hasSPE()) {
313     setOperationAction(ISD::FMA  , MVT::f64, Expand);
314     setOperationAction(ISD::FMA  , MVT::f32, Expand);
315   } else {
316     setOperationAction(ISD::FMA  , MVT::f64, Legal);
317     setOperationAction(ISD::FMA  , MVT::f32, Legal);
318   }
319 
320   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
321 
322   // If we're enabling GP optimizations, use hardware square root
323   if (!Subtarget.hasFSQRT() &&
324       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
325         Subtarget.hasFRE()))
326     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
327 
328   if (!Subtarget.hasFSQRT() &&
329       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
330         Subtarget.hasFRES()))
331     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
332 
333   if (Subtarget.hasFCPSGN()) {
334     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
335     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
336   } else {
337     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
338     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
339   }
340 
341   if (Subtarget.hasFPRND()) {
342     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
343     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
344     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
345     setOperationAction(ISD::FROUND, MVT::f64, Legal);
346 
347     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
348     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
349     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
350     setOperationAction(ISD::FROUND, MVT::f32, Legal);
351   }
352 
353   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
354   // to speed up scalar BSWAP64.
355   // CTPOP or CTTZ were introduced in P8/P9 respectively
356   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
357   if (Subtarget.hasP9Vector())
358     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
359   else
360     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
361   if (Subtarget.isISA3_0()) {
362     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
363     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
364   } else {
365     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
366     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
367   }
368 
369   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
370     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
371     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
372   } else {
373     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
374     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
375   }
376 
377   // PowerPC does not have ROTR
378   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
379   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
380 
381   if (!Subtarget.useCRBits()) {
382     // PowerPC does not have Select
383     setOperationAction(ISD::SELECT, MVT::i32, Expand);
384     setOperationAction(ISD::SELECT, MVT::i64, Expand);
385     setOperationAction(ISD::SELECT, MVT::f32, Expand);
386     setOperationAction(ISD::SELECT, MVT::f64, Expand);
387   }
388 
389   // PowerPC wants to turn select_cc of FP into fsel when possible.
390   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
391   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
392 
393   // PowerPC wants to optimize integer setcc a bit
394   if (!Subtarget.useCRBits())
395     setOperationAction(ISD::SETCC, MVT::i32, Custom);
396 
397   // PowerPC does not have BRCOND which requires SetCC
398   if (!Subtarget.useCRBits())
399     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
400 
401   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
402 
403   if (Subtarget.hasSPE()) {
404     // SPE has built-in conversions
405     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
406     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
407     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
408   } else {
409     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
410     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
411 
412     // PowerPC does not have [U|S]INT_TO_FP
413     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
414     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
415   }
416 
417   if (Subtarget.hasDirectMove() && isPPC64) {
418     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
419     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
420     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
421     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
422     if (TM.Options.UnsafeFPMath) {
423       setOperationAction(ISD::LRINT, MVT::f64, Legal);
424       setOperationAction(ISD::LRINT, MVT::f32, Legal);
425       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
426       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
427       setOperationAction(ISD::LROUND, MVT::f64, Legal);
428       setOperationAction(ISD::LROUND, MVT::f32, Legal);
429       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
430       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
431     }
432   } else {
433     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
434     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
435     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
436     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
437   }
438 
439   // We cannot sextinreg(i1).  Expand to shifts.
440   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
441 
442   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
443   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
444   // support continuation, user-level threading, and etc.. As a result, no
445   // other SjLj exception interfaces are implemented and please don't build
446   // your own exception handling based on them.
447   // LLVM/Clang supports zero-cost DWARF exception handling.
448   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
449   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
450 
451   // We want to legalize GlobalAddress and ConstantPool nodes into the
452   // appropriate instructions to materialize the address.
453   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
454   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
455   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
456   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
457   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
458   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
459   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
460   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
461   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
462   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
463 
464   // TRAP is legal.
465   setOperationAction(ISD::TRAP, MVT::Other, Legal);
466 
467   // TRAMPOLINE is custom lowered.
468   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
469   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
470 
471   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
472   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
473 
474   if (Subtarget.is64BitELFABI()) {
475     // VAARG always uses double-word chunks, so promote anything smaller.
476     setOperationAction(ISD::VAARG, MVT::i1, Promote);
477     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
478     setOperationAction(ISD::VAARG, MVT::i8, Promote);
479     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
480     setOperationAction(ISD::VAARG, MVT::i16, Promote);
481     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
482     setOperationAction(ISD::VAARG, MVT::i32, Promote);
483     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
484     setOperationAction(ISD::VAARG, MVT::Other, Expand);
485   } else if (Subtarget.is32BitELFABI()) {
486     // VAARG is custom lowered with the 32-bit SVR4 ABI.
487     setOperationAction(ISD::VAARG, MVT::Other, Custom);
488     setOperationAction(ISD::VAARG, MVT::i64, Custom);
489   } else
490     setOperationAction(ISD::VAARG, MVT::Other, Expand);
491 
492   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
493   if (Subtarget.is32BitELFABI())
494     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
495   else
496     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
497 
498   // Use the default implementation.
499   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
500   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
501   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
502   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
503   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
504   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
505   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
506   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
507   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
508 
509   // We want to custom lower some of our intrinsics.
510   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
511 
512   // To handle counter-based loop conditions.
513   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
514 
515   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
516   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
517   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
518   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
519 
520   // Comparisons that require checking two conditions.
521   if (Subtarget.hasSPE()) {
522     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
523     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
524     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
525     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
526   }
527   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
528   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
529   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
530   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
531   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
532   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
533   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
534   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
535   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
536   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
537   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
538   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
539 
540   if (Subtarget.has64BitSupport()) {
541     // They also have instructions for converting between i64 and fp.
542     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
543     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
544     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
545     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
546     // This is just the low 32 bits of a (signed) fp->i64 conversion.
547     // We cannot do this with Promote because i64 is not a legal type.
548     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
549 
550     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
551       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
552   } else {
553     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
554     if (Subtarget.hasSPE())
555       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
556     else
557       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
558   }
559 
560   // With the instructions enabled under FPCVT, we can do everything.
561   if (Subtarget.hasFPCVT()) {
562     if (Subtarget.has64BitSupport()) {
563       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
564       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
565       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
566       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
567     }
568 
569     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
570     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
571     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
572     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
573   }
574 
575   if (Subtarget.use64BitRegs()) {
576     // 64-bit PowerPC implementations can support i64 types directly
577     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
578     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
579     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
580     // 64-bit PowerPC wants to expand i128 shifts itself.
581     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
582     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
583     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
584   } else {
585     // 32-bit PowerPC wants to expand i64 shifts itself.
586     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
587     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
588     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
589   }
590 
591   if (Subtarget.hasVSX()) {
592     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
593     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
594     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
595     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
596   }
597 
598   if (Subtarget.hasAltivec()) {
599     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
600       setOperationAction(ISD::SADDSAT, VT, Legal);
601       setOperationAction(ISD::SSUBSAT, VT, Legal);
602       setOperationAction(ISD::UADDSAT, VT, Legal);
603       setOperationAction(ISD::USUBSAT, VT, Legal);
604     }
605     // First set operation action for all vector types to expand. Then we
606     // will selectively turn on ones that can be effectively codegen'd.
607     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
608       // add/sub are legal for all supported vector VT's.
609       setOperationAction(ISD::ADD, VT, Legal);
610       setOperationAction(ISD::SUB, VT, Legal);
611 
612       // For v2i64, these are only valid with P8Vector. This is corrected after
613       // the loop.
614       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
615         setOperationAction(ISD::SMAX, VT, Legal);
616         setOperationAction(ISD::SMIN, VT, Legal);
617         setOperationAction(ISD::UMAX, VT, Legal);
618         setOperationAction(ISD::UMIN, VT, Legal);
619       }
620       else {
621         setOperationAction(ISD::SMAX, VT, Expand);
622         setOperationAction(ISD::SMIN, VT, Expand);
623         setOperationAction(ISD::UMAX, VT, Expand);
624         setOperationAction(ISD::UMIN, VT, Expand);
625       }
626 
627       if (Subtarget.hasVSX()) {
628         setOperationAction(ISD::FMAXNUM, VT, Legal);
629         setOperationAction(ISD::FMINNUM, VT, Legal);
630       }
631 
632       // Vector instructions introduced in P8
633       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
634         setOperationAction(ISD::CTPOP, VT, Legal);
635         setOperationAction(ISD::CTLZ, VT, Legal);
636       }
637       else {
638         setOperationAction(ISD::CTPOP, VT, Expand);
639         setOperationAction(ISD::CTLZ, VT, Expand);
640       }
641 
642       // Vector instructions introduced in P9
643       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
644         setOperationAction(ISD::CTTZ, VT, Legal);
645       else
646         setOperationAction(ISD::CTTZ, VT, Expand);
647 
648       // We promote all shuffles to v16i8.
649       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
650       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
651 
652       // We promote all non-typed operations to v4i32.
653       setOperationAction(ISD::AND   , VT, Promote);
654       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
655       setOperationAction(ISD::OR    , VT, Promote);
656       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
657       setOperationAction(ISD::XOR   , VT, Promote);
658       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
659       setOperationAction(ISD::LOAD  , VT, Promote);
660       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
661       setOperationAction(ISD::SELECT, VT, Promote);
662       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
663       setOperationAction(ISD::VSELECT, VT, Legal);
664       setOperationAction(ISD::SELECT_CC, VT, Promote);
665       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
666       setOperationAction(ISD::STORE, VT, Promote);
667       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
668 
669       // No other operations are legal.
670       setOperationAction(ISD::MUL , VT, Expand);
671       setOperationAction(ISD::SDIV, VT, Expand);
672       setOperationAction(ISD::SREM, VT, Expand);
673       setOperationAction(ISD::UDIV, VT, Expand);
674       setOperationAction(ISD::UREM, VT, Expand);
675       setOperationAction(ISD::FDIV, VT, Expand);
676       setOperationAction(ISD::FREM, VT, Expand);
677       setOperationAction(ISD::FNEG, VT, Expand);
678       setOperationAction(ISD::FSQRT, VT, Expand);
679       setOperationAction(ISD::FLOG, VT, Expand);
680       setOperationAction(ISD::FLOG10, VT, Expand);
681       setOperationAction(ISD::FLOG2, VT, Expand);
682       setOperationAction(ISD::FEXP, VT, Expand);
683       setOperationAction(ISD::FEXP2, VT, Expand);
684       setOperationAction(ISD::FSIN, VT, Expand);
685       setOperationAction(ISD::FCOS, VT, Expand);
686       setOperationAction(ISD::FABS, VT, Expand);
687       setOperationAction(ISD::FFLOOR, VT, Expand);
688       setOperationAction(ISD::FCEIL,  VT, Expand);
689       setOperationAction(ISD::FTRUNC, VT, Expand);
690       setOperationAction(ISD::FRINT,  VT, Expand);
691       setOperationAction(ISD::FNEARBYINT, VT, Expand);
692       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
693       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
694       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
695       setOperationAction(ISD::MULHU, VT, Expand);
696       setOperationAction(ISD::MULHS, VT, Expand);
697       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
698       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
699       setOperationAction(ISD::UDIVREM, VT, Expand);
700       setOperationAction(ISD::SDIVREM, VT, Expand);
701       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
702       setOperationAction(ISD::FPOW, VT, Expand);
703       setOperationAction(ISD::BSWAP, VT, Expand);
704       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
705       setOperationAction(ISD::ROTL, VT, Expand);
706       setOperationAction(ISD::ROTR, VT, Expand);
707 
708       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
709         setTruncStoreAction(VT, InnerVT, Expand);
710         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
711         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
712         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
713       }
714     }
715     if (!Subtarget.hasP8Vector()) {
716       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
717       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
718       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
719       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
720     }
721 
722     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
723       setOperationAction(ISD::ABS, VT, Custom);
724 
725     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
726     // with merges, splats, etc.
727     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
728 
729     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
730     // are cheap, so handle them before they get expanded to scalar.
731     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
732     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
733     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
734     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
735     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
736 
737     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
738     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
739     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
740     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
741     setOperationAction(ISD::SELECT, MVT::v4i32,
742                        Subtarget.useCRBits() ? Legal : Expand);
743     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
744     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
745     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
746     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
747     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
748     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
749     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
750     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
751     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
752 
753     // Without hasP8Altivec set, v2i64 SMAX isn't available.
754     // But ABS custom lowering requires SMAX support.
755     if (!Subtarget.hasP8Altivec())
756       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
757 
758     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
759     if (Subtarget.hasAltivec())
760       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
761         setOperationAction(ISD::ROTL, VT, Legal);
762     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
763     if (Subtarget.hasP8Altivec())
764       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
765 
766     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
767     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
768     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
769     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
770 
771     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
772     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
773 
774     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
775       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
776       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
777     }
778 
779     if (Subtarget.hasP8Altivec())
780       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
781     else
782       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
783 
784     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
785     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
786 
787     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
788     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
789 
790     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
791     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
792     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
793     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
794 
795     // Altivec does not contain unordered floating-point compare instructions
796     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
797     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
798     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
799     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
800 
801     if (Subtarget.hasVSX()) {
802       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
803       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
804       if (Subtarget.hasP8Vector()) {
805         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
806         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
807       }
808       if (Subtarget.hasDirectMove() && isPPC64) {
809         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
810         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
811         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
812         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
813         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
814         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
815         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
816         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
817       }
818       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
819 
820       // The nearbyint variants are not allowed to raise the inexact exception
821       // so we can only code-gen them with unsafe math.
822       if (TM.Options.UnsafeFPMath) {
823         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
824         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
825       }
826 
827       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
828       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
829       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
830       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
831       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
832       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
833       setOperationAction(ISD::FROUND, MVT::f64, Legal);
834       setOperationAction(ISD::FRINT, MVT::f64, Legal);
835 
836       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
837       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
838       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
839       setOperationAction(ISD::FROUND, MVT::f32, Legal);
840       setOperationAction(ISD::FRINT, MVT::f32, Legal);
841 
842       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
843       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
844 
845       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
846       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
847 
848       // Share the Altivec comparison restrictions.
849       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
850       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
851       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
852       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
853 
854       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
855       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
856 
857       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
858 
859       if (Subtarget.hasP8Vector())
860         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
861 
862       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
863 
864       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
865       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
866       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
867 
868       if (Subtarget.hasP8Altivec()) {
869         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
870         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
871         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
872 
873         // 128 bit shifts can be accomplished via 3 instructions for SHL and
874         // SRL, but not for SRA because of the instructions available:
875         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
876         // doing
877         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
878         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
879         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
880 
881         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
882       }
883       else {
884         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
885         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
886         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
887 
888         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
889 
890         // VSX v2i64 only supports non-arithmetic operations.
891         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
892         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
893       }
894 
895       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
896       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
897       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
898       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
899 
900       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
901 
902       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
903       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
904       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
905       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
906 
907       // Custom handling for partial vectors of integers converted to
908       // floating point. We already have optimal handling for v2i32 through
909       // the DAG combine, so those aren't necessary.
910       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
911       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
912       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
913       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
914       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
915       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
916       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
917       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
918 
919       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
920       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
921       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
922       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
923       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
924       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
925 
926       if (Subtarget.hasDirectMove())
927         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
928       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
929 
930       // Handle constrained floating-point operations of vector.
931       // The predictor is `hasVSX` because altivec instruction has
932       // no exception but VSX vector instruction has.
933       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
934       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
935       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
936       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
937 
938       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
939       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
940       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
941       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
942 
943       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
944     }
945 
946     if (Subtarget.hasP8Altivec()) {
947       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
948       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
949     }
950 
951     if (Subtarget.hasP9Vector()) {
952       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
953       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
954 
955       // 128 bit shifts can be accomplished via 3 instructions for SHL and
956       // SRL, but not for SRA because of the instructions available:
957       // VS{RL} and VS{RL}O.
958       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
959       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
960       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
961 
962       if (EnableQuadPrecision) {
963         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
964         setOperationAction(ISD::FADD, MVT::f128, Legal);
965         setOperationAction(ISD::FSUB, MVT::f128, Legal);
966         setOperationAction(ISD::FDIV, MVT::f128, Legal);
967         setOperationAction(ISD::FMUL, MVT::f128, Legal);
968         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
969         // No extending loads to f128 on PPC.
970         for (MVT FPT : MVT::fp_valuetypes())
971           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
972         setOperationAction(ISD::FMA, MVT::f128, Legal);
973         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
974         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
975         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
976         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
977         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
978         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
979 
980         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
981         setOperationAction(ISD::FRINT, MVT::f128, Legal);
982         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
983         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
984         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
985         setOperationAction(ISD::FROUND, MVT::f128, Legal);
986 
987         setOperationAction(ISD::SELECT, MVT::f128, Expand);
988         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
989         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
990         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
991         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
992         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
993         // No implementation for these ops for PowerPC.
994         setOperationAction(ISD::FSIN , MVT::f128, Expand);
995         setOperationAction(ISD::FCOS , MVT::f128, Expand);
996         setOperationAction(ISD::FPOW, MVT::f128, Expand);
997         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
998         setOperationAction(ISD::FREM, MVT::f128, Expand);
999 
1000         // Handle constrained floating-point operations of fp128
1001         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1002         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1003         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1004         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1005       }
1006       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1007       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1008       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1009       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1010       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1011     }
1012 
1013     if (Subtarget.hasP9Altivec()) {
1014       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1015       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1016 
1017       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1018       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1019       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1020       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1021       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1022       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1023       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1024     }
1025   }
1026 
1027   if (Subtarget.hasQPX()) {
1028     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1029     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1030     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1031     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1032 
1033     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1034     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1035 
1036     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1037     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1038 
1039     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1040     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1041 
1042     if (!Subtarget.useCRBits())
1043       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1044     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1045 
1046     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1047     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1048     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1049     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1050     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1051     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1052     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1053 
1054     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1055     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1056 
1057     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1058     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1059 
1060     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1061     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1062     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1063     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1064     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1065     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1066     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1067     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1068     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1069     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1070 
1071     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1072     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1073 
1074     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1075     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1076 
1077     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1078 
1079     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1080     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1081     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1082     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1083 
1084     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1085     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1086 
1087     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1088     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1089 
1090     if (!Subtarget.useCRBits())
1091       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1092     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1093 
1094     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1095     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1096     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1097     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1098     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1099     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1100     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1101 
1102     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1103     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1104 
1105     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1106     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1107     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1108     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1109     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1110     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1111     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1112     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1113     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1114     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1115 
1116     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1117     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1118 
1119     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1120     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1121 
1122     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1123 
1124     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1125     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1126     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1127 
1128     if (!Subtarget.useCRBits())
1129       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1130     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1131 
1132     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1133     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1134 
1135     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1137     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1138     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1139     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1140     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1141     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1142 
1143     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1144     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1145 
1146     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1147 
1148     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1149     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1150     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1151     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1152 
1153     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1154     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1155     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1156     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1157 
1158     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1159     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1160 
1161     // These need to set FE_INEXACT, and so cannot be vectorized here.
1162     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1163     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1164 
1165     if (TM.Options.UnsafeFPMath) {
1166       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1167       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1168 
1169       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1170       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1171     } else {
1172       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1173       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1174 
1175       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1176       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1177     }
1178 
1179     // TODO: Handle constrained floating-point operations of v4f64
1180   }
1181 
1182   if (Subtarget.has64BitSupport())
1183     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1184 
1185   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1186 
1187   if (!isPPC64) {
1188     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1189     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1190   }
1191 
1192   setBooleanContents(ZeroOrOneBooleanContent);
1193 
1194   if (Subtarget.hasAltivec()) {
1195     // Altivec instructions set fields to all zeros or all ones.
1196     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1197   }
1198 
1199   if (!isPPC64) {
1200     // These libcalls are not available in 32-bit.
1201     setLibcallName(RTLIB::SHL_I128, nullptr);
1202     setLibcallName(RTLIB::SRL_I128, nullptr);
1203     setLibcallName(RTLIB::SRA_I128, nullptr);
1204   }
1205 
1206   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1207 
1208   // We have target-specific dag combine patterns for the following nodes:
1209   setTargetDAGCombine(ISD::ADD);
1210   setTargetDAGCombine(ISD::SHL);
1211   setTargetDAGCombine(ISD::SRA);
1212   setTargetDAGCombine(ISD::SRL);
1213   setTargetDAGCombine(ISD::MUL);
1214   setTargetDAGCombine(ISD::SINT_TO_FP);
1215   setTargetDAGCombine(ISD::BUILD_VECTOR);
1216   if (Subtarget.hasFPCVT())
1217     setTargetDAGCombine(ISD::UINT_TO_FP);
1218   setTargetDAGCombine(ISD::LOAD);
1219   setTargetDAGCombine(ISD::STORE);
1220   setTargetDAGCombine(ISD::BR_CC);
1221   if (Subtarget.useCRBits())
1222     setTargetDAGCombine(ISD::BRCOND);
1223   setTargetDAGCombine(ISD::BSWAP);
1224   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1225   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1226   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1227 
1228   setTargetDAGCombine(ISD::SIGN_EXTEND);
1229   setTargetDAGCombine(ISD::ZERO_EXTEND);
1230   setTargetDAGCombine(ISD::ANY_EXTEND);
1231 
1232   setTargetDAGCombine(ISD::TRUNCATE);
1233   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1234 
1235 
1236   if (Subtarget.useCRBits()) {
1237     setTargetDAGCombine(ISD::TRUNCATE);
1238     setTargetDAGCombine(ISD::SETCC);
1239     setTargetDAGCombine(ISD::SELECT_CC);
1240   }
1241 
1242   // Use reciprocal estimates.
1243   if (TM.Options.UnsafeFPMath) {
1244     setTargetDAGCombine(ISD::FDIV);
1245     setTargetDAGCombine(ISD::FSQRT);
1246   }
1247 
1248   if (Subtarget.hasP9Altivec()) {
1249     setTargetDAGCombine(ISD::ABS);
1250     setTargetDAGCombine(ISD::VSELECT);
1251   }
1252 
1253   if (EnableQuadPrecision) {
1254     setLibcallName(RTLIB::LOG_F128, "logf128");
1255     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1256     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1257     setLibcallName(RTLIB::EXP_F128, "expf128");
1258     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1259     setLibcallName(RTLIB::SIN_F128, "sinf128");
1260     setLibcallName(RTLIB::COS_F128, "cosf128");
1261     setLibcallName(RTLIB::POW_F128, "powf128");
1262     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1263     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1264     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1265     setLibcallName(RTLIB::REM_F128, "fmodf128");
1266   }
1267 
1268   // With 32 condition bits, we don't need to sink (and duplicate) compares
1269   // aggressively in CodeGenPrep.
1270   if (Subtarget.useCRBits()) {
1271     setHasMultipleConditionRegisters();
1272     setJumpIsExpensive();
1273   }
1274 
1275   setMinFunctionAlignment(Align(4));
1276 
1277   switch (Subtarget.getCPUDirective()) {
1278   default: break;
1279   case PPC::DIR_970:
1280   case PPC::DIR_A2:
1281   case PPC::DIR_E500:
1282   case PPC::DIR_E500mc:
1283   case PPC::DIR_E5500:
1284   case PPC::DIR_PWR4:
1285   case PPC::DIR_PWR5:
1286   case PPC::DIR_PWR5X:
1287   case PPC::DIR_PWR6:
1288   case PPC::DIR_PWR6X:
1289   case PPC::DIR_PWR7:
1290   case PPC::DIR_PWR8:
1291   case PPC::DIR_PWR9:
1292   case PPC::DIR_PWR_FUTURE:
1293     setPrefLoopAlignment(Align(16));
1294     setPrefFunctionAlignment(Align(16));
1295     break;
1296   }
1297 
1298   if (Subtarget.enableMachineScheduler())
1299     setSchedulingPreference(Sched::Source);
1300   else
1301     setSchedulingPreference(Sched::Hybrid);
1302 
1303   computeRegisterProperties(STI.getRegisterInfo());
1304 
1305   // The Freescale cores do better with aggressive inlining of memcpy and
1306   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1307   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1308       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1309     MaxStoresPerMemset = 32;
1310     MaxStoresPerMemsetOptSize = 16;
1311     MaxStoresPerMemcpy = 32;
1312     MaxStoresPerMemcpyOptSize = 8;
1313     MaxStoresPerMemmove = 32;
1314     MaxStoresPerMemmoveOptSize = 8;
1315   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1316     // The A2 also benefits from (very) aggressive inlining of memcpy and
1317     // friends. The overhead of a the function call, even when warm, can be
1318     // over one hundred cycles.
1319     MaxStoresPerMemset = 128;
1320     MaxStoresPerMemcpy = 128;
1321     MaxStoresPerMemmove = 128;
1322     MaxLoadsPerMemcmp = 128;
1323   } else {
1324     MaxLoadsPerMemcmp = 8;
1325     MaxLoadsPerMemcmpOptSize = 4;
1326   }
1327 }
1328 
1329 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1330 /// the desired ByVal argument alignment.
1331 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1332                              unsigned MaxMaxAlign) {
1333   if (MaxAlign == MaxMaxAlign)
1334     return;
1335   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1336     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1337       MaxAlign = 32;
1338     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1339       MaxAlign = 16;
1340   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1341     unsigned EltAlign = 0;
1342     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1343     if (EltAlign > MaxAlign)
1344       MaxAlign = EltAlign;
1345   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1346     for (auto *EltTy : STy->elements()) {
1347       unsigned EltAlign = 0;
1348       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1349       if (EltAlign > MaxAlign)
1350         MaxAlign = EltAlign;
1351       if (MaxAlign == MaxMaxAlign)
1352         break;
1353     }
1354   }
1355 }
1356 
1357 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1358 /// function arguments in the caller parameter area.
1359 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1360                                                   const DataLayout &DL) const {
1361   // 16byte and wider vectors are passed on 16byte boundary.
1362   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1363   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1364   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1365     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1366   return Align;
1367 }
1368 
1369 bool PPCTargetLowering::useSoftFloat() const {
1370   return Subtarget.useSoftFloat();
1371 }
1372 
1373 bool PPCTargetLowering::hasSPE() const {
1374   return Subtarget.hasSPE();
1375 }
1376 
1377 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1378   return VT.isScalarInteger();
1379 }
1380 
1381 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1382   switch ((PPCISD::NodeType)Opcode) {
1383   case PPCISD::FIRST_NUMBER:    break;
1384   case PPCISD::FSEL:            return "PPCISD::FSEL";
1385   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1386   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1387   case PPCISD::FCFID:           return "PPCISD::FCFID";
1388   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1389   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1390   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1391   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1392   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1393   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1394   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1395   case PPCISD::FP_TO_UINT_IN_VSR:
1396                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1397   case PPCISD::FP_TO_SINT_IN_VSR:
1398                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1399   case PPCISD::FRE:             return "PPCISD::FRE";
1400   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1401   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1402   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1403   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1404   case PPCISD::VPERM:           return "PPCISD::VPERM";
1405   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1406   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1407   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1408   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1409   case PPCISD::CMPB:            return "PPCISD::CMPB";
1410   case PPCISD::Hi:              return "PPCISD::Hi";
1411   case PPCISD::Lo:              return "PPCISD::Lo";
1412   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1413   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1414   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1415   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1416   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1417   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1418   case PPCISD::SRL:             return "PPCISD::SRL";
1419   case PPCISD::SRA:             return "PPCISD::SRA";
1420   case PPCISD::SHL:             return "PPCISD::SHL";
1421   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1422   case PPCISD::CALL:            return "PPCISD::CALL";
1423   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1424   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1425   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1426   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1427   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1428   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1429   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1430   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1431   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1432   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1433   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1434   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1435   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1436   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1437   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1438   case PPCISD::ANDI_rec_1_EQ_BIT:
1439     return "PPCISD::ANDI_rec_1_EQ_BIT";
1440   case PPCISD::ANDI_rec_1_GT_BIT:
1441     return "PPCISD::ANDI_rec_1_GT_BIT";
1442   case PPCISD::VCMP:            return "PPCISD::VCMP";
1443   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1444   case PPCISD::LBRX:            return "PPCISD::LBRX";
1445   case PPCISD::STBRX:           return "PPCISD::STBRX";
1446   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1447   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1448   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1449   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1450   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1451   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1452   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1453   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1454   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1455   case PPCISD::ST_VSR_SCAL_INT:
1456                                 return "PPCISD::ST_VSR_SCAL_INT";
1457   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1458   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1459   case PPCISD::BDZ:             return "PPCISD::BDZ";
1460   case PPCISD::MFFS:            return "PPCISD::MFFS";
1461   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1462   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1463   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1464   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1465   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1466   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1467   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1468   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1469   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1470   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1471   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1472   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1473   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1474   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1475   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1476   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1477   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1478   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1479   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1480   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1481   case PPCISD::SC:              return "PPCISD::SC";
1482   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1483   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1484   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1485   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1486   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1487   case PPCISD::VABSD:           return "PPCISD::VABSD";
1488   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1489   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1490   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1491   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1492   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1493   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1494   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1495   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1496   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1497   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1498   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1499   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1500   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1501   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1502   }
1503   return nullptr;
1504 }
1505 
1506 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1507                                           EVT VT) const {
1508   if (!VT.isVector())
1509     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1510 
1511   if (Subtarget.hasQPX())
1512     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1513 
1514   return VT.changeVectorElementTypeToInteger();
1515 }
1516 
1517 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1518   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1519   return true;
1520 }
1521 
1522 //===----------------------------------------------------------------------===//
1523 // Node matching predicates, for use by the tblgen matching code.
1524 //===----------------------------------------------------------------------===//
1525 
1526 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1527 static bool isFloatingPointZero(SDValue Op) {
1528   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1529     return CFP->getValueAPF().isZero();
1530   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1531     // Maybe this has already been legalized into the constant pool?
1532     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1533       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1534         return CFP->getValueAPF().isZero();
1535   }
1536   return false;
1537 }
1538 
1539 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1540 /// true if Op is undef or if it matches the specified value.
1541 static bool isConstantOrUndef(int Op, int Val) {
1542   return Op < 0 || Op == Val;
1543 }
1544 
1545 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1546 /// VPKUHUM instruction.
1547 /// The ShuffleKind distinguishes between big-endian operations with
1548 /// two different inputs (0), either-endian operations with two identical
1549 /// inputs (1), and little-endian operations with two different inputs (2).
1550 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1551 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1552                                SelectionDAG &DAG) {
1553   bool IsLE = DAG.getDataLayout().isLittleEndian();
1554   if (ShuffleKind == 0) {
1555     if (IsLE)
1556       return false;
1557     for (unsigned i = 0; i != 16; ++i)
1558       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1559         return false;
1560   } else if (ShuffleKind == 2) {
1561     if (!IsLE)
1562       return false;
1563     for (unsigned i = 0; i != 16; ++i)
1564       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1565         return false;
1566   } else if (ShuffleKind == 1) {
1567     unsigned j = IsLE ? 0 : 1;
1568     for (unsigned i = 0; i != 8; ++i)
1569       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1570           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1571         return false;
1572   }
1573   return true;
1574 }
1575 
1576 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1577 /// VPKUWUM instruction.
1578 /// The ShuffleKind distinguishes between big-endian operations with
1579 /// two different inputs (0), either-endian operations with two identical
1580 /// inputs (1), and little-endian operations with two different inputs (2).
1581 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1582 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1583                                SelectionDAG &DAG) {
1584   bool IsLE = DAG.getDataLayout().isLittleEndian();
1585   if (ShuffleKind == 0) {
1586     if (IsLE)
1587       return false;
1588     for (unsigned i = 0; i != 16; i += 2)
1589       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1590           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1591         return false;
1592   } else if (ShuffleKind == 2) {
1593     if (!IsLE)
1594       return false;
1595     for (unsigned i = 0; i != 16; i += 2)
1596       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1597           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1598         return false;
1599   } else if (ShuffleKind == 1) {
1600     unsigned j = IsLE ? 0 : 2;
1601     for (unsigned i = 0; i != 8; i += 2)
1602       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1603           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1604           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1605           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1606         return false;
1607   }
1608   return true;
1609 }
1610 
1611 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1612 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1613 /// current subtarget.
1614 ///
1615 /// The ShuffleKind distinguishes between big-endian operations with
1616 /// two different inputs (0), either-endian operations with two identical
1617 /// inputs (1), and little-endian operations with two different inputs (2).
1618 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1619 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1620                                SelectionDAG &DAG) {
1621   const PPCSubtarget& Subtarget =
1622       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1623   if (!Subtarget.hasP8Vector())
1624     return false;
1625 
1626   bool IsLE = DAG.getDataLayout().isLittleEndian();
1627   if (ShuffleKind == 0) {
1628     if (IsLE)
1629       return false;
1630     for (unsigned i = 0; i != 16; i += 4)
1631       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1632           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1633           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1634           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1635         return false;
1636   } else if (ShuffleKind == 2) {
1637     if (!IsLE)
1638       return false;
1639     for (unsigned i = 0; i != 16; i += 4)
1640       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1641           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1642           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1643           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1644         return false;
1645   } else if (ShuffleKind == 1) {
1646     unsigned j = IsLE ? 0 : 4;
1647     for (unsigned i = 0; i != 8; i += 4)
1648       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1649           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1650           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1651           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1652           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1653           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1654           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1655           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1656         return false;
1657   }
1658   return true;
1659 }
1660 
1661 /// isVMerge - Common function, used to match vmrg* shuffles.
1662 ///
1663 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1664                      unsigned LHSStart, unsigned RHSStart) {
1665   if (N->getValueType(0) != MVT::v16i8)
1666     return false;
1667   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1668          "Unsupported merge size!");
1669 
1670   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1671     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1672       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1673                              LHSStart+j+i*UnitSize) ||
1674           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1675                              RHSStart+j+i*UnitSize))
1676         return false;
1677     }
1678   return true;
1679 }
1680 
1681 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1682 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1683 /// The ShuffleKind distinguishes between big-endian merges with two
1684 /// different inputs (0), either-endian merges with two identical inputs (1),
1685 /// and little-endian merges with two different inputs (2).  For the latter,
1686 /// the input operands are swapped (see PPCInstrAltivec.td).
1687 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1688                              unsigned ShuffleKind, SelectionDAG &DAG) {
1689   if (DAG.getDataLayout().isLittleEndian()) {
1690     if (ShuffleKind == 1) // unary
1691       return isVMerge(N, UnitSize, 0, 0);
1692     else if (ShuffleKind == 2) // swapped
1693       return isVMerge(N, UnitSize, 0, 16);
1694     else
1695       return false;
1696   } else {
1697     if (ShuffleKind == 1) // unary
1698       return isVMerge(N, UnitSize, 8, 8);
1699     else if (ShuffleKind == 0) // normal
1700       return isVMerge(N, UnitSize, 8, 24);
1701     else
1702       return false;
1703   }
1704 }
1705 
1706 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1707 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1708 /// The ShuffleKind distinguishes between big-endian merges with two
1709 /// different inputs (0), either-endian merges with two identical inputs (1),
1710 /// and little-endian merges with two different inputs (2).  For the latter,
1711 /// the input operands are swapped (see PPCInstrAltivec.td).
1712 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1713                              unsigned ShuffleKind, SelectionDAG &DAG) {
1714   if (DAG.getDataLayout().isLittleEndian()) {
1715     if (ShuffleKind == 1) // unary
1716       return isVMerge(N, UnitSize, 8, 8);
1717     else if (ShuffleKind == 2) // swapped
1718       return isVMerge(N, UnitSize, 8, 24);
1719     else
1720       return false;
1721   } else {
1722     if (ShuffleKind == 1) // unary
1723       return isVMerge(N, UnitSize, 0, 0);
1724     else if (ShuffleKind == 0) // normal
1725       return isVMerge(N, UnitSize, 0, 16);
1726     else
1727       return false;
1728   }
1729 }
1730 
1731 /**
1732  * Common function used to match vmrgew and vmrgow shuffles
1733  *
1734  * The indexOffset determines whether to look for even or odd words in
1735  * the shuffle mask. This is based on the of the endianness of the target
1736  * machine.
1737  *   - Little Endian:
1738  *     - Use offset of 0 to check for odd elements
1739  *     - Use offset of 4 to check for even elements
1740  *   - Big Endian:
1741  *     - Use offset of 0 to check for even elements
1742  *     - Use offset of 4 to check for odd elements
1743  * A detailed description of the vector element ordering for little endian and
1744  * big endian can be found at
1745  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1746  * Targeting your applications - what little endian and big endian IBM XL C/C++
1747  * compiler differences mean to you
1748  *
1749  * The mask to the shuffle vector instruction specifies the indices of the
1750  * elements from the two input vectors to place in the result. The elements are
1751  * numbered in array-access order, starting with the first vector. These vectors
1752  * are always of type v16i8, thus each vector will contain 16 elements of size
1753  * 8. More info on the shuffle vector can be found in the
1754  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1755  * Language Reference.
1756  *
1757  * The RHSStartValue indicates whether the same input vectors are used (unary)
1758  * or two different input vectors are used, based on the following:
1759  *   - If the instruction uses the same vector for both inputs, the range of the
1760  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1761  *     be 0.
1762  *   - If the instruction has two different vectors then the range of the
1763  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1764  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1765  *     to 31 specify elements in the second vector).
1766  *
1767  * \param[in] N The shuffle vector SD Node to analyze
1768  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1769  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1770  * vector to the shuffle_vector instruction
1771  * \return true iff this shuffle vector represents an even or odd word merge
1772  */
1773 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1774                      unsigned RHSStartValue) {
1775   if (N->getValueType(0) != MVT::v16i8)
1776     return false;
1777 
1778   for (unsigned i = 0; i < 2; ++i)
1779     for (unsigned j = 0; j < 4; ++j)
1780       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1781                              i*RHSStartValue+j+IndexOffset) ||
1782           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1783                              i*RHSStartValue+j+IndexOffset+8))
1784         return false;
1785   return true;
1786 }
1787 
1788 /**
1789  * Determine if the specified shuffle mask is suitable for the vmrgew or
1790  * vmrgow instructions.
1791  *
1792  * \param[in] N The shuffle vector SD Node to analyze
1793  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1794  * \param[in] ShuffleKind Identify the type of merge:
1795  *   - 0 = big-endian merge with two different inputs;
1796  *   - 1 = either-endian merge with two identical inputs;
1797  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1798  *     little-endian merges).
1799  * \param[in] DAG The current SelectionDAG
1800  * \return true iff this shuffle mask
1801  */
1802 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1803                               unsigned ShuffleKind, SelectionDAG &DAG) {
1804   if (DAG.getDataLayout().isLittleEndian()) {
1805     unsigned indexOffset = CheckEven ? 4 : 0;
1806     if (ShuffleKind == 1) // Unary
1807       return isVMerge(N, indexOffset, 0);
1808     else if (ShuffleKind == 2) // swapped
1809       return isVMerge(N, indexOffset, 16);
1810     else
1811       return false;
1812   }
1813   else {
1814     unsigned indexOffset = CheckEven ? 0 : 4;
1815     if (ShuffleKind == 1) // Unary
1816       return isVMerge(N, indexOffset, 0);
1817     else if (ShuffleKind == 0) // Normal
1818       return isVMerge(N, indexOffset, 16);
1819     else
1820       return false;
1821   }
1822   return false;
1823 }
1824 
1825 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1826 /// amount, otherwise return -1.
1827 /// The ShuffleKind distinguishes between big-endian operations with two
1828 /// different inputs (0), either-endian operations with two identical inputs
1829 /// (1), and little-endian operations with two different inputs (2).  For the
1830 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1831 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1832                              SelectionDAG &DAG) {
1833   if (N->getValueType(0) != MVT::v16i8)
1834     return -1;
1835 
1836   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1837 
1838   // Find the first non-undef value in the shuffle mask.
1839   unsigned i;
1840   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1841     /*search*/;
1842 
1843   if (i == 16) return -1;  // all undef.
1844 
1845   // Otherwise, check to see if the rest of the elements are consecutively
1846   // numbered from this value.
1847   unsigned ShiftAmt = SVOp->getMaskElt(i);
1848   if (ShiftAmt < i) return -1;
1849 
1850   ShiftAmt -= i;
1851   bool isLE = DAG.getDataLayout().isLittleEndian();
1852 
1853   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1854     // Check the rest of the elements to see if they are consecutive.
1855     for (++i; i != 16; ++i)
1856       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1857         return -1;
1858   } else if (ShuffleKind == 1) {
1859     // Check the rest of the elements to see if they are consecutive.
1860     for (++i; i != 16; ++i)
1861       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1862         return -1;
1863   } else
1864     return -1;
1865 
1866   if (isLE)
1867     ShiftAmt = 16 - ShiftAmt;
1868 
1869   return ShiftAmt;
1870 }
1871 
1872 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1873 /// specifies a splat of a single element that is suitable for input to
1874 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1875 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1876   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1877          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1878 
1879   // The consecutive indices need to specify an element, not part of two
1880   // different elements.  So abandon ship early if this isn't the case.
1881   if (N->getMaskElt(0) % EltSize != 0)
1882     return false;
1883 
1884   // This is a splat operation if each element of the permute is the same, and
1885   // if the value doesn't reference the second vector.
1886   unsigned ElementBase = N->getMaskElt(0);
1887 
1888   // FIXME: Handle UNDEF elements too!
1889   if (ElementBase >= 16)
1890     return false;
1891 
1892   // Check that the indices are consecutive, in the case of a multi-byte element
1893   // splatted with a v16i8 mask.
1894   for (unsigned i = 1; i != EltSize; ++i)
1895     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1896       return false;
1897 
1898   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1899     if (N->getMaskElt(i) < 0) continue;
1900     for (unsigned j = 0; j != EltSize; ++j)
1901       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1902         return false;
1903   }
1904   return true;
1905 }
1906 
1907 /// Check that the mask is shuffling N byte elements. Within each N byte
1908 /// element of the mask, the indices could be either in increasing or
1909 /// decreasing order as long as they are consecutive.
1910 /// \param[in] N the shuffle vector SD Node to analyze
1911 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1912 /// Word/DoubleWord/QuadWord).
1913 /// \param[in] StepLen the delta indices number among the N byte element, if
1914 /// the mask is in increasing/decreasing order then it is 1/-1.
1915 /// \return true iff the mask is shuffling N byte elements.
1916 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1917                                    int StepLen) {
1918   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1919          "Unexpected element width.");
1920   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1921 
1922   unsigned NumOfElem = 16 / Width;
1923   unsigned MaskVal[16]; //  Width is never greater than 16
1924   for (unsigned i = 0; i < NumOfElem; ++i) {
1925     MaskVal[0] = N->getMaskElt(i * Width);
1926     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1927       return false;
1928     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1929       return false;
1930     }
1931 
1932     for (unsigned int j = 1; j < Width; ++j) {
1933       MaskVal[j] = N->getMaskElt(i * Width + j);
1934       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1935         return false;
1936       }
1937     }
1938   }
1939 
1940   return true;
1941 }
1942 
1943 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1944                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1945   if (!isNByteElemShuffleMask(N, 4, 1))
1946     return false;
1947 
1948   // Now we look at mask elements 0,4,8,12
1949   unsigned M0 = N->getMaskElt(0) / 4;
1950   unsigned M1 = N->getMaskElt(4) / 4;
1951   unsigned M2 = N->getMaskElt(8) / 4;
1952   unsigned M3 = N->getMaskElt(12) / 4;
1953   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1954   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1955 
1956   // Below, let H and L be arbitrary elements of the shuffle mask
1957   // where H is in the range [4,7] and L is in the range [0,3].
1958   // H, 1, 2, 3 or L, 5, 6, 7
1959   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1960       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1961     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1962     InsertAtByte = IsLE ? 12 : 0;
1963     Swap = M0 < 4;
1964     return true;
1965   }
1966   // 0, H, 2, 3 or 4, L, 6, 7
1967   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1968       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1969     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1970     InsertAtByte = IsLE ? 8 : 4;
1971     Swap = M1 < 4;
1972     return true;
1973   }
1974   // 0, 1, H, 3 or 4, 5, L, 7
1975   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1976       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1977     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1978     InsertAtByte = IsLE ? 4 : 8;
1979     Swap = M2 < 4;
1980     return true;
1981   }
1982   // 0, 1, 2, H or 4, 5, 6, L
1983   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1984       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1985     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1986     InsertAtByte = IsLE ? 0 : 12;
1987     Swap = M3 < 4;
1988     return true;
1989   }
1990 
1991   // If both vector operands for the shuffle are the same vector, the mask will
1992   // contain only elements from the first one and the second one will be undef.
1993   if (N->getOperand(1).isUndef()) {
1994     ShiftElts = 0;
1995     Swap = true;
1996     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1997     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1998       InsertAtByte = IsLE ? 12 : 0;
1999       return true;
2000     }
2001     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2002       InsertAtByte = IsLE ? 8 : 4;
2003       return true;
2004     }
2005     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2006       InsertAtByte = IsLE ? 4 : 8;
2007       return true;
2008     }
2009     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2010       InsertAtByte = IsLE ? 0 : 12;
2011       return true;
2012     }
2013   }
2014 
2015   return false;
2016 }
2017 
2018 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2019                                bool &Swap, bool IsLE) {
2020   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2021   // Ensure each byte index of the word is consecutive.
2022   if (!isNByteElemShuffleMask(N, 4, 1))
2023     return false;
2024 
2025   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2026   unsigned M0 = N->getMaskElt(0) / 4;
2027   unsigned M1 = N->getMaskElt(4) / 4;
2028   unsigned M2 = N->getMaskElt(8) / 4;
2029   unsigned M3 = N->getMaskElt(12) / 4;
2030 
2031   // If both vector operands for the shuffle are the same vector, the mask will
2032   // contain only elements from the first one and the second one will be undef.
2033   if (N->getOperand(1).isUndef()) {
2034     assert(M0 < 4 && "Indexing into an undef vector?");
2035     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2036       return false;
2037 
2038     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2039     Swap = false;
2040     return true;
2041   }
2042 
2043   // Ensure each word index of the ShuffleVector Mask is consecutive.
2044   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2045     return false;
2046 
2047   if (IsLE) {
2048     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2049       // Input vectors don't need to be swapped if the leading element
2050       // of the result is one of the 3 left elements of the second vector
2051       // (or if there is no shift to be done at all).
2052       Swap = false;
2053       ShiftElts = (8 - M0) % 8;
2054     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2055       // Input vectors need to be swapped if the leading element
2056       // of the result is one of the 3 left elements of the first vector
2057       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2058       Swap = true;
2059       ShiftElts = (4 - M0) % 4;
2060     }
2061 
2062     return true;
2063   } else {                                          // BE
2064     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2065       // Input vectors don't need to be swapped if the leading element
2066       // of the result is one of the 4 elements of the first vector.
2067       Swap = false;
2068       ShiftElts = M0;
2069     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2070       // Input vectors need to be swapped if the leading element
2071       // of the result is one of the 4 elements of the right vector.
2072       Swap = true;
2073       ShiftElts = M0 - 4;
2074     }
2075 
2076     return true;
2077   }
2078 }
2079 
2080 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2081   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2082 
2083   if (!isNByteElemShuffleMask(N, Width, -1))
2084     return false;
2085 
2086   for (int i = 0; i < 16; i += Width)
2087     if (N->getMaskElt(i) != i + Width - 1)
2088       return false;
2089 
2090   return true;
2091 }
2092 
2093 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2094   return isXXBRShuffleMaskHelper(N, 2);
2095 }
2096 
2097 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2098   return isXXBRShuffleMaskHelper(N, 4);
2099 }
2100 
2101 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2102   return isXXBRShuffleMaskHelper(N, 8);
2103 }
2104 
2105 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2106   return isXXBRShuffleMaskHelper(N, 16);
2107 }
2108 
2109 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2110 /// if the inputs to the instruction should be swapped and set \p DM to the
2111 /// value for the immediate.
2112 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2113 /// AND element 0 of the result comes from the first input (LE) or second input
2114 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2115 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2116 /// mask.
2117 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2118                                bool &Swap, bool IsLE) {
2119   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2120 
2121   // Ensure each byte index of the double word is consecutive.
2122   if (!isNByteElemShuffleMask(N, 8, 1))
2123     return false;
2124 
2125   unsigned M0 = N->getMaskElt(0) / 8;
2126   unsigned M1 = N->getMaskElt(8) / 8;
2127   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2128 
2129   // If both vector operands for the shuffle are the same vector, the mask will
2130   // contain only elements from the first one and the second one will be undef.
2131   if (N->getOperand(1).isUndef()) {
2132     if ((M0 | M1) < 2) {
2133       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2134       Swap = false;
2135       return true;
2136     } else
2137       return false;
2138   }
2139 
2140   if (IsLE) {
2141     if (M0 > 1 && M1 < 2) {
2142       Swap = false;
2143     } else if (M0 < 2 && M1 > 1) {
2144       M0 = (M0 + 2) % 4;
2145       M1 = (M1 + 2) % 4;
2146       Swap = true;
2147     } else
2148       return false;
2149 
2150     // Note: if control flow comes here that means Swap is already set above
2151     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2152     return true;
2153   } else { // BE
2154     if (M0 < 2 && M1 > 1) {
2155       Swap = false;
2156     } else if (M0 > 1 && M1 < 2) {
2157       M0 = (M0 + 2) % 4;
2158       M1 = (M1 + 2) % 4;
2159       Swap = true;
2160     } else
2161       return false;
2162 
2163     // Note: if control flow comes here that means Swap is already set above
2164     DM = (M0 << 1) + (M1 & 1);
2165     return true;
2166   }
2167 }
2168 
2169 
2170 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2171 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2172 /// elements are counted from the left of the vector register).
2173 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2174                                          SelectionDAG &DAG) {
2175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2176   assert(isSplatShuffleMask(SVOp, EltSize));
2177   if (DAG.getDataLayout().isLittleEndian())
2178     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2179   else
2180     return SVOp->getMaskElt(0) / EltSize;
2181 }
2182 
2183 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2184 /// by using a vspltis[bhw] instruction of the specified element size, return
2185 /// the constant being splatted.  The ByteSize field indicates the number of
2186 /// bytes of each element [124] -> [bhw].
2187 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2188   SDValue OpVal(nullptr, 0);
2189 
2190   // If ByteSize of the splat is bigger than the element size of the
2191   // build_vector, then we have a case where we are checking for a splat where
2192   // multiple elements of the buildvector are folded together into a single
2193   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2194   unsigned EltSize = 16/N->getNumOperands();
2195   if (EltSize < ByteSize) {
2196     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2197     SDValue UniquedVals[4];
2198     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2199 
2200     // See if all of the elements in the buildvector agree across.
2201     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2202       if (N->getOperand(i).isUndef()) continue;
2203       // If the element isn't a constant, bail fully out.
2204       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2205 
2206       if (!UniquedVals[i&(Multiple-1)].getNode())
2207         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2208       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2209         return SDValue();  // no match.
2210     }
2211 
2212     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2213     // either constant or undef values that are identical for each chunk.  See
2214     // if these chunks can form into a larger vspltis*.
2215 
2216     // Check to see if all of the leading entries are either 0 or -1.  If
2217     // neither, then this won't fit into the immediate field.
2218     bool LeadingZero = true;
2219     bool LeadingOnes = true;
2220     for (unsigned i = 0; i != Multiple-1; ++i) {
2221       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2222 
2223       LeadingZero &= isNullConstant(UniquedVals[i]);
2224       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2225     }
2226     // Finally, check the least significant entry.
2227     if (LeadingZero) {
2228       if (!UniquedVals[Multiple-1].getNode())
2229         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2230       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2231       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2232         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2233     }
2234     if (LeadingOnes) {
2235       if (!UniquedVals[Multiple-1].getNode())
2236         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2237       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2238       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2239         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2240     }
2241 
2242     return SDValue();
2243   }
2244 
2245   // Check to see if this buildvec has a single non-undef value in its elements.
2246   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2247     if (N->getOperand(i).isUndef()) continue;
2248     if (!OpVal.getNode())
2249       OpVal = N->getOperand(i);
2250     else if (OpVal != N->getOperand(i))
2251       return SDValue();
2252   }
2253 
2254   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2255 
2256   unsigned ValSizeInBytes = EltSize;
2257   uint64_t Value = 0;
2258   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2259     Value = CN->getZExtValue();
2260   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2261     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2262     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2263   }
2264 
2265   // If the splat value is larger than the element value, then we can never do
2266   // this splat.  The only case that we could fit the replicated bits into our
2267   // immediate field for would be zero, and we prefer to use vxor for it.
2268   if (ValSizeInBytes < ByteSize) return SDValue();
2269 
2270   // If the element value is larger than the splat value, check if it consists
2271   // of a repeated bit pattern of size ByteSize.
2272   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2273     return SDValue();
2274 
2275   // Properly sign extend the value.
2276   int MaskVal = SignExtend32(Value, ByteSize * 8);
2277 
2278   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2279   if (MaskVal == 0) return SDValue();
2280 
2281   // Finally, if this value fits in a 5 bit sext field, return it
2282   if (SignExtend32<5>(MaskVal) == MaskVal)
2283     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2284   return SDValue();
2285 }
2286 
2287 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2288 /// amount, otherwise return -1.
2289 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2290   EVT VT = N->getValueType(0);
2291   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2292     return -1;
2293 
2294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2295 
2296   // Find the first non-undef value in the shuffle mask.
2297   unsigned i;
2298   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2299     /*search*/;
2300 
2301   if (i == 4) return -1;  // all undef.
2302 
2303   // Otherwise, check to see if the rest of the elements are consecutively
2304   // numbered from this value.
2305   unsigned ShiftAmt = SVOp->getMaskElt(i);
2306   if (ShiftAmt < i) return -1;
2307   ShiftAmt -= i;
2308 
2309   // Check the rest of the elements to see if they are consecutive.
2310   for (++i; i != 4; ++i)
2311     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2312       return -1;
2313 
2314   return ShiftAmt;
2315 }
2316 
2317 //===----------------------------------------------------------------------===//
2318 //  Addressing Mode Selection
2319 //===----------------------------------------------------------------------===//
2320 
2321 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2322 /// or 64-bit immediate, and if the value can be accurately represented as a
2323 /// sign extension from a 16-bit value.  If so, this returns true and the
2324 /// immediate.
2325 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2326   if (!isa<ConstantSDNode>(N))
2327     return false;
2328 
2329   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2330   if (N->getValueType(0) == MVT::i32)
2331     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2332   else
2333     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2334 }
2335 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2336   return isIntS16Immediate(Op.getNode(), Imm);
2337 }
2338 
2339 
2340 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2341 /// be represented as an indexed [r+r] operation.
2342 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2343                                                SDValue &Index,
2344                                                SelectionDAG &DAG) const {
2345   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2346       UI != E; ++UI) {
2347     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2348       if (Memop->getMemoryVT() == MVT::f64) {
2349           Base = N.getOperand(0);
2350           Index = N.getOperand(1);
2351           return true;
2352       }
2353     }
2354   }
2355   return false;
2356 }
2357 
2358 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2359 /// can be represented as an indexed [r+r] operation.  Returns false if it
2360 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2361 /// non-zero and N can be represented by a base register plus a signed 16-bit
2362 /// displacement, make a more precise judgement by checking (displacement % \p
2363 /// EncodingAlignment).
2364 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2365                                             SDValue &Index, SelectionDAG &DAG,
2366                                             unsigned EncodingAlignment) const {
2367   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2368   // a [pc+imm].
2369   if (SelectAddressPCRel(N, Base))
2370     return false;
2371 
2372   int16_t imm = 0;
2373   if (N.getOpcode() == ISD::ADD) {
2374     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2375     // SPE load/store can only handle 8-bit offsets.
2376     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2377         return true;
2378     if (isIntS16Immediate(N.getOperand(1), imm) &&
2379         (!EncodingAlignment || !(imm % EncodingAlignment)))
2380       return false; // r+i
2381     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2382       return false;    // r+i
2383 
2384     Base = N.getOperand(0);
2385     Index = N.getOperand(1);
2386     return true;
2387   } else if (N.getOpcode() == ISD::OR) {
2388     if (isIntS16Immediate(N.getOperand(1), imm) &&
2389         (!EncodingAlignment || !(imm % EncodingAlignment)))
2390       return false; // r+i can fold it if we can.
2391 
2392     // If this is an or of disjoint bitfields, we can codegen this as an add
2393     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2394     // disjoint.
2395     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2396 
2397     if (LHSKnown.Zero.getBoolValue()) {
2398       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2399       // If all of the bits are known zero on the LHS or RHS, the add won't
2400       // carry.
2401       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2402         Base = N.getOperand(0);
2403         Index = N.getOperand(1);
2404         return true;
2405       }
2406     }
2407   }
2408 
2409   return false;
2410 }
2411 
2412 // If we happen to be doing an i64 load or store into a stack slot that has
2413 // less than a 4-byte alignment, then the frame-index elimination may need to
2414 // use an indexed load or store instruction (because the offset may not be a
2415 // multiple of 4). The extra register needed to hold the offset comes from the
2416 // register scavenger, and it is possible that the scavenger will need to use
2417 // an emergency spill slot. As a result, we need to make sure that a spill slot
2418 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2419 // stack slot.
2420 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2421   // FIXME: This does not handle the LWA case.
2422   if (VT != MVT::i64)
2423     return;
2424 
2425   // NOTE: We'll exclude negative FIs here, which come from argument
2426   // lowering, because there are no known test cases triggering this problem
2427   // using packed structures (or similar). We can remove this exclusion if
2428   // we find such a test case. The reason why this is so test-case driven is
2429   // because this entire 'fixup' is only to prevent crashes (from the
2430   // register scavenger) on not-really-valid inputs. For example, if we have:
2431   //   %a = alloca i1
2432   //   %b = bitcast i1* %a to i64*
2433   //   store i64* a, i64 b
2434   // then the store should really be marked as 'align 1', but is not. If it
2435   // were marked as 'align 1' then the indexed form would have been
2436   // instruction-selected initially, and the problem this 'fixup' is preventing
2437   // won't happen regardless.
2438   if (FrameIdx < 0)
2439     return;
2440 
2441   MachineFunction &MF = DAG.getMachineFunction();
2442   MachineFrameInfo &MFI = MF.getFrameInfo();
2443 
2444   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2445     return;
2446 
2447   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2448   FuncInfo->setHasNonRISpills();
2449 }
2450 
2451 /// Returns true if the address N can be represented by a base register plus
2452 /// a signed 16-bit displacement [r+imm], and if it is not better
2453 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2454 /// displacements that are multiples of that value.
2455 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2456                                             SDValue &Base,
2457                                             SelectionDAG &DAG,
2458                                             unsigned EncodingAlignment) const {
2459   // FIXME dl should come from parent load or store, not from address
2460   SDLoc dl(N);
2461 
2462   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2463   // a [pc+imm].
2464   if (SelectAddressPCRel(N, Base))
2465     return false;
2466 
2467   // If this can be more profitably realized as r+r, fail.
2468   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2469     return false;
2470 
2471   if (N.getOpcode() == ISD::ADD) {
2472     int16_t imm = 0;
2473     if (isIntS16Immediate(N.getOperand(1), imm) &&
2474         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2475       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2476       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2477         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2478         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2479       } else {
2480         Base = N.getOperand(0);
2481       }
2482       return true; // [r+i]
2483     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2484       // Match LOAD (ADD (X, Lo(G))).
2485       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2486              && "Cannot handle constant offsets yet!");
2487       Disp = N.getOperand(1).getOperand(0);  // The global address.
2488       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2489              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2490              Disp.getOpcode() == ISD::TargetConstantPool ||
2491              Disp.getOpcode() == ISD::TargetJumpTable);
2492       Base = N.getOperand(0);
2493       return true;  // [&g+r]
2494     }
2495   } else if (N.getOpcode() == ISD::OR) {
2496     int16_t imm = 0;
2497     if (isIntS16Immediate(N.getOperand(1), imm) &&
2498         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2499       // If this is an or of disjoint bitfields, we can codegen this as an add
2500       // (for better address arithmetic) if the LHS and RHS of the OR are
2501       // provably disjoint.
2502       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2503 
2504       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2505         // If all of the bits are known zero on the LHS or RHS, the add won't
2506         // carry.
2507         if (FrameIndexSDNode *FI =
2508               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2509           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2510           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2511         } else {
2512           Base = N.getOperand(0);
2513         }
2514         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2515         return true;
2516       }
2517     }
2518   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2519     // Loading from a constant address.
2520 
2521     // If this address fits entirely in a 16-bit sext immediate field, codegen
2522     // this as "d, 0"
2523     int16_t Imm;
2524     if (isIntS16Immediate(CN, Imm) &&
2525         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2526       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2527       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2528                              CN->getValueType(0));
2529       return true;
2530     }
2531 
2532     // Handle 32-bit sext immediates with LIS + addr mode.
2533     if ((CN->getValueType(0) == MVT::i32 ||
2534          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2535         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2536       int Addr = (int)CN->getZExtValue();
2537 
2538       // Otherwise, break this down into an LIS + disp.
2539       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2540 
2541       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2542                                    MVT::i32);
2543       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2544       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2545       return true;
2546     }
2547   }
2548 
2549   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2550   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2551     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2552     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2553   } else
2554     Base = N;
2555   return true;      // [r+0]
2556 }
2557 
2558 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2559 /// represented as an indexed [r+r] operation.
2560 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2561                                                 SDValue &Index,
2562                                                 SelectionDAG &DAG) const {
2563   // Check to see if we can easily represent this as an [r+r] address.  This
2564   // will fail if it thinks that the address is more profitably represented as
2565   // reg+imm, e.g. where imm = 0.
2566   if (SelectAddressRegReg(N, Base, Index, DAG))
2567     return true;
2568 
2569   // If the address is the result of an add, we will utilize the fact that the
2570   // address calculation includes an implicit add.  However, we can reduce
2571   // register pressure if we do not materialize a constant just for use as the
2572   // index register.  We only get rid of the add if it is not an add of a
2573   // value and a 16-bit signed constant and both have a single use.
2574   int16_t imm = 0;
2575   if (N.getOpcode() == ISD::ADD &&
2576       (!isIntS16Immediate(N.getOperand(1), imm) ||
2577        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2578     Base = N.getOperand(0);
2579     Index = N.getOperand(1);
2580     return true;
2581   }
2582 
2583   // Otherwise, do it the hard way, using R0 as the base register.
2584   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2585                          N.getValueType());
2586   Index = N;
2587   return true;
2588 }
2589 
2590 /// Returns true if this address is a PC Relative address.
2591 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG.
2592 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2593   ConstantPoolSDNode *ConstPoolNode =
2594       dyn_cast<ConstantPoolSDNode>(N.getNode());
2595   bool HasFlag = ConstPoolNode &&
2596                  ConstPoolNode->getTargetFlags() == PPCII::MO_PCREL_FLAG;
2597   bool HasNode = N.getOpcode() == PPCISD::MAT_PCREL_ADDR;
2598   if (HasFlag || HasNode) {
2599     Base = N;
2600     return true;
2601   }
2602   return false;
2603 }
2604 
2605 /// Returns true if we should use a direct load into vector instruction
2606 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2607 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2608 
2609   // If there are any other uses other than scalar to vector, then we should
2610   // keep it as a scalar load -> direct move pattern to prevent multiple
2611   // loads.
2612   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2613   if (!LD)
2614     return false;
2615 
2616   EVT MemVT = LD->getMemoryVT();
2617   if (!MemVT.isSimple())
2618     return false;
2619   switch(MemVT.getSimpleVT().SimpleTy) {
2620   case MVT::i64:
2621     break;
2622   case MVT::i32:
2623     if (!ST.hasP8Vector())
2624       return false;
2625     break;
2626   case MVT::i16:
2627   case MVT::i8:
2628     if (!ST.hasP9Vector())
2629       return false;
2630     break;
2631   default:
2632     return false;
2633   }
2634 
2635   SDValue LoadedVal(N, 0);
2636   if (!LoadedVal.hasOneUse())
2637     return false;
2638 
2639   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2640        UI != UE; ++UI)
2641     if (UI.getUse().get().getResNo() == 0 &&
2642         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2643       return false;
2644 
2645   return true;
2646 }
2647 
2648 /// getPreIndexedAddressParts - returns true by value, base pointer and
2649 /// offset pointer and addressing mode by reference if the node's address
2650 /// can be legally represented as pre-indexed load / store address.
2651 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2652                                                   SDValue &Offset,
2653                                                   ISD::MemIndexedMode &AM,
2654                                                   SelectionDAG &DAG) const {
2655   if (DisablePPCPreinc) return false;
2656 
2657   bool isLoad = true;
2658   SDValue Ptr;
2659   EVT VT;
2660   unsigned Alignment;
2661   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2662     Ptr = LD->getBasePtr();
2663     VT = LD->getMemoryVT();
2664     Alignment = LD->getAlignment();
2665   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2666     Ptr = ST->getBasePtr();
2667     VT  = ST->getMemoryVT();
2668     Alignment = ST->getAlignment();
2669     isLoad = false;
2670   } else
2671     return false;
2672 
2673   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2674   // instructions because we can fold these into a more efficient instruction
2675   // instead, (such as LXSD).
2676   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2677     return false;
2678   }
2679 
2680   // PowerPC doesn't have preinc load/store instructions for vectors (except
2681   // for QPX, which does have preinc r+r forms).
2682   if (VT.isVector()) {
2683     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2684       return false;
2685     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2686       AM = ISD::PRE_INC;
2687       return true;
2688     }
2689   }
2690 
2691   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2692     // Common code will reject creating a pre-inc form if the base pointer
2693     // is a frame index, or if N is a store and the base pointer is either
2694     // the same as or a predecessor of the value being stored.  Check for
2695     // those situations here, and try with swapped Base/Offset instead.
2696     bool Swap = false;
2697 
2698     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2699       Swap = true;
2700     else if (!isLoad) {
2701       SDValue Val = cast<StoreSDNode>(N)->getValue();
2702       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2703         Swap = true;
2704     }
2705 
2706     if (Swap)
2707       std::swap(Base, Offset);
2708 
2709     AM = ISD::PRE_INC;
2710     return true;
2711   }
2712 
2713   // LDU/STU can only handle immediates that are a multiple of 4.
2714   if (VT != MVT::i64) {
2715     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2716       return false;
2717   } else {
2718     // LDU/STU need an address with at least 4-byte alignment.
2719     if (Alignment < 4)
2720       return false;
2721 
2722     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2723       return false;
2724   }
2725 
2726   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2727     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2728     // sext i32 to i64 when addr mode is r+i.
2729     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2730         LD->getExtensionType() == ISD::SEXTLOAD &&
2731         isa<ConstantSDNode>(Offset))
2732       return false;
2733   }
2734 
2735   AM = ISD::PRE_INC;
2736   return true;
2737 }
2738 
2739 //===----------------------------------------------------------------------===//
2740 //  LowerOperation implementation
2741 //===----------------------------------------------------------------------===//
2742 
2743 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2744 /// and LoOpFlags to the target MO flags.
2745 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2746                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2747                                const GlobalValue *GV = nullptr) {
2748   HiOpFlags = PPCII::MO_HA;
2749   LoOpFlags = PPCII::MO_LO;
2750 
2751   // Don't use the pic base if not in PIC relocation model.
2752   if (IsPIC) {
2753     HiOpFlags |= PPCII::MO_PIC_FLAG;
2754     LoOpFlags |= PPCII::MO_PIC_FLAG;
2755   }
2756 }
2757 
2758 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2759                              SelectionDAG &DAG) {
2760   SDLoc DL(HiPart);
2761   EVT PtrVT = HiPart.getValueType();
2762   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2763 
2764   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2765   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2766 
2767   // With PIC, the first instruction is actually "GR+hi(&G)".
2768   if (isPIC)
2769     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2770                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2771 
2772   // Generate non-pic code that has direct accesses to the constant pool.
2773   // The address of the global is just (hi(&g)+lo(&g)).
2774   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2775 }
2776 
2777 static void setUsesTOCBasePtr(MachineFunction &MF) {
2778   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2779   FuncInfo->setUsesTOCBasePtr();
2780 }
2781 
2782 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2783   setUsesTOCBasePtr(DAG.getMachineFunction());
2784 }
2785 
2786 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2787                                        SDValue GA) const {
2788   const bool Is64Bit = Subtarget.isPPC64();
2789   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2790   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2791                         : Subtarget.isAIXABI()
2792                               ? DAG.getRegister(PPC::R2, VT)
2793                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2794   SDValue Ops[] = { GA, Reg };
2795   return DAG.getMemIntrinsicNode(
2796       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2797       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2798       MachineMemOperand::MOLoad);
2799 }
2800 
2801 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2802                                              SelectionDAG &DAG) const {
2803   EVT PtrVT = Op.getValueType();
2804   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2805   const Constant *C = CP->getConstVal();
2806 
2807   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2808   // The actual address of the GlobalValue is stored in the TOC.
2809   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2810     if (Subtarget.hasPCRelativeMemops()) {
2811       SDLoc DL(CP);
2812       EVT Ty = getPointerTy(DAG.getDataLayout());
2813       SDValue ConstPool = DAG.getTargetConstantPool(C, Ty,
2814                                                     CP->getAlignment(),
2815                                                     CP->getOffset(),
2816                                                     PPCII::MO_PCREL_FLAG);
2817       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2818     }
2819     setUsesTOCBasePtr(DAG);
2820     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2821     return getTOCEntry(DAG, SDLoc(CP), GA);
2822   }
2823 
2824   unsigned MOHiFlag, MOLoFlag;
2825   bool IsPIC = isPositionIndependent();
2826   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2827 
2828   if (IsPIC && Subtarget.isSVR4ABI()) {
2829     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2830                                            PPCII::MO_PIC_FLAG);
2831     return getTOCEntry(DAG, SDLoc(CP), GA);
2832   }
2833 
2834   SDValue CPIHi =
2835     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2836   SDValue CPILo =
2837     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2838   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2839 }
2840 
2841 // For 64-bit PowerPC, prefer the more compact relative encodings.
2842 // This trades 32 bits per jump table entry for one or two instructions
2843 // on the jump site.
2844 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2845   if (isJumpTableRelative())
2846     return MachineJumpTableInfo::EK_LabelDifference32;
2847 
2848   return TargetLowering::getJumpTableEncoding();
2849 }
2850 
2851 bool PPCTargetLowering::isJumpTableRelative() const {
2852   if (UseAbsoluteJumpTables)
2853     return false;
2854   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2855     return true;
2856   return TargetLowering::isJumpTableRelative();
2857 }
2858 
2859 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2860                                                     SelectionDAG &DAG) const {
2861   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2862     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2863 
2864   switch (getTargetMachine().getCodeModel()) {
2865   case CodeModel::Small:
2866   case CodeModel::Medium:
2867     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2868   default:
2869     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2870                        getPointerTy(DAG.getDataLayout()));
2871   }
2872 }
2873 
2874 const MCExpr *
2875 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2876                                                 unsigned JTI,
2877                                                 MCContext &Ctx) const {
2878   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2879     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2880 
2881   switch (getTargetMachine().getCodeModel()) {
2882   case CodeModel::Small:
2883   case CodeModel::Medium:
2884     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2885   default:
2886     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2887   }
2888 }
2889 
2890 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2891   EVT PtrVT = Op.getValueType();
2892   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2893 
2894   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2895   // The actual address of the GlobalValue is stored in the TOC.
2896   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2897     setUsesTOCBasePtr(DAG);
2898     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2899     return getTOCEntry(DAG, SDLoc(JT), GA);
2900   }
2901 
2902   unsigned MOHiFlag, MOLoFlag;
2903   bool IsPIC = isPositionIndependent();
2904   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2905 
2906   if (IsPIC && Subtarget.isSVR4ABI()) {
2907     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2908                                         PPCII::MO_PIC_FLAG);
2909     return getTOCEntry(DAG, SDLoc(GA), GA);
2910   }
2911 
2912   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2913   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2914   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2915 }
2916 
2917 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2918                                              SelectionDAG &DAG) const {
2919   EVT PtrVT = Op.getValueType();
2920   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2921   const BlockAddress *BA = BASDN->getBlockAddress();
2922 
2923   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2924   // The actual BlockAddress is stored in the TOC.
2925   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2926     setUsesTOCBasePtr(DAG);
2927     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2928     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2929   }
2930 
2931   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2932   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2933     return getTOCEntry(
2934         DAG, SDLoc(BASDN),
2935         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2936 
2937   unsigned MOHiFlag, MOLoFlag;
2938   bool IsPIC = isPositionIndependent();
2939   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2940   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2941   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2942   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2943 }
2944 
2945 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2946                                               SelectionDAG &DAG) const {
2947   // FIXME: TLS addresses currently use medium model code sequences,
2948   // which is the most useful form.  Eventually support for small and
2949   // large models could be added if users need it, at the cost of
2950   // additional complexity.
2951   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2952   if (DAG.getTarget().useEmulatedTLS())
2953     return LowerToTLSEmulatedModel(GA, DAG);
2954 
2955   SDLoc dl(GA);
2956   const GlobalValue *GV = GA->getGlobal();
2957   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2958   bool is64bit = Subtarget.isPPC64();
2959   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2960   PICLevel::Level picLevel = M->getPICLevel();
2961 
2962   const TargetMachine &TM = getTargetMachine();
2963   TLSModel::Model Model = TM.getTLSModel(GV);
2964 
2965   if (Model == TLSModel::LocalExec) {
2966     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2967                                                PPCII::MO_TPREL_HA);
2968     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2969                                                PPCII::MO_TPREL_LO);
2970     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2971                              : DAG.getRegister(PPC::R2, MVT::i32);
2972 
2973     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2974     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2975   }
2976 
2977   if (Model == TLSModel::InitialExec) {
2978     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2979     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2980                                                 PPCII::MO_TLS);
2981     SDValue GOTPtr;
2982     if (is64bit) {
2983       setUsesTOCBasePtr(DAG);
2984       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2985       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2986                            PtrVT, GOTReg, TGA);
2987     } else {
2988       if (!TM.isPositionIndependent())
2989         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2990       else if (picLevel == PICLevel::SmallPIC)
2991         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2992       else
2993         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2994     }
2995     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2996                                    PtrVT, TGA, GOTPtr);
2997     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2998   }
2999 
3000   if (Model == TLSModel::GeneralDynamic) {
3001     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3002     SDValue GOTPtr;
3003     if (is64bit) {
3004       setUsesTOCBasePtr(DAG);
3005       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3006       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3007                                    GOTReg, TGA);
3008     } else {
3009       if (picLevel == PICLevel::SmallPIC)
3010         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3011       else
3012         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3013     }
3014     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3015                        GOTPtr, TGA, TGA);
3016   }
3017 
3018   if (Model == TLSModel::LocalDynamic) {
3019     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3020     SDValue GOTPtr;
3021     if (is64bit) {
3022       setUsesTOCBasePtr(DAG);
3023       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3024       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3025                            GOTReg, TGA);
3026     } else {
3027       if (picLevel == PICLevel::SmallPIC)
3028         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3029       else
3030         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3031     }
3032     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3033                                   PtrVT, GOTPtr, TGA, TGA);
3034     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3035                                       PtrVT, TLSAddr, TGA);
3036     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3037   }
3038 
3039   llvm_unreachable("Unknown TLS model!");
3040 }
3041 
3042 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3043                                               SelectionDAG &DAG) const {
3044   EVT PtrVT = Op.getValueType();
3045   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3046   SDLoc DL(GSDN);
3047   const GlobalValue *GV = GSDN->getGlobal();
3048 
3049   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3050   // The actual address of the GlobalValue is stored in the TOC.
3051   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3052     setUsesTOCBasePtr(DAG);
3053     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3054     return getTOCEntry(DAG, DL, GA);
3055   }
3056 
3057   unsigned MOHiFlag, MOLoFlag;
3058   bool IsPIC = isPositionIndependent();
3059   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3060 
3061   if (IsPIC && Subtarget.isSVR4ABI()) {
3062     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3063                                             GSDN->getOffset(),
3064                                             PPCII::MO_PIC_FLAG);
3065     return getTOCEntry(DAG, DL, GA);
3066   }
3067 
3068   SDValue GAHi =
3069     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3070   SDValue GALo =
3071     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3072 
3073   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3074 }
3075 
3076 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3077   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3078   SDLoc dl(Op);
3079 
3080   if (Op.getValueType() == MVT::v2i64) {
3081     // When the operands themselves are v2i64 values, we need to do something
3082     // special because VSX has no underlying comparison operations for these.
3083     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3084       // Equality can be handled by casting to the legal type for Altivec
3085       // comparisons, everything else needs to be expanded.
3086       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3087         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3088                  DAG.getSetCC(dl, MVT::v4i32,
3089                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3090                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3091                    CC));
3092       }
3093 
3094       return SDValue();
3095     }
3096 
3097     // We handle most of these in the usual way.
3098     return Op;
3099   }
3100 
3101   // If we're comparing for equality to zero, expose the fact that this is
3102   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3103   // fold the new nodes.
3104   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3105     return V;
3106 
3107   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3108     // Leave comparisons against 0 and -1 alone for now, since they're usually
3109     // optimized.  FIXME: revisit this when we can custom lower all setcc
3110     // optimizations.
3111     if (C->isAllOnesValue() || C->isNullValue())
3112       return SDValue();
3113   }
3114 
3115   // If we have an integer seteq/setne, turn it into a compare against zero
3116   // by xor'ing the rhs with the lhs, which is faster than setting a
3117   // condition register, reading it back out, and masking the correct bit.  The
3118   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3119   // the result to other bit-twiddling opportunities.
3120   EVT LHSVT = Op.getOperand(0).getValueType();
3121   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3122     EVT VT = Op.getValueType();
3123     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3124                                 Op.getOperand(1));
3125     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3126   }
3127   return SDValue();
3128 }
3129 
3130 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3131   SDNode *Node = Op.getNode();
3132   EVT VT = Node->getValueType(0);
3133   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3134   SDValue InChain = Node->getOperand(0);
3135   SDValue VAListPtr = Node->getOperand(1);
3136   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3137   SDLoc dl(Node);
3138 
3139   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3140 
3141   // gpr_index
3142   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3143                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3144   InChain = GprIndex.getValue(1);
3145 
3146   if (VT == MVT::i64) {
3147     // Check if GprIndex is even
3148     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3149                                  DAG.getConstant(1, dl, MVT::i32));
3150     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3151                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3152     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3153                                           DAG.getConstant(1, dl, MVT::i32));
3154     // Align GprIndex to be even if it isn't
3155     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3156                            GprIndex);
3157   }
3158 
3159   // fpr index is 1 byte after gpr
3160   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3161                                DAG.getConstant(1, dl, MVT::i32));
3162 
3163   // fpr
3164   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3165                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3166   InChain = FprIndex.getValue(1);
3167 
3168   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3169                                        DAG.getConstant(8, dl, MVT::i32));
3170 
3171   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3172                                         DAG.getConstant(4, dl, MVT::i32));
3173 
3174   // areas
3175   SDValue OverflowArea =
3176       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3177   InChain = OverflowArea.getValue(1);
3178 
3179   SDValue RegSaveArea =
3180       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3181   InChain = RegSaveArea.getValue(1);
3182 
3183   // select overflow_area if index > 8
3184   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3185                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3186 
3187   // adjustment constant gpr_index * 4/8
3188   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3189                                     VT.isInteger() ? GprIndex : FprIndex,
3190                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3191                                                     MVT::i32));
3192 
3193   // OurReg = RegSaveArea + RegConstant
3194   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3195                                RegConstant);
3196 
3197   // Floating types are 32 bytes into RegSaveArea
3198   if (VT.isFloatingPoint())
3199     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3200                          DAG.getConstant(32, dl, MVT::i32));
3201 
3202   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3203   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3204                                    VT.isInteger() ? GprIndex : FprIndex,
3205                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3206                                                    MVT::i32));
3207 
3208   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3209                               VT.isInteger() ? VAListPtr : FprPtr,
3210                               MachinePointerInfo(SV), MVT::i8);
3211 
3212   // determine if we should load from reg_save_area or overflow_area
3213   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3214 
3215   // increase overflow_area by 4/8 if gpr/fpr > 8
3216   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3217                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3218                                           dl, MVT::i32));
3219 
3220   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3221                              OverflowAreaPlusN);
3222 
3223   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3224                               MachinePointerInfo(), MVT::i32);
3225 
3226   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3227 }
3228 
3229 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3230   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3231 
3232   // We have to copy the entire va_list struct:
3233   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3234   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3235                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3236                        false, true, false, MachinePointerInfo(),
3237                        MachinePointerInfo());
3238 }
3239 
3240 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3241                                                   SelectionDAG &DAG) const {
3242   if (Subtarget.isAIXABI())
3243     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3244 
3245   return Op.getOperand(0);
3246 }
3247 
3248 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3249                                                 SelectionDAG &DAG) const {
3250   if (Subtarget.isAIXABI())
3251     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3252 
3253   SDValue Chain = Op.getOperand(0);
3254   SDValue Trmp = Op.getOperand(1); // trampoline
3255   SDValue FPtr = Op.getOperand(2); // nested function
3256   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3257   SDLoc dl(Op);
3258 
3259   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3260   bool isPPC64 = (PtrVT == MVT::i64);
3261   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3262 
3263   TargetLowering::ArgListTy Args;
3264   TargetLowering::ArgListEntry Entry;
3265 
3266   Entry.Ty = IntPtrTy;
3267   Entry.Node = Trmp; Args.push_back(Entry);
3268 
3269   // TrampSize == (isPPC64 ? 48 : 40);
3270   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3271                                isPPC64 ? MVT::i64 : MVT::i32);
3272   Args.push_back(Entry);
3273 
3274   Entry.Node = FPtr; Args.push_back(Entry);
3275   Entry.Node = Nest; Args.push_back(Entry);
3276 
3277   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3278   TargetLowering::CallLoweringInfo CLI(DAG);
3279   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3280       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3281       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3282 
3283   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3284   return CallResult.second;
3285 }
3286 
3287 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3288   MachineFunction &MF = DAG.getMachineFunction();
3289   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3290   EVT PtrVT = getPointerTy(MF.getDataLayout());
3291 
3292   SDLoc dl(Op);
3293 
3294   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3295     // vastart just stores the address of the VarArgsFrameIndex slot into the
3296     // memory location argument.
3297     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3298     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3299     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3300                         MachinePointerInfo(SV));
3301   }
3302 
3303   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3304   // We suppose the given va_list is already allocated.
3305   //
3306   // typedef struct {
3307   //  char gpr;     /* index into the array of 8 GPRs
3308   //                 * stored in the register save area
3309   //                 * gpr=0 corresponds to r3,
3310   //                 * gpr=1 to r4, etc.
3311   //                 */
3312   //  char fpr;     /* index into the array of 8 FPRs
3313   //                 * stored in the register save area
3314   //                 * fpr=0 corresponds to f1,
3315   //                 * fpr=1 to f2, etc.
3316   //                 */
3317   //  char *overflow_arg_area;
3318   //                /* location on stack that holds
3319   //                 * the next overflow argument
3320   //                 */
3321   //  char *reg_save_area;
3322   //               /* where r3:r10 and f1:f8 (if saved)
3323   //                * are stored
3324   //                */
3325   // } va_list[1];
3326 
3327   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3328   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3329   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3330                                             PtrVT);
3331   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3332                                  PtrVT);
3333 
3334   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3335   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3336 
3337   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3338   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3339 
3340   uint64_t FPROffset = 1;
3341   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3342 
3343   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3344 
3345   // Store first byte : number of int regs
3346   SDValue firstStore =
3347       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3348                         MachinePointerInfo(SV), MVT::i8);
3349   uint64_t nextOffset = FPROffset;
3350   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3351                                   ConstFPROffset);
3352 
3353   // Store second byte : number of float regs
3354   SDValue secondStore =
3355       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3356                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3357   nextOffset += StackOffset;
3358   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3359 
3360   // Store second word : arguments given on stack
3361   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3362                                     MachinePointerInfo(SV, nextOffset));
3363   nextOffset += FrameOffset;
3364   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3365 
3366   // Store third word : arguments given in registers
3367   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3368                       MachinePointerInfo(SV, nextOffset));
3369 }
3370 
3371 /// FPR - The set of FP registers that should be allocated for arguments
3372 /// on Darwin and AIX.
3373 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3374                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3375                                 PPC::F11, PPC::F12, PPC::F13};
3376 
3377 /// QFPR - The set of QPX registers that should be allocated for arguments.
3378 static const MCPhysReg QFPR[] = {
3379     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3380     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3381 
3382 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3383 /// the stack.
3384 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3385                                        unsigned PtrByteSize) {
3386   unsigned ArgSize = ArgVT.getStoreSize();
3387   if (Flags.isByVal())
3388     ArgSize = Flags.getByValSize();
3389 
3390   // Round up to multiples of the pointer size, except for array members,
3391   // which are always packed.
3392   if (!Flags.isInConsecutiveRegs())
3393     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3394 
3395   return ArgSize;
3396 }
3397 
3398 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3399 /// on the stack.
3400 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3401                                          ISD::ArgFlagsTy Flags,
3402                                          unsigned PtrByteSize) {
3403   Align Alignment(PtrByteSize);
3404 
3405   // Altivec parameters are padded to a 16 byte boundary.
3406   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3407       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3408       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3409       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3410     Alignment = Align(16);
3411   // QPX vector types stored in double-precision are padded to a 32 byte
3412   // boundary.
3413   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3414     Alignment = Align(32);
3415 
3416   // ByVal parameters are aligned as requested.
3417   if (Flags.isByVal()) {
3418     auto BVAlign = Flags.getNonZeroByValAlign();
3419     if (BVAlign > PtrByteSize) {
3420       if (BVAlign.value() % PtrByteSize != 0)
3421         llvm_unreachable(
3422             "ByVal alignment is not a multiple of the pointer size");
3423 
3424       Alignment = BVAlign;
3425     }
3426   }
3427 
3428   // Array members are always packed to their original alignment.
3429   if (Flags.isInConsecutiveRegs()) {
3430     // If the array member was split into multiple registers, the first
3431     // needs to be aligned to the size of the full type.  (Except for
3432     // ppcf128, which is only aligned as its f64 components.)
3433     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3434       Alignment = Align(OrigVT.getStoreSize());
3435     else
3436       Alignment = Align(ArgVT.getStoreSize());
3437   }
3438 
3439   return Alignment;
3440 }
3441 
3442 /// CalculateStackSlotUsed - Return whether this argument will use its
3443 /// stack slot (instead of being passed in registers).  ArgOffset,
3444 /// AvailableFPRs, and AvailableVRs must hold the current argument
3445 /// position, and will be updated to account for this argument.
3446 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3447                                    ISD::ArgFlagsTy Flags,
3448                                    unsigned PtrByteSize,
3449                                    unsigned LinkageSize,
3450                                    unsigned ParamAreaSize,
3451                                    unsigned &ArgOffset,
3452                                    unsigned &AvailableFPRs,
3453                                    unsigned &AvailableVRs, bool HasQPX) {
3454   bool UseMemory = false;
3455 
3456   // Respect alignment of argument on the stack.
3457   Align Alignment =
3458       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3459   ArgOffset = alignTo(ArgOffset, Alignment);
3460   // If there's no space left in the argument save area, we must
3461   // use memory (this check also catches zero-sized arguments).
3462   if (ArgOffset >= LinkageSize + ParamAreaSize)
3463     UseMemory = true;
3464 
3465   // Allocate argument on the stack.
3466   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3467   if (Flags.isInConsecutiveRegsLast())
3468     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3469   // If we overran the argument save area, we must use memory
3470   // (this check catches arguments passed partially in memory)
3471   if (ArgOffset > LinkageSize + ParamAreaSize)
3472     UseMemory = true;
3473 
3474   // However, if the argument is actually passed in an FPR or a VR,
3475   // we don't use memory after all.
3476   if (!Flags.isByVal()) {
3477     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3478         // QPX registers overlap with the scalar FP registers.
3479         (HasQPX && (ArgVT == MVT::v4f32 ||
3480                     ArgVT == MVT::v4f64 ||
3481                     ArgVT == MVT::v4i1)))
3482       if (AvailableFPRs > 0) {
3483         --AvailableFPRs;
3484         return false;
3485       }
3486     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3487         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3488         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3489         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3490       if (AvailableVRs > 0) {
3491         --AvailableVRs;
3492         return false;
3493       }
3494   }
3495 
3496   return UseMemory;
3497 }
3498 
3499 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3500 /// ensure minimum alignment required for target.
3501 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3502                                      unsigned NumBytes) {
3503   return alignTo(NumBytes, Lowering->getStackAlign());
3504 }
3505 
3506 SDValue PPCTargetLowering::LowerFormalArguments(
3507     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3508     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3509     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3510   if (Subtarget.isAIXABI())
3511     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3512                                     InVals);
3513   if (Subtarget.is64BitELFABI())
3514     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3515                                        InVals);
3516   if (Subtarget.is32BitELFABI())
3517     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3518                                        InVals);
3519 
3520   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3521                                      InVals);
3522 }
3523 
3524 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3525     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3526     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3527     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3528 
3529   // 32-bit SVR4 ABI Stack Frame Layout:
3530   //              +-----------------------------------+
3531   //        +-->  |            Back chain             |
3532   //        |     +-----------------------------------+
3533   //        |     | Floating-point register save area |
3534   //        |     +-----------------------------------+
3535   //        |     |    General register save area     |
3536   //        |     +-----------------------------------+
3537   //        |     |          CR save word             |
3538   //        |     +-----------------------------------+
3539   //        |     |         VRSAVE save word          |
3540   //        |     +-----------------------------------+
3541   //        |     |         Alignment padding         |
3542   //        |     +-----------------------------------+
3543   //        |     |     Vector register save area     |
3544   //        |     +-----------------------------------+
3545   //        |     |       Local variable space        |
3546   //        |     +-----------------------------------+
3547   //        |     |        Parameter list area        |
3548   //        |     +-----------------------------------+
3549   //        |     |           LR save word            |
3550   //        |     +-----------------------------------+
3551   // SP-->  +---  |            Back chain             |
3552   //              +-----------------------------------+
3553   //
3554   // Specifications:
3555   //   System V Application Binary Interface PowerPC Processor Supplement
3556   //   AltiVec Technology Programming Interface Manual
3557 
3558   MachineFunction &MF = DAG.getMachineFunction();
3559   MachineFrameInfo &MFI = MF.getFrameInfo();
3560   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3561 
3562   EVT PtrVT = getPointerTy(MF.getDataLayout());
3563   // Potential tail calls could cause overwriting of argument stack slots.
3564   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3565                        (CallConv == CallingConv::Fast));
3566   unsigned PtrByteSize = 4;
3567 
3568   // Assign locations to all of the incoming arguments.
3569   SmallVector<CCValAssign, 16> ArgLocs;
3570   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3571                  *DAG.getContext());
3572 
3573   // Reserve space for the linkage area on the stack.
3574   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3575   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3576   if (useSoftFloat())
3577     CCInfo.PreAnalyzeFormalArguments(Ins);
3578 
3579   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3580   CCInfo.clearWasPPCF128();
3581 
3582   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3583     CCValAssign &VA = ArgLocs[i];
3584 
3585     // Arguments stored in registers.
3586     if (VA.isRegLoc()) {
3587       const TargetRegisterClass *RC;
3588       EVT ValVT = VA.getValVT();
3589 
3590       switch (ValVT.getSimpleVT().SimpleTy) {
3591         default:
3592           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3593         case MVT::i1:
3594         case MVT::i32:
3595           RC = &PPC::GPRCRegClass;
3596           break;
3597         case MVT::f32:
3598           if (Subtarget.hasP8Vector())
3599             RC = &PPC::VSSRCRegClass;
3600           else if (Subtarget.hasSPE())
3601             RC = &PPC::GPRCRegClass;
3602           else
3603             RC = &PPC::F4RCRegClass;
3604           break;
3605         case MVT::f64:
3606           if (Subtarget.hasVSX())
3607             RC = &PPC::VSFRCRegClass;
3608           else if (Subtarget.hasSPE())
3609             // SPE passes doubles in GPR pairs.
3610             RC = &PPC::GPRCRegClass;
3611           else
3612             RC = &PPC::F8RCRegClass;
3613           break;
3614         case MVT::v16i8:
3615         case MVT::v8i16:
3616         case MVT::v4i32:
3617           RC = &PPC::VRRCRegClass;
3618           break;
3619         case MVT::v4f32:
3620           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3621           break;
3622         case MVT::v2f64:
3623         case MVT::v2i64:
3624           RC = &PPC::VRRCRegClass;
3625           break;
3626         case MVT::v4f64:
3627           RC = &PPC::QFRCRegClass;
3628           break;
3629         case MVT::v4i1:
3630           RC = &PPC::QBRCRegClass;
3631           break;
3632       }
3633 
3634       SDValue ArgValue;
3635       // Transform the arguments stored in physical registers into
3636       // virtual ones.
3637       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3638         assert(i + 1 < e && "No second half of double precision argument");
3639         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3640         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3641         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3642         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3643         if (!Subtarget.isLittleEndian())
3644           std::swap (ArgValueLo, ArgValueHi);
3645         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3646                                ArgValueHi);
3647       } else {
3648         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3649         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3650                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3651         if (ValVT == MVT::i1)
3652           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3653       }
3654 
3655       InVals.push_back(ArgValue);
3656     } else {
3657       // Argument stored in memory.
3658       assert(VA.isMemLoc());
3659 
3660       // Get the extended size of the argument type in stack
3661       unsigned ArgSize = VA.getLocVT().getStoreSize();
3662       // Get the actual size of the argument type
3663       unsigned ObjSize = VA.getValVT().getStoreSize();
3664       unsigned ArgOffset = VA.getLocMemOffset();
3665       // Stack objects in PPC32 are right justified.
3666       ArgOffset += ArgSize - ObjSize;
3667       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3668 
3669       // Create load nodes to retrieve arguments from the stack.
3670       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3671       InVals.push_back(
3672           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3673     }
3674   }
3675 
3676   // Assign locations to all of the incoming aggregate by value arguments.
3677   // Aggregates passed by value are stored in the local variable space of the
3678   // caller's stack frame, right above the parameter list area.
3679   SmallVector<CCValAssign, 16> ByValArgLocs;
3680   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3681                       ByValArgLocs, *DAG.getContext());
3682 
3683   // Reserve stack space for the allocations in CCInfo.
3684   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3685 
3686   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3687 
3688   // Area that is at least reserved in the caller of this function.
3689   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3690   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3691 
3692   // Set the size that is at least reserved in caller of this function.  Tail
3693   // call optimized function's reserved stack space needs to be aligned so that
3694   // taking the difference between two stack areas will result in an aligned
3695   // stack.
3696   MinReservedArea =
3697       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3698   FuncInfo->setMinReservedArea(MinReservedArea);
3699 
3700   SmallVector<SDValue, 8> MemOps;
3701 
3702   // If the function takes variable number of arguments, make a frame index for
3703   // the start of the first vararg value... for expansion of llvm.va_start.
3704   if (isVarArg) {
3705     static const MCPhysReg GPArgRegs[] = {
3706       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3707       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3708     };
3709     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3710 
3711     static const MCPhysReg FPArgRegs[] = {
3712       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3713       PPC::F8
3714     };
3715     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3716 
3717     if (useSoftFloat() || hasSPE())
3718        NumFPArgRegs = 0;
3719 
3720     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3721     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3722 
3723     // Make room for NumGPArgRegs and NumFPArgRegs.
3724     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3725                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3726 
3727     FuncInfo->setVarArgsStackOffset(
3728       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3729                             CCInfo.getNextStackOffset(), true));
3730 
3731     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3732     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3733 
3734     // The fixed integer arguments of a variadic function are stored to the
3735     // VarArgsFrameIndex on the stack so that they may be loaded by
3736     // dereferencing the result of va_next.
3737     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3738       // Get an existing live-in vreg, or add a new one.
3739       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3740       if (!VReg)
3741         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3742 
3743       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3744       SDValue Store =
3745           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3746       MemOps.push_back(Store);
3747       // Increment the address by four for the next argument to store
3748       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3749       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3750     }
3751 
3752     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3753     // is set.
3754     // The double arguments are stored to the VarArgsFrameIndex
3755     // on the stack.
3756     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3757       // Get an existing live-in vreg, or add a new one.
3758       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3759       if (!VReg)
3760         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3761 
3762       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3763       SDValue Store =
3764           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3765       MemOps.push_back(Store);
3766       // Increment the address by eight for the next argument to store
3767       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3768                                          PtrVT);
3769       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3770     }
3771   }
3772 
3773   if (!MemOps.empty())
3774     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3775 
3776   return Chain;
3777 }
3778 
3779 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3780 // value to MVT::i64 and then truncate to the correct register size.
3781 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3782                                              EVT ObjectVT, SelectionDAG &DAG,
3783                                              SDValue ArgVal,
3784                                              const SDLoc &dl) const {
3785   if (Flags.isSExt())
3786     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3787                          DAG.getValueType(ObjectVT));
3788   else if (Flags.isZExt())
3789     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3790                          DAG.getValueType(ObjectVT));
3791 
3792   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3793 }
3794 
3795 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3796     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3797     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3798     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3799   // TODO: add description of PPC stack frame format, or at least some docs.
3800   //
3801   bool isELFv2ABI = Subtarget.isELFv2ABI();
3802   bool isLittleEndian = Subtarget.isLittleEndian();
3803   MachineFunction &MF = DAG.getMachineFunction();
3804   MachineFrameInfo &MFI = MF.getFrameInfo();
3805   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3806 
3807   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3808          "fastcc not supported on varargs functions");
3809 
3810   EVT PtrVT = getPointerTy(MF.getDataLayout());
3811   // Potential tail calls could cause overwriting of argument stack slots.
3812   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3813                        (CallConv == CallingConv::Fast));
3814   unsigned PtrByteSize = 8;
3815   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3816 
3817   static const MCPhysReg GPR[] = {
3818     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3819     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3820   };
3821   static const MCPhysReg VR[] = {
3822     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3823     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3824   };
3825 
3826   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3827   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3828   const unsigned Num_VR_Regs  = array_lengthof(VR);
3829   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3830 
3831   // Do a first pass over the arguments to determine whether the ABI
3832   // guarantees that our caller has allocated the parameter save area
3833   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3834   // in the ELFv2 ABI, it is true if this is a vararg function or if
3835   // any parameter is located in a stack slot.
3836 
3837   bool HasParameterArea = !isELFv2ABI || isVarArg;
3838   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3839   unsigned NumBytes = LinkageSize;
3840   unsigned AvailableFPRs = Num_FPR_Regs;
3841   unsigned AvailableVRs = Num_VR_Regs;
3842   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3843     if (Ins[i].Flags.isNest())
3844       continue;
3845 
3846     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3847                                PtrByteSize, LinkageSize, ParamAreaSize,
3848                                NumBytes, AvailableFPRs, AvailableVRs,
3849                                Subtarget.hasQPX()))
3850       HasParameterArea = true;
3851   }
3852 
3853   // Add DAG nodes to load the arguments or copy them out of registers.  On
3854   // entry to a function on PPC, the arguments start after the linkage area,
3855   // although the first ones are often in registers.
3856 
3857   unsigned ArgOffset = LinkageSize;
3858   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3859   unsigned &QFPR_idx = FPR_idx;
3860   SmallVector<SDValue, 8> MemOps;
3861   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3862   unsigned CurArgIdx = 0;
3863   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3864     SDValue ArgVal;
3865     bool needsLoad = false;
3866     EVT ObjectVT = Ins[ArgNo].VT;
3867     EVT OrigVT = Ins[ArgNo].ArgVT;
3868     unsigned ObjSize = ObjectVT.getStoreSize();
3869     unsigned ArgSize = ObjSize;
3870     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3871     if (Ins[ArgNo].isOrigArg()) {
3872       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3873       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3874     }
3875     // We re-align the argument offset for each argument, except when using the
3876     // fast calling convention, when we need to make sure we do that only when
3877     // we'll actually use a stack slot.
3878     unsigned CurArgOffset;
3879     Align Alignment;
3880     auto ComputeArgOffset = [&]() {
3881       /* Respect alignment of argument on the stack.  */
3882       Alignment =
3883           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3884       ArgOffset = alignTo(ArgOffset, Alignment);
3885       CurArgOffset = ArgOffset;
3886     };
3887 
3888     if (CallConv != CallingConv::Fast) {
3889       ComputeArgOffset();
3890 
3891       /* Compute GPR index associated with argument offset.  */
3892       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3893       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3894     }
3895 
3896     // FIXME the codegen can be much improved in some cases.
3897     // We do not have to keep everything in memory.
3898     if (Flags.isByVal()) {
3899       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3900 
3901       if (CallConv == CallingConv::Fast)
3902         ComputeArgOffset();
3903 
3904       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3905       ObjSize = Flags.getByValSize();
3906       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3907       // Empty aggregate parameters do not take up registers.  Examples:
3908       //   struct { } a;
3909       //   union  { } b;
3910       //   int c[0];
3911       // etc.  However, we have to provide a place-holder in InVals, so
3912       // pretend we have an 8-byte item at the current address for that
3913       // purpose.
3914       if (!ObjSize) {
3915         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3916         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3917         InVals.push_back(FIN);
3918         continue;
3919       }
3920 
3921       // Create a stack object covering all stack doublewords occupied
3922       // by the argument.  If the argument is (fully or partially) on
3923       // the stack, or if the argument is fully in registers but the
3924       // caller has allocated the parameter save anyway, we can refer
3925       // directly to the caller's stack frame.  Otherwise, create a
3926       // local copy in our own frame.
3927       int FI;
3928       if (HasParameterArea ||
3929           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3930         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3931       else
3932         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3933       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3934 
3935       // Handle aggregates smaller than 8 bytes.
3936       if (ObjSize < PtrByteSize) {
3937         // The value of the object is its address, which differs from the
3938         // address of the enclosing doubleword on big-endian systems.
3939         SDValue Arg = FIN;
3940         if (!isLittleEndian) {
3941           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3942           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3943         }
3944         InVals.push_back(Arg);
3945 
3946         if (GPR_idx != Num_GPR_Regs) {
3947           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3948           FuncInfo->addLiveInAttr(VReg, Flags);
3949           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3950           SDValue Store;
3951 
3952           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3953             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3954                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3955             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3956                                       MachinePointerInfo(&*FuncArg), ObjType);
3957           } else {
3958             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3959             // store the whole register as-is to the parameter save area
3960             // slot.
3961             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3962                                  MachinePointerInfo(&*FuncArg));
3963           }
3964 
3965           MemOps.push_back(Store);
3966         }
3967         // Whether we copied from a register or not, advance the offset
3968         // into the parameter save area by a full doubleword.
3969         ArgOffset += PtrByteSize;
3970         continue;
3971       }
3972 
3973       // The value of the object is its address, which is the address of
3974       // its first stack doubleword.
3975       InVals.push_back(FIN);
3976 
3977       // Store whatever pieces of the object are in registers to memory.
3978       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3979         if (GPR_idx == Num_GPR_Regs)
3980           break;
3981 
3982         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3983         FuncInfo->addLiveInAttr(VReg, Flags);
3984         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3985         SDValue Addr = FIN;
3986         if (j) {
3987           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3988           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3989         }
3990         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3991                                      MachinePointerInfo(&*FuncArg, j));
3992         MemOps.push_back(Store);
3993         ++GPR_idx;
3994       }
3995       ArgOffset += ArgSize;
3996       continue;
3997     }
3998 
3999     switch (ObjectVT.getSimpleVT().SimpleTy) {
4000     default: llvm_unreachable("Unhandled argument type!");
4001     case MVT::i1:
4002     case MVT::i32:
4003     case MVT::i64:
4004       if (Flags.isNest()) {
4005         // The 'nest' parameter, if any, is passed in R11.
4006         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4007         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4008 
4009         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4010           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4011 
4012         break;
4013       }
4014 
4015       // These can be scalar arguments or elements of an integer array type
4016       // passed directly.  Clang may use those instead of "byval" aggregate
4017       // types to avoid forcing arguments to memory unnecessarily.
4018       if (GPR_idx != Num_GPR_Regs) {
4019         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4020         FuncInfo->addLiveInAttr(VReg, Flags);
4021         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4022 
4023         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4024           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4025           // value to MVT::i64 and then truncate to the correct register size.
4026           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4027       } else {
4028         if (CallConv == CallingConv::Fast)
4029           ComputeArgOffset();
4030 
4031         needsLoad = true;
4032         ArgSize = PtrByteSize;
4033       }
4034       if (CallConv != CallingConv::Fast || needsLoad)
4035         ArgOffset += 8;
4036       break;
4037 
4038     case MVT::f32:
4039     case MVT::f64:
4040       // These can be scalar arguments or elements of a float array type
4041       // passed directly.  The latter are used to implement ELFv2 homogenous
4042       // float aggregates.
4043       if (FPR_idx != Num_FPR_Regs) {
4044         unsigned VReg;
4045 
4046         if (ObjectVT == MVT::f32)
4047           VReg = MF.addLiveIn(FPR[FPR_idx],
4048                               Subtarget.hasP8Vector()
4049                                   ? &PPC::VSSRCRegClass
4050                                   : &PPC::F4RCRegClass);
4051         else
4052           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4053                                                 ? &PPC::VSFRCRegClass
4054                                                 : &PPC::F8RCRegClass);
4055 
4056         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4057         ++FPR_idx;
4058       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4059         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4060         // once we support fp <-> gpr moves.
4061 
4062         // This can only ever happen in the presence of f32 array types,
4063         // since otherwise we never run out of FPRs before running out
4064         // of GPRs.
4065         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4066         FuncInfo->addLiveInAttr(VReg, Flags);
4067         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4068 
4069         if (ObjectVT == MVT::f32) {
4070           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4071             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4072                                  DAG.getConstant(32, dl, MVT::i32));
4073           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4074         }
4075 
4076         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4077       } else {
4078         if (CallConv == CallingConv::Fast)
4079           ComputeArgOffset();
4080 
4081         needsLoad = true;
4082       }
4083 
4084       // When passing an array of floats, the array occupies consecutive
4085       // space in the argument area; only round up to the next doubleword
4086       // at the end of the array.  Otherwise, each float takes 8 bytes.
4087       if (CallConv != CallingConv::Fast || needsLoad) {
4088         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4089         ArgOffset += ArgSize;
4090         if (Flags.isInConsecutiveRegsLast())
4091           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4092       }
4093       break;
4094     case MVT::v4f32:
4095     case MVT::v4i32:
4096     case MVT::v8i16:
4097     case MVT::v16i8:
4098     case MVT::v2f64:
4099     case MVT::v2i64:
4100     case MVT::v1i128:
4101     case MVT::f128:
4102       if (!Subtarget.hasQPX()) {
4103         // These can be scalar arguments or elements of a vector array type
4104         // passed directly.  The latter are used to implement ELFv2 homogenous
4105         // vector aggregates.
4106         if (VR_idx != Num_VR_Regs) {
4107           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4108           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4109           ++VR_idx;
4110         } else {
4111           if (CallConv == CallingConv::Fast)
4112             ComputeArgOffset();
4113           needsLoad = true;
4114         }
4115         if (CallConv != CallingConv::Fast || needsLoad)
4116           ArgOffset += 16;
4117         break;
4118       } // not QPX
4119 
4120       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4121              "Invalid QPX parameter type");
4122       LLVM_FALLTHROUGH;
4123 
4124     case MVT::v4f64:
4125     case MVT::v4i1:
4126       // QPX vectors are treated like their scalar floating-point subregisters
4127       // (except that they're larger).
4128       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4129       if (QFPR_idx != Num_QFPR_Regs) {
4130         const TargetRegisterClass *RC;
4131         switch (ObjectVT.getSimpleVT().SimpleTy) {
4132         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4133         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4134         default:         RC = &PPC::QBRCRegClass; break;
4135         }
4136 
4137         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4138         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4139         ++QFPR_idx;
4140       } else {
4141         if (CallConv == CallingConv::Fast)
4142           ComputeArgOffset();
4143         needsLoad = true;
4144       }
4145       if (CallConv != CallingConv::Fast || needsLoad)
4146         ArgOffset += Sz;
4147       break;
4148     }
4149 
4150     // We need to load the argument to a virtual register if we determined
4151     // above that we ran out of physical registers of the appropriate type.
4152     if (needsLoad) {
4153       if (ObjSize < ArgSize && !isLittleEndian)
4154         CurArgOffset += ArgSize - ObjSize;
4155       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4156       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4157       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4158     }
4159 
4160     InVals.push_back(ArgVal);
4161   }
4162 
4163   // Area that is at least reserved in the caller of this function.
4164   unsigned MinReservedArea;
4165   if (HasParameterArea)
4166     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4167   else
4168     MinReservedArea = LinkageSize;
4169 
4170   // Set the size that is at least reserved in caller of this function.  Tail
4171   // call optimized functions' reserved stack space needs to be aligned so that
4172   // taking the difference between two stack areas will result in an aligned
4173   // stack.
4174   MinReservedArea =
4175       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4176   FuncInfo->setMinReservedArea(MinReservedArea);
4177 
4178   // If the function takes variable number of arguments, make a frame index for
4179   // the start of the first vararg value... for expansion of llvm.va_start.
4180   if (isVarArg) {
4181     int Depth = ArgOffset;
4182 
4183     FuncInfo->setVarArgsFrameIndex(
4184       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4185     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4186 
4187     // If this function is vararg, store any remaining integer argument regs
4188     // to their spots on the stack so that they may be loaded by dereferencing
4189     // the result of va_next.
4190     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4191          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4192       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4193       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4194       SDValue Store =
4195           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4196       MemOps.push_back(Store);
4197       // Increment the address by four for the next argument to store
4198       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4199       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4200     }
4201   }
4202 
4203   if (!MemOps.empty())
4204     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4205 
4206   return Chain;
4207 }
4208 
4209 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4210     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4211     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4212     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4213   // TODO: add description of PPC stack frame format, or at least some docs.
4214   //
4215   MachineFunction &MF = DAG.getMachineFunction();
4216   MachineFrameInfo &MFI = MF.getFrameInfo();
4217   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4218 
4219   EVT PtrVT = getPointerTy(MF.getDataLayout());
4220   bool isPPC64 = PtrVT == MVT::i64;
4221   // Potential tail calls could cause overwriting of argument stack slots.
4222   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4223                        (CallConv == CallingConv::Fast));
4224   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4225   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4226   unsigned ArgOffset = LinkageSize;
4227   // Area that is at least reserved in caller of this function.
4228   unsigned MinReservedArea = ArgOffset;
4229 
4230   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4231     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4232     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4233   };
4234   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4235     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4236     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4237   };
4238   static const MCPhysReg VR[] = {
4239     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4240     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4241   };
4242 
4243   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4244   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4245   const unsigned Num_VR_Regs  = array_lengthof( VR);
4246 
4247   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4248 
4249   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4250 
4251   // In 32-bit non-varargs functions, the stack space for vectors is after the
4252   // stack space for non-vectors.  We do not use this space unless we have
4253   // too many vectors to fit in registers, something that only occurs in
4254   // constructed examples:), but we have to walk the arglist to figure
4255   // that out...for the pathological case, compute VecArgOffset as the
4256   // start of the vector parameter area.  Computing VecArgOffset is the
4257   // entire point of the following loop.
4258   unsigned VecArgOffset = ArgOffset;
4259   if (!isVarArg && !isPPC64) {
4260     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4261          ++ArgNo) {
4262       EVT ObjectVT = Ins[ArgNo].VT;
4263       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4264 
4265       if (Flags.isByVal()) {
4266         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4267         unsigned ObjSize = Flags.getByValSize();
4268         unsigned ArgSize =
4269                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4270         VecArgOffset += ArgSize;
4271         continue;
4272       }
4273 
4274       switch(ObjectVT.getSimpleVT().SimpleTy) {
4275       default: llvm_unreachable("Unhandled argument type!");
4276       case MVT::i1:
4277       case MVT::i32:
4278       case MVT::f32:
4279         VecArgOffset += 4;
4280         break;
4281       case MVT::i64:  // PPC64
4282       case MVT::f64:
4283         // FIXME: We are guaranteed to be !isPPC64 at this point.
4284         // Does MVT::i64 apply?
4285         VecArgOffset += 8;
4286         break;
4287       case MVT::v4f32:
4288       case MVT::v4i32:
4289       case MVT::v8i16:
4290       case MVT::v16i8:
4291         // Nothing to do, we're only looking at Nonvector args here.
4292         break;
4293       }
4294     }
4295   }
4296   // We've found where the vector parameter area in memory is.  Skip the
4297   // first 12 parameters; these don't use that memory.
4298   VecArgOffset = ((VecArgOffset+15)/16)*16;
4299   VecArgOffset += 12*16;
4300 
4301   // Add DAG nodes to load the arguments or copy them out of registers.  On
4302   // entry to a function on PPC, the arguments start after the linkage area,
4303   // although the first ones are often in registers.
4304 
4305   SmallVector<SDValue, 8> MemOps;
4306   unsigned nAltivecParamsAtEnd = 0;
4307   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4308   unsigned CurArgIdx = 0;
4309   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4310     SDValue ArgVal;
4311     bool needsLoad = false;
4312     EVT ObjectVT = Ins[ArgNo].VT;
4313     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4314     unsigned ArgSize = ObjSize;
4315     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4316     if (Ins[ArgNo].isOrigArg()) {
4317       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4318       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4319     }
4320     unsigned CurArgOffset = ArgOffset;
4321 
4322     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4323     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4324         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4325       if (isVarArg || isPPC64) {
4326         MinReservedArea = ((MinReservedArea+15)/16)*16;
4327         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4328                                                   Flags,
4329                                                   PtrByteSize);
4330       } else  nAltivecParamsAtEnd++;
4331     } else
4332       // Calculate min reserved area.
4333       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4334                                                 Flags,
4335                                                 PtrByteSize);
4336 
4337     // FIXME the codegen can be much improved in some cases.
4338     // We do not have to keep everything in memory.
4339     if (Flags.isByVal()) {
4340       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4341 
4342       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4343       ObjSize = Flags.getByValSize();
4344       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4345       // Objects of size 1 and 2 are right justified, everything else is
4346       // left justified.  This means the memory address is adjusted forwards.
4347       if (ObjSize==1 || ObjSize==2) {
4348         CurArgOffset = CurArgOffset + (4 - ObjSize);
4349       }
4350       // The value of the object is its address.
4351       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4352       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4353       InVals.push_back(FIN);
4354       if (ObjSize==1 || ObjSize==2) {
4355         if (GPR_idx != Num_GPR_Regs) {
4356           unsigned VReg;
4357           if (isPPC64)
4358             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4359           else
4360             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4361           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4362           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4363           SDValue Store =
4364               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4365                                 MachinePointerInfo(&*FuncArg), ObjType);
4366           MemOps.push_back(Store);
4367           ++GPR_idx;
4368         }
4369 
4370         ArgOffset += PtrByteSize;
4371 
4372         continue;
4373       }
4374       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4375         // Store whatever pieces of the object are in registers
4376         // to memory.  ArgOffset will be the address of the beginning
4377         // of the object.
4378         if (GPR_idx != Num_GPR_Regs) {
4379           unsigned VReg;
4380           if (isPPC64)
4381             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4382           else
4383             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4384           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4385           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4386           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4387           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4388                                        MachinePointerInfo(&*FuncArg, j));
4389           MemOps.push_back(Store);
4390           ++GPR_idx;
4391           ArgOffset += PtrByteSize;
4392         } else {
4393           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4394           break;
4395         }
4396       }
4397       continue;
4398     }
4399 
4400     switch (ObjectVT.getSimpleVT().SimpleTy) {
4401     default: llvm_unreachable("Unhandled argument type!");
4402     case MVT::i1:
4403     case MVT::i32:
4404       if (!isPPC64) {
4405         if (GPR_idx != Num_GPR_Regs) {
4406           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4407           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4408 
4409           if (ObjectVT == MVT::i1)
4410             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4411 
4412           ++GPR_idx;
4413         } else {
4414           needsLoad = true;
4415           ArgSize = PtrByteSize;
4416         }
4417         // All int arguments reserve stack space in the Darwin ABI.
4418         ArgOffset += PtrByteSize;
4419         break;
4420       }
4421       LLVM_FALLTHROUGH;
4422     case MVT::i64:  // PPC64
4423       if (GPR_idx != Num_GPR_Regs) {
4424         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4425         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4426 
4427         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4428           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4429           // value to MVT::i64 and then truncate to the correct register size.
4430           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4431 
4432         ++GPR_idx;
4433       } else {
4434         needsLoad = true;
4435         ArgSize = PtrByteSize;
4436       }
4437       // All int arguments reserve stack space in the Darwin ABI.
4438       ArgOffset += 8;
4439       break;
4440 
4441     case MVT::f32:
4442     case MVT::f64:
4443       // Every 4 bytes of argument space consumes one of the GPRs available for
4444       // argument passing.
4445       if (GPR_idx != Num_GPR_Regs) {
4446         ++GPR_idx;
4447         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4448           ++GPR_idx;
4449       }
4450       if (FPR_idx != Num_FPR_Regs) {
4451         unsigned VReg;
4452 
4453         if (ObjectVT == MVT::f32)
4454           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4455         else
4456           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4457 
4458         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4459         ++FPR_idx;
4460       } else {
4461         needsLoad = true;
4462       }
4463 
4464       // All FP arguments reserve stack space in the Darwin ABI.
4465       ArgOffset += isPPC64 ? 8 : ObjSize;
4466       break;
4467     case MVT::v4f32:
4468     case MVT::v4i32:
4469     case MVT::v8i16:
4470     case MVT::v16i8:
4471       // Note that vector arguments in registers don't reserve stack space,
4472       // except in varargs functions.
4473       if (VR_idx != Num_VR_Regs) {
4474         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4475         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4476         if (isVarArg) {
4477           while ((ArgOffset % 16) != 0) {
4478             ArgOffset += PtrByteSize;
4479             if (GPR_idx != Num_GPR_Regs)
4480               GPR_idx++;
4481           }
4482           ArgOffset += 16;
4483           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4484         }
4485         ++VR_idx;
4486       } else {
4487         if (!isVarArg && !isPPC64) {
4488           // Vectors go after all the nonvectors.
4489           CurArgOffset = VecArgOffset;
4490           VecArgOffset += 16;
4491         } else {
4492           // Vectors are aligned.
4493           ArgOffset = ((ArgOffset+15)/16)*16;
4494           CurArgOffset = ArgOffset;
4495           ArgOffset += 16;
4496         }
4497         needsLoad = true;
4498       }
4499       break;
4500     }
4501 
4502     // We need to load the argument to a virtual register if we determined above
4503     // that we ran out of physical registers of the appropriate type.
4504     if (needsLoad) {
4505       int FI = MFI.CreateFixedObject(ObjSize,
4506                                      CurArgOffset + (ArgSize - ObjSize),
4507                                      isImmutable);
4508       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4509       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4510     }
4511 
4512     InVals.push_back(ArgVal);
4513   }
4514 
4515   // Allow for Altivec parameters at the end, if needed.
4516   if (nAltivecParamsAtEnd) {
4517     MinReservedArea = ((MinReservedArea+15)/16)*16;
4518     MinReservedArea += 16*nAltivecParamsAtEnd;
4519   }
4520 
4521   // Area that is at least reserved in the caller of this function.
4522   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4523 
4524   // Set the size that is at least reserved in caller of this function.  Tail
4525   // call optimized functions' reserved stack space needs to be aligned so that
4526   // taking the difference between two stack areas will result in an aligned
4527   // stack.
4528   MinReservedArea =
4529       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4530   FuncInfo->setMinReservedArea(MinReservedArea);
4531 
4532   // If the function takes variable number of arguments, make a frame index for
4533   // the start of the first vararg value... for expansion of llvm.va_start.
4534   if (isVarArg) {
4535     int Depth = ArgOffset;
4536 
4537     FuncInfo->setVarArgsFrameIndex(
4538       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4539                             Depth, true));
4540     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4541 
4542     // If this function is vararg, store any remaining integer argument regs
4543     // to their spots on the stack so that they may be loaded by dereferencing
4544     // the result of va_next.
4545     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4546       unsigned VReg;
4547 
4548       if (isPPC64)
4549         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4550       else
4551         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4552 
4553       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4554       SDValue Store =
4555           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4556       MemOps.push_back(Store);
4557       // Increment the address by four for the next argument to store
4558       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4559       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4560     }
4561   }
4562 
4563   if (!MemOps.empty())
4564     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4565 
4566   return Chain;
4567 }
4568 
4569 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4570 /// adjusted to accommodate the arguments for the tailcall.
4571 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4572                                    unsigned ParamSize) {
4573 
4574   if (!isTailCall) return 0;
4575 
4576   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4577   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4578   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4579   // Remember only if the new adjustment is bigger.
4580   if (SPDiff < FI->getTailCallSPDelta())
4581     FI->setTailCallSPDelta(SPDiff);
4582 
4583   return SPDiff;
4584 }
4585 
4586 static bool isFunctionGlobalAddress(SDValue Callee);
4587 
4588 static bool
4589 callsShareTOCBase(const Function *Caller, SDValue Callee,
4590                     const TargetMachine &TM) {
4591    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4592    // don't have enough information to determine if the caller and calle share
4593    // the same  TOC base, so we have to pessimistically assume they don't for
4594    // correctness.
4595    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4596    if (!G)
4597      return false;
4598 
4599    const GlobalValue *GV = G->getGlobal();
4600   // The medium and large code models are expected to provide a sufficiently
4601   // large TOC to provide all data addressing needs of a module with a
4602   // single TOC. Since each module will be addressed with a single TOC then we
4603   // only need to check that caller and callee don't cross dso boundaries.
4604   if (CodeModel::Medium == TM.getCodeModel() ||
4605       CodeModel::Large == TM.getCodeModel())
4606     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4607 
4608   // Otherwise we need to ensure callee and caller are in the same section,
4609   // since the linker may allocate multiple TOCs, and we don't know which
4610   // sections will belong to the same TOC base.
4611 
4612   if (!GV->isStrongDefinitionForLinker())
4613     return false;
4614 
4615   // Any explicitly-specified sections and section prefixes must also match.
4616   // Also, if we're using -ffunction-sections, then each function is always in
4617   // a different section (the same is true for COMDAT functions).
4618   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4619       GV->getSection() != Caller->getSection())
4620     return false;
4621   if (const auto *F = dyn_cast<Function>(GV)) {
4622     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4623       return false;
4624   }
4625 
4626   // If the callee might be interposed, then we can't assume the ultimate call
4627   // target will be in the same section. Even in cases where we can assume that
4628   // interposition won't happen, in any case where the linker might insert a
4629   // stub to allow for interposition, we must generate code as though
4630   // interposition might occur. To understand why this matters, consider a
4631   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4632   // in the same section, but a is in a different module (i.e. has a different
4633   // TOC base pointer). If the linker allows for interposition between b and c,
4634   // then it will generate a stub for the call edge between b and c which will
4635   // save the TOC pointer into the designated stack slot allocated by b. If we
4636   // return true here, and therefore allow a tail call between b and c, that
4637   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4638   // pointer into the stack slot allocated by a (where the a -> b stub saved
4639   // a's TOC base pointer). If we're not considering a tail call, but rather,
4640   // whether a nop is needed after the call instruction in b, because the linker
4641   // will insert a stub, it might complain about a missing nop if we omit it
4642   // (although many don't complain in this case).
4643   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4644     return false;
4645 
4646   return true;
4647 }
4648 
4649 static bool
4650 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4651                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4652   assert(Subtarget.is64BitELFABI());
4653 
4654   const unsigned PtrByteSize = 8;
4655   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4656 
4657   static const MCPhysReg GPR[] = {
4658     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4659     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4660   };
4661   static const MCPhysReg VR[] = {
4662     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4663     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4664   };
4665 
4666   const unsigned NumGPRs = array_lengthof(GPR);
4667   const unsigned NumFPRs = 13;
4668   const unsigned NumVRs = array_lengthof(VR);
4669   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4670 
4671   unsigned NumBytes = LinkageSize;
4672   unsigned AvailableFPRs = NumFPRs;
4673   unsigned AvailableVRs = NumVRs;
4674 
4675   for (const ISD::OutputArg& Param : Outs) {
4676     if (Param.Flags.isNest()) continue;
4677 
4678     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4679                                PtrByteSize, LinkageSize, ParamAreaSize,
4680                                NumBytes, AvailableFPRs, AvailableVRs,
4681                                Subtarget.hasQPX()))
4682       return true;
4683   }
4684   return false;
4685 }
4686 
4687 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4688   if (CB.arg_size() != CallerFn->arg_size())
4689     return false;
4690 
4691   auto CalleeArgIter = CB.arg_begin();
4692   auto CalleeArgEnd = CB.arg_end();
4693   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4694 
4695   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4696     const Value* CalleeArg = *CalleeArgIter;
4697     const Value* CallerArg = &(*CallerArgIter);
4698     if (CalleeArg == CallerArg)
4699       continue;
4700 
4701     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4702     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4703     //      }
4704     // 1st argument of callee is undef and has the same type as caller.
4705     if (CalleeArg->getType() == CallerArg->getType() &&
4706         isa<UndefValue>(CalleeArg))
4707       continue;
4708 
4709     return false;
4710   }
4711 
4712   return true;
4713 }
4714 
4715 // Returns true if TCO is possible between the callers and callees
4716 // calling conventions.
4717 static bool
4718 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4719                                     CallingConv::ID CalleeCC) {
4720   // Tail calls are possible with fastcc and ccc.
4721   auto isTailCallableCC  = [] (CallingConv::ID CC){
4722       return  CC == CallingConv::C || CC == CallingConv::Fast;
4723   };
4724   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4725     return false;
4726 
4727   // We can safely tail call both fastcc and ccc callees from a c calling
4728   // convention caller. If the caller is fastcc, we may have less stack space
4729   // than a non-fastcc caller with the same signature so disable tail-calls in
4730   // that case.
4731   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4732 }
4733 
4734 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4735     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4736     const SmallVectorImpl<ISD::OutputArg> &Outs,
4737     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4738   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4739 
4740   // FIXME: Tail calls are currently disabled when using PC Relative addressing.
4741   // The issue is that PC Relative is only partially implemented and so there
4742   // is currently a mix of functions that require the TOC and functions that do
4743   // not require it. If we have A calls B calls C and both A and B require the
4744   // TOC and C does not and is marked as clobbering R2 then it is not safe for
4745   // B to tail call C. Since we do not have the information of whether or not
4746   // a funciton needs to use the TOC here in this function we need to be
4747   // conservatively safe and disable all tail calls for now.
4748   if (Subtarget.isUsingPCRelativeCalls()) return false;
4749 
4750   if (DisableSCO && !TailCallOpt) return false;
4751 
4752   // Variadic argument functions are not supported.
4753   if (isVarArg) return false;
4754 
4755   auto &Caller = DAG.getMachineFunction().getFunction();
4756   // Check that the calling conventions are compatible for tco.
4757   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4758     return false;
4759 
4760   // Caller contains any byval parameter is not supported.
4761   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4762     return false;
4763 
4764   // Callee contains any byval parameter is not supported, too.
4765   // Note: This is a quick work around, because in some cases, e.g.
4766   // caller's stack size > callee's stack size, we are still able to apply
4767   // sibling call optimization. For example, gcc is able to do SCO for caller1
4768   // in the following example, but not for caller2.
4769   //   struct test {
4770   //     long int a;
4771   //     char ary[56];
4772   //   } gTest;
4773   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4774   //     b->a = v.a;
4775   //     return 0;
4776   //   }
4777   //   void caller1(struct test a, struct test c, struct test *b) {
4778   //     callee(gTest, b); }
4779   //   void caller2(struct test *b) { callee(gTest, b); }
4780   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4781     return false;
4782 
4783   // If callee and caller use different calling conventions, we cannot pass
4784   // parameters on stack since offsets for the parameter area may be different.
4785   if (Caller.getCallingConv() != CalleeCC &&
4786       needStackSlotPassParameters(Subtarget, Outs))
4787     return false;
4788 
4789   // No TCO/SCO on indirect call because Caller have to restore its TOC
4790   if (!isFunctionGlobalAddress(Callee) &&
4791       !isa<ExternalSymbolSDNode>(Callee))
4792     return false;
4793 
4794   // If the caller and callee potentially have different TOC bases then we
4795   // cannot tail call since we need to restore the TOC pointer after the call.
4796   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4797   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4798     return false;
4799 
4800   // TCO allows altering callee ABI, so we don't have to check further.
4801   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4802     return true;
4803 
4804   if (DisableSCO) return false;
4805 
4806   // If callee use the same argument list that caller is using, then we can
4807   // apply SCO on this case. If it is not, then we need to check if callee needs
4808   // stack for passing arguments.
4809   assert(CB && "Expected to have a CallBase!");
4810   if (!hasSameArgumentList(&Caller, *CB) &&
4811       needStackSlotPassParameters(Subtarget, Outs)) {
4812     return false;
4813   }
4814 
4815   return true;
4816 }
4817 
4818 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4819 /// for tail call optimization. Targets which want to do tail call
4820 /// optimization should implement this function.
4821 bool
4822 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4823                                                      CallingConv::ID CalleeCC,
4824                                                      bool isVarArg,
4825                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4826                                                      SelectionDAG& DAG) const {
4827   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4828     return false;
4829 
4830   // Variable argument functions are not supported.
4831   if (isVarArg)
4832     return false;
4833 
4834   MachineFunction &MF = DAG.getMachineFunction();
4835   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4836   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4837     // Functions containing by val parameters are not supported.
4838     for (unsigned i = 0; i != Ins.size(); i++) {
4839        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4840        if (Flags.isByVal()) return false;
4841     }
4842 
4843     // Non-PIC/GOT tail calls are supported.
4844     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4845       return true;
4846 
4847     // At the moment we can only do local tail calls (in same module, hidden
4848     // or protected) if we are generating PIC.
4849     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4850       return G->getGlobal()->hasHiddenVisibility()
4851           || G->getGlobal()->hasProtectedVisibility();
4852   }
4853 
4854   return false;
4855 }
4856 
4857 /// isCallCompatibleAddress - Return the immediate to use if the specified
4858 /// 32-bit value is representable in the immediate field of a BxA instruction.
4859 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4860   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4861   if (!C) return nullptr;
4862 
4863   int Addr = C->getZExtValue();
4864   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4865       SignExtend32<26>(Addr) != Addr)
4866     return nullptr;  // Top 6 bits have to be sext of immediate.
4867 
4868   return DAG
4869       .getConstant(
4870           (int)C->getZExtValue() >> 2, SDLoc(Op),
4871           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4872       .getNode();
4873 }
4874 
4875 namespace {
4876 
4877 struct TailCallArgumentInfo {
4878   SDValue Arg;
4879   SDValue FrameIdxOp;
4880   int FrameIdx = 0;
4881 
4882   TailCallArgumentInfo() = default;
4883 };
4884 
4885 } // end anonymous namespace
4886 
4887 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4888 static void StoreTailCallArgumentsToStackSlot(
4889     SelectionDAG &DAG, SDValue Chain,
4890     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4891     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4892   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4893     SDValue Arg = TailCallArgs[i].Arg;
4894     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4895     int FI = TailCallArgs[i].FrameIdx;
4896     // Store relative to framepointer.
4897     MemOpChains.push_back(DAG.getStore(
4898         Chain, dl, Arg, FIN,
4899         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4900   }
4901 }
4902 
4903 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4904 /// the appropriate stack slot for the tail call optimized function call.
4905 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4906                                              SDValue OldRetAddr, SDValue OldFP,
4907                                              int SPDiff, const SDLoc &dl) {
4908   if (SPDiff) {
4909     // Calculate the new stack slot for the return address.
4910     MachineFunction &MF = DAG.getMachineFunction();
4911     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4912     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4913     bool isPPC64 = Subtarget.isPPC64();
4914     int SlotSize = isPPC64 ? 8 : 4;
4915     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4916     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4917                                                          NewRetAddrLoc, true);
4918     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4919     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4920     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4921                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4922   }
4923   return Chain;
4924 }
4925 
4926 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4927 /// the position of the argument.
4928 static void
4929 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4930                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4931                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4932   int Offset = ArgOffset + SPDiff;
4933   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4934   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4935   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4936   SDValue FIN = DAG.getFrameIndex(FI, VT);
4937   TailCallArgumentInfo Info;
4938   Info.Arg = Arg;
4939   Info.FrameIdxOp = FIN;
4940   Info.FrameIdx = FI;
4941   TailCallArguments.push_back(Info);
4942 }
4943 
4944 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4945 /// stack slot. Returns the chain as result and the loaded frame pointers in
4946 /// LROpOut/FPOpout. Used when tail calling.
4947 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4948     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4949     SDValue &FPOpOut, const SDLoc &dl) const {
4950   if (SPDiff) {
4951     // Load the LR and FP stack slot for later adjusting.
4952     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4953     LROpOut = getReturnAddrFrameIndex(DAG);
4954     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4955     Chain = SDValue(LROpOut.getNode(), 1);
4956   }
4957   return Chain;
4958 }
4959 
4960 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4961 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4962 /// specified by the specific parameter attribute. The copy will be passed as
4963 /// a byval function parameter.
4964 /// Sometimes what we are copying is the end of a larger object, the part that
4965 /// does not fit in registers.
4966 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4967                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4968                                          SelectionDAG &DAG, const SDLoc &dl) {
4969   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4970   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4971                        Flags.getNonZeroByValAlign(), false, false, false,
4972                        MachinePointerInfo(), MachinePointerInfo());
4973 }
4974 
4975 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4976 /// tail calls.
4977 static void LowerMemOpCallTo(
4978     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4979     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4980     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4981     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4982   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4983   if (!isTailCall) {
4984     if (isVector) {
4985       SDValue StackPtr;
4986       if (isPPC64)
4987         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4988       else
4989         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4990       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4991                            DAG.getConstant(ArgOffset, dl, PtrVT));
4992     }
4993     MemOpChains.push_back(
4994         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4995     // Calculate and remember argument location.
4996   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4997                                   TailCallArguments);
4998 }
4999 
5000 static void
5001 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5002                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5003                 SDValue FPOp,
5004                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5005   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5006   // might overwrite each other in case of tail call optimization.
5007   SmallVector<SDValue, 8> MemOpChains2;
5008   // Do not flag preceding copytoreg stuff together with the following stuff.
5009   InFlag = SDValue();
5010   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5011                                     MemOpChains2, dl);
5012   if (!MemOpChains2.empty())
5013     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5014 
5015   // Store the return address to the appropriate stack slot.
5016   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5017 
5018   // Emit callseq_end just before tailcall node.
5019   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5020                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5021   InFlag = Chain.getValue(1);
5022 }
5023 
5024 // Is this global address that of a function that can be called by name? (as
5025 // opposed to something that must hold a descriptor for an indirect call).
5026 static bool isFunctionGlobalAddress(SDValue Callee) {
5027   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5028     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5029         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5030       return false;
5031 
5032     return G->getGlobal()->getValueType()->isFunctionTy();
5033   }
5034 
5035   return false;
5036 }
5037 
5038 SDValue PPCTargetLowering::LowerCallResult(
5039     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5040     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5041     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5042   SmallVector<CCValAssign, 16> RVLocs;
5043   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5044                     *DAG.getContext());
5045 
5046   CCRetInfo.AnalyzeCallResult(
5047       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5048                ? RetCC_PPC_Cold
5049                : RetCC_PPC);
5050 
5051   // Copy all of the result registers out of their specified physreg.
5052   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5053     CCValAssign &VA = RVLocs[i];
5054     assert(VA.isRegLoc() && "Can only return in registers!");
5055 
5056     SDValue Val;
5057 
5058     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5059       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5060                                       InFlag);
5061       Chain = Lo.getValue(1);
5062       InFlag = Lo.getValue(2);
5063       VA = RVLocs[++i]; // skip ahead to next loc
5064       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5065                                       InFlag);
5066       Chain = Hi.getValue(1);
5067       InFlag = Hi.getValue(2);
5068       if (!Subtarget.isLittleEndian())
5069         std::swap (Lo, Hi);
5070       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5071     } else {
5072       Val = DAG.getCopyFromReg(Chain, dl,
5073                                VA.getLocReg(), VA.getLocVT(), InFlag);
5074       Chain = Val.getValue(1);
5075       InFlag = Val.getValue(2);
5076     }
5077 
5078     switch (VA.getLocInfo()) {
5079     default: llvm_unreachable("Unknown loc info!");
5080     case CCValAssign::Full: break;
5081     case CCValAssign::AExt:
5082       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5083       break;
5084     case CCValAssign::ZExt:
5085       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5086                         DAG.getValueType(VA.getValVT()));
5087       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5088       break;
5089     case CCValAssign::SExt:
5090       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5091                         DAG.getValueType(VA.getValVT()));
5092       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5093       break;
5094     }
5095 
5096     InVals.push_back(Val);
5097   }
5098 
5099   return Chain;
5100 }
5101 
5102 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5103                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5104   // PatchPoint calls are not indirect.
5105   if (isPatchPoint)
5106     return false;
5107 
5108   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5109     return false;
5110 
5111   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5112   // becuase the immediate function pointer points to a descriptor instead of
5113   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5114   // pointer immediate points to the global entry point, while the BLA would
5115   // need to jump to the local entry point (see rL211174).
5116   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5117       isBLACompatibleAddress(Callee, DAG))
5118     return false;
5119 
5120   return true;
5121 }
5122 
5123 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5124                               const Function &Caller,
5125                               const SDValue &Callee,
5126                               const PPCSubtarget &Subtarget,
5127                               const TargetMachine &TM) {
5128   if (CFlags.IsTailCall)
5129     return PPCISD::TC_RETURN;
5130 
5131   // This is a call through a function pointer.
5132   if (CFlags.IsIndirect) {
5133     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5134     // indirect calls. The save of the caller's TOC pointer to the stack will be
5135     // inserted into the DAG as part of call lowering. The restore of the TOC
5136     // pointer is modeled by using a pseudo instruction for the call opcode that
5137     // represents the 2 instruction sequence of an indirect branch and link,
5138     // immediately followed by a load of the TOC pointer from the the stack save
5139     // slot into gpr2.
5140     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5141       return PPCISD::BCTRL_LOAD_TOC;
5142 
5143     // An indirect call that does not need a TOC restore.
5144     return PPCISD::BCTRL;
5145   }
5146 
5147   // FIXME: At this moment indirect calls are treated ahead of the
5148   // PC Relative condition because binaries can still contain a possible
5149   // mix of functions that use a TOC and functions that do not use a TOC.
5150   // Once the PC Relative feature is complete this condition should be moved
5151   // up ahead of the indirect calls and should return a PPCISD::BCTRL for
5152   // that case.
5153   if (Subtarget.isUsingPCRelativeCalls()) {
5154     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5155     return PPCISD::CALL_NOTOC;
5156   }
5157 
5158   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5159   // immediately following the call instruction if the caller and callee may
5160   // have different TOC bases. At link time if the linker determines the calls
5161   // may not share a TOC base, the call is redirected to a trampoline inserted
5162   // by the linker. The trampoline will (among other things) save the callers
5163   // TOC pointer at an ABI designated offset in the linkage area and the linker
5164   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5165   // into gpr2.
5166   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5167       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5168                                                     : PPCISD::CALL_NOP;
5169 
5170   return PPCISD::CALL;
5171 }
5172 
5173 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5174                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5175   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5176     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5177       return SDValue(Dest, 0);
5178 
5179   // Returns true if the callee is local, and false otherwise.
5180   auto isLocalCallee = [&]() {
5181     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5182     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5183     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5184 
5185     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5186            !dyn_cast_or_null<GlobalIFunc>(GV);
5187   };
5188 
5189   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5190   // a static relocation model causes some versions of GNU LD (2.17.50, at
5191   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5192   // built with secure-PLT.
5193   bool UsePlt =
5194       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5195       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5196 
5197   // On AIX, direct function calls reference the symbol for the function's
5198   // entry point, which is named by prepending a "." before the function's
5199   // C-linkage name.
5200   const auto getAIXFuncEntryPointSymbolSDNode =
5201       [&](StringRef FuncName, bool IsDeclaration,
5202           const XCOFF::StorageClass &SC) {
5203         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5204 
5205         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5206             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5207 
5208         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5209           // On AIX, an undefined symbol needs to be associated with a
5210           // MCSectionXCOFF to get the correct storage mapping class.
5211           // In this case, XCOFF::XMC_PR.
5212           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5213               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5214               SectionKind::getMetadata());
5215           S->setRepresentedCsect(Sec);
5216         }
5217 
5218         MVT PtrVT =
5219             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5220         return DAG.getMCSymbol(S, PtrVT);
5221       };
5222 
5223   if (isFunctionGlobalAddress(Callee)) {
5224     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5225     const GlobalValue *GV = G->getGlobal();
5226 
5227     if (!Subtarget.isAIXABI())
5228       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5229                                         UsePlt ? PPCII::MO_PLT : 0);
5230 
5231     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5232     const GlobalObject *GO = cast<GlobalObject>(GV);
5233     const XCOFF::StorageClass SC =
5234         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5235     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5236                                             SC);
5237   }
5238 
5239   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5240     const char *SymName = S->getSymbol();
5241     if (!Subtarget.isAIXABI())
5242       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5243                                          UsePlt ? PPCII::MO_PLT : 0);
5244 
5245     // If there exists a user-declared function whose name is the same as the
5246     // ExternalSymbol's, then we pick up the user-declared version.
5247     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5248     if (const Function *F =
5249             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5250       const XCOFF::StorageClass SC =
5251           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5252       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5253                                               SC);
5254     }
5255 
5256     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5257   }
5258 
5259   // No transformation needed.
5260   assert(Callee.getNode() && "What no callee?");
5261   return Callee;
5262 }
5263 
5264 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5265   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5266          "Expected a CALLSEQ_STARTSDNode.");
5267 
5268   // The last operand is the chain, except when the node has glue. If the node
5269   // has glue, then the last operand is the glue, and the chain is the second
5270   // last operand.
5271   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5272   if (LastValue.getValueType() != MVT::Glue)
5273     return LastValue;
5274 
5275   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5276 }
5277 
5278 // Creates the node that moves a functions address into the count register
5279 // to prepare for an indirect call instruction.
5280 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5281                                 SDValue &Glue, SDValue &Chain,
5282                                 const SDLoc &dl) {
5283   SDValue MTCTROps[] = {Chain, Callee, Glue};
5284   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5285   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5286                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5287   // The glue is the second value produced.
5288   Glue = Chain.getValue(1);
5289 }
5290 
5291 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5292                                           SDValue &Glue, SDValue &Chain,
5293                                           SDValue CallSeqStart,
5294                                           const CallBase *CB, const SDLoc &dl,
5295                                           bool hasNest,
5296                                           const PPCSubtarget &Subtarget) {
5297   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5298   // entry point, but to the function descriptor (the function entry point
5299   // address is part of the function descriptor though).
5300   // The function descriptor is a three doubleword structure with the
5301   // following fields: function entry point, TOC base address and
5302   // environment pointer.
5303   // Thus for a call through a function pointer, the following actions need
5304   // to be performed:
5305   //   1. Save the TOC of the caller in the TOC save area of its stack
5306   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5307   //   2. Load the address of the function entry point from the function
5308   //      descriptor.
5309   //   3. Load the TOC of the callee from the function descriptor into r2.
5310   //   4. Load the environment pointer from the function descriptor into
5311   //      r11.
5312   //   5. Branch to the function entry point address.
5313   //   6. On return of the callee, the TOC of the caller needs to be
5314   //      restored (this is done in FinishCall()).
5315   //
5316   // The loads are scheduled at the beginning of the call sequence, and the
5317   // register copies are flagged together to ensure that no other
5318   // operations can be scheduled in between. E.g. without flagging the
5319   // copies together, a TOC access in the caller could be scheduled between
5320   // the assignment of the callee TOC and the branch to the callee, which leads
5321   // to incorrect code.
5322 
5323   // Start by loading the function address from the descriptor.
5324   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5325   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5326                       ? (MachineMemOperand::MODereferenceable |
5327                          MachineMemOperand::MOInvariant)
5328                       : MachineMemOperand::MONone;
5329 
5330   MachinePointerInfo MPI(CB ? CB->getCalledValue() : nullptr);
5331 
5332   // Registers used in building the DAG.
5333   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5334   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5335 
5336   // Offsets of descriptor members.
5337   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5338   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5339 
5340   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5341   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5342 
5343   // One load for the functions entry point address.
5344   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5345                                     Alignment, MMOFlags);
5346 
5347   // One for loading the TOC anchor for the module that contains the called
5348   // function.
5349   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5350   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5351   SDValue TOCPtr =
5352       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5353                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5354 
5355   // One for loading the environment pointer.
5356   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5357   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5358   SDValue LoadEnvPtr =
5359       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5360                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5361 
5362 
5363   // Then copy the newly loaded TOC anchor to the TOC pointer.
5364   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5365   Chain = TOCVal.getValue(0);
5366   Glue = TOCVal.getValue(1);
5367 
5368   // If the function call has an explicit 'nest' parameter, it takes the
5369   // place of the environment pointer.
5370   assert((!hasNest || !Subtarget.isAIXABI()) &&
5371          "Nest parameter is not supported on AIX.");
5372   if (!hasNest) {
5373     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5374     Chain = EnvVal.getValue(0);
5375     Glue = EnvVal.getValue(1);
5376   }
5377 
5378   // The rest of the indirect call sequence is the same as the non-descriptor
5379   // DAG.
5380   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5381 }
5382 
5383 static void
5384 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5385                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5386                   SelectionDAG &DAG,
5387                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5388                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5389                   const PPCSubtarget &Subtarget) {
5390   const bool IsPPC64 = Subtarget.isPPC64();
5391   // MVT for a general purpose register.
5392   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5393 
5394   // First operand is always the chain.
5395   Ops.push_back(Chain);
5396 
5397   // If it's a direct call pass the callee as the second operand.
5398   if (!CFlags.IsIndirect)
5399     Ops.push_back(Callee);
5400   else {
5401     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5402 
5403     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5404     // on the stack (this would have been done in `LowerCall_64SVR4` or
5405     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5406     // represents both the indirect branch and a load that restores the TOC
5407     // pointer from the linkage area. The operand for the TOC restore is an add
5408     // of the TOC save offset to the stack pointer. This must be the second
5409     // operand: after the chain input but before any other variadic arguments.
5410     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5411       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5412 
5413       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5414       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5415       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5416       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5417       Ops.push_back(AddTOC);
5418     }
5419 
5420     // Add the register used for the environment pointer.
5421     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5422       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5423                                     RegVT));
5424 
5425 
5426     // Add CTR register as callee so a bctr can be emitted later.
5427     if (CFlags.IsTailCall)
5428       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5429   }
5430 
5431   // If this is a tail call add stack pointer delta.
5432   if (CFlags.IsTailCall)
5433     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5434 
5435   // Add argument registers to the end of the list so that they are known live
5436   // into the call.
5437   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5438     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5439                                   RegsToPass[i].second.getValueType()));
5440 
5441   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5442   // no way to mark dependencies as implicit here.
5443   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5444   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5445        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5446     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5447 
5448   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5449   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5450     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5451 
5452   // Add a register mask operand representing the call-preserved registers.
5453   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5454   const uint32_t *Mask =
5455       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5456   assert(Mask && "Missing call preserved mask for calling convention");
5457   Ops.push_back(DAG.getRegisterMask(Mask));
5458 
5459   // If the glue is valid, it is the last operand.
5460   if (Glue.getNode())
5461     Ops.push_back(Glue);
5462 }
5463 
5464 SDValue PPCTargetLowering::FinishCall(
5465     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5466     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5467     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5468     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5469     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5470 
5471   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5472       Subtarget.isAIXABI())
5473     setUsesTOCBasePtr(DAG);
5474 
5475   unsigned CallOpc =
5476       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5477                     Subtarget, DAG.getTarget());
5478 
5479   if (!CFlags.IsIndirect)
5480     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5481   else if (Subtarget.usesFunctionDescriptors())
5482     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5483                                   dl, CFlags.HasNest, Subtarget);
5484   else
5485     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5486 
5487   // Build the operand list for the call instruction.
5488   SmallVector<SDValue, 8> Ops;
5489   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5490                     SPDiff, Subtarget);
5491 
5492   // Emit tail call.
5493   if (CFlags.IsTailCall) {
5494     assert(((Callee.getOpcode() == ISD::Register &&
5495              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5496             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5497             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5498             isa<ConstantSDNode>(Callee)) &&
5499            "Expecting a global address, external symbol, absolute value or "
5500            "register");
5501     assert(CallOpc == PPCISD::TC_RETURN &&
5502            "Unexpected call opcode for a tail call.");
5503     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5504     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5505   }
5506 
5507   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5508   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5509   Glue = Chain.getValue(1);
5510 
5511   // When performing tail call optimization the callee pops its arguments off
5512   // the stack. Account for this here so these bytes can be pushed back on in
5513   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5514   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5515                          getTargetMachine().Options.GuaranteedTailCallOpt)
5516                             ? NumBytes
5517                             : 0;
5518 
5519   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5520                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5521                              Glue, dl);
5522   Glue = Chain.getValue(1);
5523 
5524   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5525                          DAG, InVals);
5526 }
5527 
5528 SDValue
5529 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5530                              SmallVectorImpl<SDValue> &InVals) const {
5531   SelectionDAG &DAG                     = CLI.DAG;
5532   SDLoc &dl                             = CLI.DL;
5533   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5534   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5535   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5536   SDValue Chain                         = CLI.Chain;
5537   SDValue Callee                        = CLI.Callee;
5538   bool &isTailCall                      = CLI.IsTailCall;
5539   CallingConv::ID CallConv              = CLI.CallConv;
5540   bool isVarArg                         = CLI.IsVarArg;
5541   bool isPatchPoint                     = CLI.IsPatchPoint;
5542   const CallBase *CB                    = CLI.CB;
5543 
5544   if (isTailCall) {
5545     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5546       isTailCall = false;
5547     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5548       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5549           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5550     else
5551       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5552                                                      Ins, DAG);
5553     if (isTailCall) {
5554       ++NumTailCalls;
5555       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5556         ++NumSiblingCalls;
5557 
5558       assert(isa<GlobalAddressSDNode>(Callee) &&
5559              "Callee should be an llvm::Function object.");
5560       LLVM_DEBUG(
5561           const GlobalValue *GV =
5562               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5563           const unsigned Width =
5564               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5565           dbgs() << "TCO caller: "
5566                  << left_justify(DAG.getMachineFunction().getName(), Width)
5567                  << ", callee linkage: " << GV->getVisibility() << ", "
5568                  << GV->getLinkage() << "\n");
5569     }
5570   }
5571 
5572   if (!isTailCall && CB && CB->isMustTailCall())
5573     report_fatal_error("failed to perform tail call elimination on a call "
5574                        "site marked musttail");
5575 
5576   // When long calls (i.e. indirect calls) are always used, calls are always
5577   // made via function pointer. If we have a function name, first translate it
5578   // into a pointer.
5579   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5580       !isTailCall)
5581     Callee = LowerGlobalAddress(Callee, DAG);
5582 
5583   CallFlags CFlags(
5584       CallConv, isTailCall, isVarArg, isPatchPoint,
5585       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5586       // hasNest
5587       Subtarget.is64BitELFABI() &&
5588           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5589 
5590   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5591     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5592                             InVals, CB);
5593 
5594   if (Subtarget.isSVR4ABI())
5595     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5596                             InVals, CB);
5597 
5598   if (Subtarget.isAIXABI())
5599     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5600                          InVals, CB);
5601 
5602   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5603                           InVals, CB);
5604 }
5605 
5606 SDValue PPCTargetLowering::LowerCall_32SVR4(
5607     SDValue Chain, SDValue Callee, CallFlags CFlags,
5608     const SmallVectorImpl<ISD::OutputArg> &Outs,
5609     const SmallVectorImpl<SDValue> &OutVals,
5610     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5611     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5612     const CallBase *CB) const {
5613   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5614   // of the 32-bit SVR4 ABI stack frame layout.
5615 
5616   const CallingConv::ID CallConv = CFlags.CallConv;
5617   const bool IsVarArg = CFlags.IsVarArg;
5618   const bool IsTailCall = CFlags.IsTailCall;
5619 
5620   assert((CallConv == CallingConv::C ||
5621           CallConv == CallingConv::Cold ||
5622           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5623 
5624   unsigned PtrByteSize = 4;
5625 
5626   MachineFunction &MF = DAG.getMachineFunction();
5627 
5628   // Mark this function as potentially containing a function that contains a
5629   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5630   // and restoring the callers stack pointer in this functions epilog. This is
5631   // done because by tail calling the called function might overwrite the value
5632   // in this function's (MF) stack pointer stack slot 0(SP).
5633   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5634       CallConv == CallingConv::Fast)
5635     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5636 
5637   // Count how many bytes are to be pushed on the stack, including the linkage
5638   // area, parameter list area and the part of the local variable space which
5639   // contains copies of aggregates which are passed by value.
5640 
5641   // Assign locations to all of the outgoing arguments.
5642   SmallVector<CCValAssign, 16> ArgLocs;
5643   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5644 
5645   // Reserve space for the linkage area on the stack.
5646   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5647                        PtrByteSize);
5648   if (useSoftFloat())
5649     CCInfo.PreAnalyzeCallOperands(Outs);
5650 
5651   if (IsVarArg) {
5652     // Handle fixed and variable vector arguments differently.
5653     // Fixed vector arguments go into registers as long as registers are
5654     // available. Variable vector arguments always go into memory.
5655     unsigned NumArgs = Outs.size();
5656 
5657     for (unsigned i = 0; i != NumArgs; ++i) {
5658       MVT ArgVT = Outs[i].VT;
5659       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5660       bool Result;
5661 
5662       if (Outs[i].IsFixed) {
5663         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5664                                CCInfo);
5665       } else {
5666         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5667                                       ArgFlags, CCInfo);
5668       }
5669 
5670       if (Result) {
5671 #ifndef NDEBUG
5672         errs() << "Call operand #" << i << " has unhandled type "
5673              << EVT(ArgVT).getEVTString() << "\n";
5674 #endif
5675         llvm_unreachable(nullptr);
5676       }
5677     }
5678   } else {
5679     // All arguments are treated the same.
5680     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5681   }
5682   CCInfo.clearWasPPCF128();
5683 
5684   // Assign locations to all of the outgoing aggregate by value arguments.
5685   SmallVector<CCValAssign, 16> ByValArgLocs;
5686   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5687 
5688   // Reserve stack space for the allocations in CCInfo.
5689   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5690 
5691   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5692 
5693   // Size of the linkage area, parameter list area and the part of the local
5694   // space variable where copies of aggregates which are passed by value are
5695   // stored.
5696   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5697 
5698   // Calculate by how many bytes the stack has to be adjusted in case of tail
5699   // call optimization.
5700   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5701 
5702   // Adjust the stack pointer for the new arguments...
5703   // These operations are automatically eliminated by the prolog/epilog pass
5704   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5705   SDValue CallSeqStart = Chain;
5706 
5707   // Load the return address and frame pointer so it can be moved somewhere else
5708   // later.
5709   SDValue LROp, FPOp;
5710   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5711 
5712   // Set up a copy of the stack pointer for use loading and storing any
5713   // arguments that may not fit in the registers available for argument
5714   // passing.
5715   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5716 
5717   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5718   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5719   SmallVector<SDValue, 8> MemOpChains;
5720 
5721   bool seenFloatArg = false;
5722   // Walk the register/memloc assignments, inserting copies/loads.
5723   // i - Tracks the index into the list of registers allocated for the call
5724   // RealArgIdx - Tracks the index into the list of actual function arguments
5725   // j - Tracks the index into the list of byval arguments
5726   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5727        i != e;
5728        ++i, ++RealArgIdx) {
5729     CCValAssign &VA = ArgLocs[i];
5730     SDValue Arg = OutVals[RealArgIdx];
5731     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5732 
5733     if (Flags.isByVal()) {
5734       // Argument is an aggregate which is passed by value, thus we need to
5735       // create a copy of it in the local variable space of the current stack
5736       // frame (which is the stack frame of the caller) and pass the address of
5737       // this copy to the callee.
5738       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5739       CCValAssign &ByValVA = ByValArgLocs[j++];
5740       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5741 
5742       // Memory reserved in the local variable space of the callers stack frame.
5743       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5744 
5745       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5746       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5747                            StackPtr, PtrOff);
5748 
5749       // Create a copy of the argument in the local area of the current
5750       // stack frame.
5751       SDValue MemcpyCall =
5752         CreateCopyOfByValArgument(Arg, PtrOff,
5753                                   CallSeqStart.getNode()->getOperand(0),
5754                                   Flags, DAG, dl);
5755 
5756       // This must go outside the CALLSEQ_START..END.
5757       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5758                                                      SDLoc(MemcpyCall));
5759       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5760                              NewCallSeqStart.getNode());
5761       Chain = CallSeqStart = NewCallSeqStart;
5762 
5763       // Pass the address of the aggregate copy on the stack either in a
5764       // physical register or in the parameter list area of the current stack
5765       // frame to the callee.
5766       Arg = PtrOff;
5767     }
5768 
5769     // When useCRBits() is true, there can be i1 arguments.
5770     // It is because getRegisterType(MVT::i1) => MVT::i1,
5771     // and for other integer types getRegisterType() => MVT::i32.
5772     // Extend i1 and ensure callee will get i32.
5773     if (Arg.getValueType() == MVT::i1)
5774       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5775                         dl, MVT::i32, Arg);
5776 
5777     if (VA.isRegLoc()) {
5778       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5779       // Put argument in a physical register.
5780       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5781         bool IsLE = Subtarget.isLittleEndian();
5782         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5783                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5784         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5785         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5786                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5787         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5788                              SVal.getValue(0)));
5789       } else
5790         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5791     } else {
5792       // Put argument in the parameter list area of the current stack frame.
5793       assert(VA.isMemLoc());
5794       unsigned LocMemOffset = VA.getLocMemOffset();
5795 
5796       if (!IsTailCall) {
5797         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5798         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5799                              StackPtr, PtrOff);
5800 
5801         MemOpChains.push_back(
5802             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5803       } else {
5804         // Calculate and remember argument location.
5805         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5806                                  TailCallArguments);
5807       }
5808     }
5809   }
5810 
5811   if (!MemOpChains.empty())
5812     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5813 
5814   // Build a sequence of copy-to-reg nodes chained together with token chain
5815   // and flag operands which copy the outgoing args into the appropriate regs.
5816   SDValue InFlag;
5817   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5818     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5819                              RegsToPass[i].second, InFlag);
5820     InFlag = Chain.getValue(1);
5821   }
5822 
5823   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5824   // registers.
5825   if (IsVarArg) {
5826     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5827     SDValue Ops[] = { Chain, InFlag };
5828 
5829     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5830                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5831 
5832     InFlag = Chain.getValue(1);
5833   }
5834 
5835   if (IsTailCall)
5836     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5837                     TailCallArguments);
5838 
5839   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5840                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5841 }
5842 
5843 // Copy an argument into memory, being careful to do this outside the
5844 // call sequence for the call to which the argument belongs.
5845 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5846     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5847     SelectionDAG &DAG, const SDLoc &dl) const {
5848   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5849                         CallSeqStart.getNode()->getOperand(0),
5850                         Flags, DAG, dl);
5851   // The MEMCPY must go outside the CALLSEQ_START..END.
5852   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5853   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5854                                                  SDLoc(MemcpyCall));
5855   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5856                          NewCallSeqStart.getNode());
5857   return NewCallSeqStart;
5858 }
5859 
5860 SDValue PPCTargetLowering::LowerCall_64SVR4(
5861     SDValue Chain, SDValue Callee, CallFlags CFlags,
5862     const SmallVectorImpl<ISD::OutputArg> &Outs,
5863     const SmallVectorImpl<SDValue> &OutVals,
5864     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5865     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5866     const CallBase *CB) const {
5867   bool isELFv2ABI = Subtarget.isELFv2ABI();
5868   bool isLittleEndian = Subtarget.isLittleEndian();
5869   unsigned NumOps = Outs.size();
5870   bool IsSibCall = false;
5871   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5872 
5873   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5874   unsigned PtrByteSize = 8;
5875 
5876   MachineFunction &MF = DAG.getMachineFunction();
5877 
5878   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5879     IsSibCall = true;
5880 
5881   // Mark this function as potentially containing a function that contains a
5882   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5883   // and restoring the callers stack pointer in this functions epilog. This is
5884   // done because by tail calling the called function might overwrite the value
5885   // in this function's (MF) stack pointer stack slot 0(SP).
5886   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5887     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5888 
5889   assert(!(IsFastCall && CFlags.IsVarArg) &&
5890          "fastcc not supported on varargs functions");
5891 
5892   // Count how many bytes are to be pushed on the stack, including the linkage
5893   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5894   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5895   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5896   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5897   unsigned NumBytes = LinkageSize;
5898   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5899   unsigned &QFPR_idx = FPR_idx;
5900 
5901   static const MCPhysReg GPR[] = {
5902     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5903     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5904   };
5905   static const MCPhysReg VR[] = {
5906     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5907     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5908   };
5909 
5910   const unsigned NumGPRs = array_lengthof(GPR);
5911   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5912   const unsigned NumVRs  = array_lengthof(VR);
5913   const unsigned NumQFPRs = NumFPRs;
5914 
5915   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5916   // can be passed to the callee in registers.
5917   // For the fast calling convention, there is another check below.
5918   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5919   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5920   if (!HasParameterArea) {
5921     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5922     unsigned AvailableFPRs = NumFPRs;
5923     unsigned AvailableVRs = NumVRs;
5924     unsigned NumBytesTmp = NumBytes;
5925     for (unsigned i = 0; i != NumOps; ++i) {
5926       if (Outs[i].Flags.isNest()) continue;
5927       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5928                                 PtrByteSize, LinkageSize, ParamAreaSize,
5929                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5930                                 Subtarget.hasQPX()))
5931         HasParameterArea = true;
5932     }
5933   }
5934 
5935   // When using the fast calling convention, we don't provide backing for
5936   // arguments that will be in registers.
5937   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5938 
5939   // Avoid allocating parameter area for fastcc functions if all the arguments
5940   // can be passed in the registers.
5941   if (IsFastCall)
5942     HasParameterArea = false;
5943 
5944   // Add up all the space actually used.
5945   for (unsigned i = 0; i != NumOps; ++i) {
5946     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5947     EVT ArgVT = Outs[i].VT;
5948     EVT OrigVT = Outs[i].ArgVT;
5949 
5950     if (Flags.isNest())
5951       continue;
5952 
5953     if (IsFastCall) {
5954       if (Flags.isByVal()) {
5955         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5956         if (NumGPRsUsed > NumGPRs)
5957           HasParameterArea = true;
5958       } else {
5959         switch (ArgVT.getSimpleVT().SimpleTy) {
5960         default: llvm_unreachable("Unexpected ValueType for argument!");
5961         case MVT::i1:
5962         case MVT::i32:
5963         case MVT::i64:
5964           if (++NumGPRsUsed <= NumGPRs)
5965             continue;
5966           break;
5967         case MVT::v4i32:
5968         case MVT::v8i16:
5969         case MVT::v16i8:
5970         case MVT::v2f64:
5971         case MVT::v2i64:
5972         case MVT::v1i128:
5973         case MVT::f128:
5974           if (++NumVRsUsed <= NumVRs)
5975             continue;
5976           break;
5977         case MVT::v4f32:
5978           // When using QPX, this is handled like a FP register, otherwise, it
5979           // is an Altivec register.
5980           if (Subtarget.hasQPX()) {
5981             if (++NumFPRsUsed <= NumFPRs)
5982               continue;
5983           } else {
5984             if (++NumVRsUsed <= NumVRs)
5985               continue;
5986           }
5987           break;
5988         case MVT::f32:
5989         case MVT::f64:
5990         case MVT::v4f64: // QPX
5991         case MVT::v4i1:  // QPX
5992           if (++NumFPRsUsed <= NumFPRs)
5993             continue;
5994           break;
5995         }
5996         HasParameterArea = true;
5997       }
5998     }
5999 
6000     /* Respect alignment of argument on the stack.  */
6001     auto Alignement =
6002         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6003     NumBytes = alignTo(NumBytes, Alignement);
6004 
6005     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6006     if (Flags.isInConsecutiveRegsLast())
6007       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6008   }
6009 
6010   unsigned NumBytesActuallyUsed = NumBytes;
6011 
6012   // In the old ELFv1 ABI,
6013   // the prolog code of the callee may store up to 8 GPR argument registers to
6014   // the stack, allowing va_start to index over them in memory if its varargs.
6015   // Because we cannot tell if this is needed on the caller side, we have to
6016   // conservatively assume that it is needed.  As such, make sure we have at
6017   // least enough stack space for the caller to store the 8 GPRs.
6018   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6019   // really requires memory operands, e.g. a vararg function.
6020   if (HasParameterArea)
6021     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6022   else
6023     NumBytes = LinkageSize;
6024 
6025   // Tail call needs the stack to be aligned.
6026   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6027     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6028 
6029   int SPDiff = 0;
6030 
6031   // Calculate by how many bytes the stack has to be adjusted in case of tail
6032   // call optimization.
6033   if (!IsSibCall)
6034     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6035 
6036   // To protect arguments on the stack from being clobbered in a tail call,
6037   // force all the loads to happen before doing any other lowering.
6038   if (CFlags.IsTailCall)
6039     Chain = DAG.getStackArgumentTokenFactor(Chain);
6040 
6041   // Adjust the stack pointer for the new arguments...
6042   // These operations are automatically eliminated by the prolog/epilog pass
6043   if (!IsSibCall)
6044     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6045   SDValue CallSeqStart = Chain;
6046 
6047   // Load the return address and frame pointer so it can be move somewhere else
6048   // later.
6049   SDValue LROp, FPOp;
6050   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6051 
6052   // Set up a copy of the stack pointer for use loading and storing any
6053   // arguments that may not fit in the registers available for argument
6054   // passing.
6055   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6056 
6057   // Figure out which arguments are going to go in registers, and which in
6058   // memory.  Also, if this is a vararg function, floating point operations
6059   // must be stored to our stack, and loaded into integer regs as well, if
6060   // any integer regs are available for argument passing.
6061   unsigned ArgOffset = LinkageSize;
6062 
6063   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6064   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6065 
6066   SmallVector<SDValue, 8> MemOpChains;
6067   for (unsigned i = 0; i != NumOps; ++i) {
6068     SDValue Arg = OutVals[i];
6069     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6070     EVT ArgVT = Outs[i].VT;
6071     EVT OrigVT = Outs[i].ArgVT;
6072 
6073     // PtrOff will be used to store the current argument to the stack if a
6074     // register cannot be found for it.
6075     SDValue PtrOff;
6076 
6077     // We re-align the argument offset for each argument, except when using the
6078     // fast calling convention, when we need to make sure we do that only when
6079     // we'll actually use a stack slot.
6080     auto ComputePtrOff = [&]() {
6081       /* Respect alignment of argument on the stack.  */
6082       auto Alignment =
6083           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6084       ArgOffset = alignTo(ArgOffset, Alignment);
6085 
6086       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6087 
6088       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6089     };
6090 
6091     if (!IsFastCall) {
6092       ComputePtrOff();
6093 
6094       /* Compute GPR index associated with argument offset.  */
6095       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6096       GPR_idx = std::min(GPR_idx, NumGPRs);
6097     }
6098 
6099     // Promote integers to 64-bit values.
6100     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6101       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6102       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6103       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6104     }
6105 
6106     // FIXME memcpy is used way more than necessary.  Correctness first.
6107     // Note: "by value" is code for passing a structure by value, not
6108     // basic types.
6109     if (Flags.isByVal()) {
6110       // Note: Size includes alignment padding, so
6111       //   struct x { short a; char b; }
6112       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6113       // These are the proper values we need for right-justifying the
6114       // aggregate in a parameter register.
6115       unsigned Size = Flags.getByValSize();
6116 
6117       // An empty aggregate parameter takes up no storage and no
6118       // registers.
6119       if (Size == 0)
6120         continue;
6121 
6122       if (IsFastCall)
6123         ComputePtrOff();
6124 
6125       // All aggregates smaller than 8 bytes must be passed right-justified.
6126       if (Size==1 || Size==2 || Size==4) {
6127         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6128         if (GPR_idx != NumGPRs) {
6129           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6130                                         MachinePointerInfo(), VT);
6131           MemOpChains.push_back(Load.getValue(1));
6132           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6133 
6134           ArgOffset += PtrByteSize;
6135           continue;
6136         }
6137       }
6138 
6139       if (GPR_idx == NumGPRs && Size < 8) {
6140         SDValue AddPtr = PtrOff;
6141         if (!isLittleEndian) {
6142           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6143                                           PtrOff.getValueType());
6144           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6145         }
6146         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6147                                                           CallSeqStart,
6148                                                           Flags, DAG, dl);
6149         ArgOffset += PtrByteSize;
6150         continue;
6151       }
6152       // Copy entire object into memory.  There are cases where gcc-generated
6153       // code assumes it is there, even if it could be put entirely into
6154       // registers.  (This is not what the doc says.)
6155 
6156       // FIXME: The above statement is likely due to a misunderstanding of the
6157       // documents.  All arguments must be copied into the parameter area BY
6158       // THE CALLEE in the event that the callee takes the address of any
6159       // formal argument.  That has not yet been implemented.  However, it is
6160       // reasonable to use the stack area as a staging area for the register
6161       // load.
6162 
6163       // Skip this for small aggregates, as we will use the same slot for a
6164       // right-justified copy, below.
6165       if (Size >= 8)
6166         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6167                                                           CallSeqStart,
6168                                                           Flags, DAG, dl);
6169 
6170       // When a register is available, pass a small aggregate right-justified.
6171       if (Size < 8 && GPR_idx != NumGPRs) {
6172         // The easiest way to get this right-justified in a register
6173         // is to copy the structure into the rightmost portion of a
6174         // local variable slot, then load the whole slot into the
6175         // register.
6176         // FIXME: The memcpy seems to produce pretty awful code for
6177         // small aggregates, particularly for packed ones.
6178         // FIXME: It would be preferable to use the slot in the
6179         // parameter save area instead of a new local variable.
6180         SDValue AddPtr = PtrOff;
6181         if (!isLittleEndian) {
6182           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6183           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6184         }
6185         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6186                                                           CallSeqStart,
6187                                                           Flags, DAG, dl);
6188 
6189         // Load the slot into the register.
6190         SDValue Load =
6191             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6192         MemOpChains.push_back(Load.getValue(1));
6193         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6194 
6195         // Done with this argument.
6196         ArgOffset += PtrByteSize;
6197         continue;
6198       }
6199 
6200       // For aggregates larger than PtrByteSize, copy the pieces of the
6201       // object that fit into registers from the parameter save area.
6202       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6203         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6204         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6205         if (GPR_idx != NumGPRs) {
6206           SDValue Load =
6207               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6208           MemOpChains.push_back(Load.getValue(1));
6209           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6210           ArgOffset += PtrByteSize;
6211         } else {
6212           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6213           break;
6214         }
6215       }
6216       continue;
6217     }
6218 
6219     switch (Arg.getSimpleValueType().SimpleTy) {
6220     default: llvm_unreachable("Unexpected ValueType for argument!");
6221     case MVT::i1:
6222     case MVT::i32:
6223     case MVT::i64:
6224       if (Flags.isNest()) {
6225         // The 'nest' parameter, if any, is passed in R11.
6226         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6227         break;
6228       }
6229 
6230       // These can be scalar arguments or elements of an integer array type
6231       // passed directly.  Clang may use those instead of "byval" aggregate
6232       // types to avoid forcing arguments to memory unnecessarily.
6233       if (GPR_idx != NumGPRs) {
6234         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6235       } else {
6236         if (IsFastCall)
6237           ComputePtrOff();
6238 
6239         assert(HasParameterArea &&
6240                "Parameter area must exist to pass an argument in memory.");
6241         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6242                          true, CFlags.IsTailCall, false, MemOpChains,
6243                          TailCallArguments, dl);
6244         if (IsFastCall)
6245           ArgOffset += PtrByteSize;
6246       }
6247       if (!IsFastCall)
6248         ArgOffset += PtrByteSize;
6249       break;
6250     case MVT::f32:
6251     case MVT::f64: {
6252       // These can be scalar arguments or elements of a float array type
6253       // passed directly.  The latter are used to implement ELFv2 homogenous
6254       // float aggregates.
6255 
6256       // Named arguments go into FPRs first, and once they overflow, the
6257       // remaining arguments go into GPRs and then the parameter save area.
6258       // Unnamed arguments for vararg functions always go to GPRs and
6259       // then the parameter save area.  For now, put all arguments to vararg
6260       // routines always in both locations (FPR *and* GPR or stack slot).
6261       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6262       bool NeededLoad = false;
6263 
6264       // First load the argument into the next available FPR.
6265       if (FPR_idx != NumFPRs)
6266         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6267 
6268       // Next, load the argument into GPR or stack slot if needed.
6269       if (!NeedGPROrStack)
6270         ;
6271       else if (GPR_idx != NumGPRs && !IsFastCall) {
6272         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6273         // once we support fp <-> gpr moves.
6274 
6275         // In the non-vararg case, this can only ever happen in the
6276         // presence of f32 array types, since otherwise we never run
6277         // out of FPRs before running out of GPRs.
6278         SDValue ArgVal;
6279 
6280         // Double values are always passed in a single GPR.
6281         if (Arg.getValueType() != MVT::f32) {
6282           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6283 
6284         // Non-array float values are extended and passed in a GPR.
6285         } else if (!Flags.isInConsecutiveRegs()) {
6286           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6287           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6288 
6289         // If we have an array of floats, we collect every odd element
6290         // together with its predecessor into one GPR.
6291         } else if (ArgOffset % PtrByteSize != 0) {
6292           SDValue Lo, Hi;
6293           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6294           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6295           if (!isLittleEndian)
6296             std::swap(Lo, Hi);
6297           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6298 
6299         // The final element, if even, goes into the first half of a GPR.
6300         } else if (Flags.isInConsecutiveRegsLast()) {
6301           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6302           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6303           if (!isLittleEndian)
6304             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6305                                  DAG.getConstant(32, dl, MVT::i32));
6306 
6307         // Non-final even elements are skipped; they will be handled
6308         // together the with subsequent argument on the next go-around.
6309         } else
6310           ArgVal = SDValue();
6311 
6312         if (ArgVal.getNode())
6313           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6314       } else {
6315         if (IsFastCall)
6316           ComputePtrOff();
6317 
6318         // Single-precision floating-point values are mapped to the
6319         // second (rightmost) word of the stack doubleword.
6320         if (Arg.getValueType() == MVT::f32 &&
6321             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6322           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6323           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6324         }
6325 
6326         assert(HasParameterArea &&
6327                "Parameter area must exist to pass an argument in memory.");
6328         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6329                          true, CFlags.IsTailCall, false, MemOpChains,
6330                          TailCallArguments, dl);
6331 
6332         NeededLoad = true;
6333       }
6334       // When passing an array of floats, the array occupies consecutive
6335       // space in the argument area; only round up to the next doubleword
6336       // at the end of the array.  Otherwise, each float takes 8 bytes.
6337       if (!IsFastCall || NeededLoad) {
6338         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6339                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6340         if (Flags.isInConsecutiveRegsLast())
6341           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6342       }
6343       break;
6344     }
6345     case MVT::v4f32:
6346     case MVT::v4i32:
6347     case MVT::v8i16:
6348     case MVT::v16i8:
6349     case MVT::v2f64:
6350     case MVT::v2i64:
6351     case MVT::v1i128:
6352     case MVT::f128:
6353       if (!Subtarget.hasQPX()) {
6354       // These can be scalar arguments or elements of a vector array type
6355       // passed directly.  The latter are used to implement ELFv2 homogenous
6356       // vector aggregates.
6357 
6358       // For a varargs call, named arguments go into VRs or on the stack as
6359       // usual; unnamed arguments always go to the stack or the corresponding
6360       // GPRs when within range.  For now, we always put the value in both
6361       // locations (or even all three).
6362       if (CFlags.IsVarArg) {
6363         assert(HasParameterArea &&
6364                "Parameter area must exist if we have a varargs call.");
6365         // We could elide this store in the case where the object fits
6366         // entirely in R registers.  Maybe later.
6367         SDValue Store =
6368             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6369         MemOpChains.push_back(Store);
6370         if (VR_idx != NumVRs) {
6371           SDValue Load =
6372               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6373           MemOpChains.push_back(Load.getValue(1));
6374           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6375         }
6376         ArgOffset += 16;
6377         for (unsigned i=0; i<16; i+=PtrByteSize) {
6378           if (GPR_idx == NumGPRs)
6379             break;
6380           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6381                                    DAG.getConstant(i, dl, PtrVT));
6382           SDValue Load =
6383               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6384           MemOpChains.push_back(Load.getValue(1));
6385           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6386         }
6387         break;
6388       }
6389 
6390       // Non-varargs Altivec params go into VRs or on the stack.
6391       if (VR_idx != NumVRs) {
6392         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6393       } else {
6394         if (IsFastCall)
6395           ComputePtrOff();
6396 
6397         assert(HasParameterArea &&
6398                "Parameter area must exist to pass an argument in memory.");
6399         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6400                          true, CFlags.IsTailCall, true, MemOpChains,
6401                          TailCallArguments, dl);
6402         if (IsFastCall)
6403           ArgOffset += 16;
6404       }
6405 
6406       if (!IsFastCall)
6407         ArgOffset += 16;
6408       break;
6409       } // not QPX
6410 
6411       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6412              "Invalid QPX parameter type");
6413 
6414       LLVM_FALLTHROUGH;
6415     case MVT::v4f64:
6416     case MVT::v4i1: {
6417       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6418       if (CFlags.IsVarArg) {
6419         assert(HasParameterArea &&
6420                "Parameter area must exist if we have a varargs call.");
6421         // We could elide this store in the case where the object fits
6422         // entirely in R registers.  Maybe later.
6423         SDValue Store =
6424             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6425         MemOpChains.push_back(Store);
6426         if (QFPR_idx != NumQFPRs) {
6427           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6428                                      PtrOff, MachinePointerInfo());
6429           MemOpChains.push_back(Load.getValue(1));
6430           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6431         }
6432         ArgOffset += (IsF32 ? 16 : 32);
6433         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6434           if (GPR_idx == NumGPRs)
6435             break;
6436           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6437                                    DAG.getConstant(i, dl, PtrVT));
6438           SDValue Load =
6439               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6440           MemOpChains.push_back(Load.getValue(1));
6441           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6442         }
6443         break;
6444       }
6445 
6446       // Non-varargs QPX params go into registers or on the stack.
6447       if (QFPR_idx != NumQFPRs) {
6448         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6449       } else {
6450         if (IsFastCall)
6451           ComputePtrOff();
6452 
6453         assert(HasParameterArea &&
6454                "Parameter area must exist to pass an argument in memory.");
6455         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6456                          true, CFlags.IsTailCall, true, MemOpChains,
6457                          TailCallArguments, dl);
6458         if (IsFastCall)
6459           ArgOffset += (IsF32 ? 16 : 32);
6460       }
6461 
6462       if (!IsFastCall)
6463         ArgOffset += (IsF32 ? 16 : 32);
6464       break;
6465       }
6466     }
6467   }
6468 
6469   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6470          "mismatch in size of parameter area");
6471   (void)NumBytesActuallyUsed;
6472 
6473   if (!MemOpChains.empty())
6474     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6475 
6476   // Check if this is an indirect call (MTCTR/BCTRL).
6477   // See prepareDescriptorIndirectCall and buildCallOperands for more
6478   // information about calls through function pointers in the 64-bit SVR4 ABI.
6479   if (CFlags.IsIndirect) {
6480     assert(!CFlags.IsTailCall &&  "Indirect tails calls not supported");
6481     // Load r2 into a virtual register and store it to the TOC save area.
6482     setUsesTOCBasePtr(DAG);
6483     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6484     // TOC save area offset.
6485     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6486     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6487     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6488     Chain = DAG.getStore(
6489         Val.getValue(1), dl, Val, AddPtr,
6490         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6491     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6492     // This does not mean the MTCTR instruction must use R12; it's easier
6493     // to model this as an extra parameter, so do that.
6494     if (isELFv2ABI && !CFlags.IsPatchPoint)
6495       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6496   }
6497 
6498   // Build a sequence of copy-to-reg nodes chained together with token chain
6499   // and flag operands which copy the outgoing args into the appropriate regs.
6500   SDValue InFlag;
6501   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6502     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6503                              RegsToPass[i].second, InFlag);
6504     InFlag = Chain.getValue(1);
6505   }
6506 
6507   if (CFlags.IsTailCall && !IsSibCall)
6508     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6509                     TailCallArguments);
6510 
6511   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6512                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6513 }
6514 
6515 SDValue PPCTargetLowering::LowerCall_Darwin(
6516     SDValue Chain, SDValue Callee, CallFlags CFlags,
6517     const SmallVectorImpl<ISD::OutputArg> &Outs,
6518     const SmallVectorImpl<SDValue> &OutVals,
6519     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6520     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6521     const CallBase *CB) const {
6522   unsigned NumOps = Outs.size();
6523 
6524   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6525   bool isPPC64 = PtrVT == MVT::i64;
6526   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6527 
6528   MachineFunction &MF = DAG.getMachineFunction();
6529 
6530   // Mark this function as potentially containing a function that contains a
6531   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6532   // and restoring the callers stack pointer in this functions epilog. This is
6533   // done because by tail calling the called function might overwrite the value
6534   // in this function's (MF) stack pointer stack slot 0(SP).
6535   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6536       CFlags.CallConv == CallingConv::Fast)
6537     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6538 
6539   // Count how many bytes are to be pushed on the stack, including the linkage
6540   // area, and parameter passing area.  We start with 24/48 bytes, which is
6541   // prereserved space for [SP][CR][LR][3 x unused].
6542   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6543   unsigned NumBytes = LinkageSize;
6544 
6545   // Add up all the space actually used.
6546   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6547   // they all go in registers, but we must reserve stack space for them for
6548   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6549   // assigned stack space in order, with padding so Altivec parameters are
6550   // 16-byte aligned.
6551   unsigned nAltivecParamsAtEnd = 0;
6552   for (unsigned i = 0; i != NumOps; ++i) {
6553     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6554     EVT ArgVT = Outs[i].VT;
6555     // Varargs Altivec parameters are padded to a 16 byte boundary.
6556     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6557         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6558         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6559       if (!CFlags.IsVarArg && !isPPC64) {
6560         // Non-varargs Altivec parameters go after all the non-Altivec
6561         // parameters; handle those later so we know how much padding we need.
6562         nAltivecParamsAtEnd++;
6563         continue;
6564       }
6565       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6566       NumBytes = ((NumBytes+15)/16)*16;
6567     }
6568     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6569   }
6570 
6571   // Allow for Altivec parameters at the end, if needed.
6572   if (nAltivecParamsAtEnd) {
6573     NumBytes = ((NumBytes+15)/16)*16;
6574     NumBytes += 16*nAltivecParamsAtEnd;
6575   }
6576 
6577   // The prolog code of the callee may store up to 8 GPR argument registers to
6578   // the stack, allowing va_start to index over them in memory if its varargs.
6579   // Because we cannot tell if this is needed on the caller side, we have to
6580   // conservatively assume that it is needed.  As such, make sure we have at
6581   // least enough stack space for the caller to store the 8 GPRs.
6582   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6583 
6584   // Tail call needs the stack to be aligned.
6585   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6586       CFlags.CallConv == CallingConv::Fast)
6587     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6588 
6589   // Calculate by how many bytes the stack has to be adjusted in case of tail
6590   // call optimization.
6591   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6592 
6593   // To protect arguments on the stack from being clobbered in a tail call,
6594   // force all the loads to happen before doing any other lowering.
6595   if (CFlags.IsTailCall)
6596     Chain = DAG.getStackArgumentTokenFactor(Chain);
6597 
6598   // Adjust the stack pointer for the new arguments...
6599   // These operations are automatically eliminated by the prolog/epilog pass
6600   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6601   SDValue CallSeqStart = Chain;
6602 
6603   // Load the return address and frame pointer so it can be move somewhere else
6604   // later.
6605   SDValue LROp, FPOp;
6606   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6607 
6608   // Set up a copy of the stack pointer for use loading and storing any
6609   // arguments that may not fit in the registers available for argument
6610   // passing.
6611   SDValue StackPtr;
6612   if (isPPC64)
6613     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6614   else
6615     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6616 
6617   // Figure out which arguments are going to go in registers, and which in
6618   // memory.  Also, if this is a vararg function, floating point operations
6619   // must be stored to our stack, and loaded into integer regs as well, if
6620   // any integer regs are available for argument passing.
6621   unsigned ArgOffset = LinkageSize;
6622   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6623 
6624   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6625     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6626     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6627   };
6628   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6629     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6630     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6631   };
6632   static const MCPhysReg VR[] = {
6633     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6634     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6635   };
6636   const unsigned NumGPRs = array_lengthof(GPR_32);
6637   const unsigned NumFPRs = 13;
6638   const unsigned NumVRs  = array_lengthof(VR);
6639 
6640   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6641 
6642   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6643   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6644 
6645   SmallVector<SDValue, 8> MemOpChains;
6646   for (unsigned i = 0; i != NumOps; ++i) {
6647     SDValue Arg = OutVals[i];
6648     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6649 
6650     // PtrOff will be used to store the current argument to the stack if a
6651     // register cannot be found for it.
6652     SDValue PtrOff;
6653 
6654     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6655 
6656     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6657 
6658     // On PPC64, promote integers to 64-bit values.
6659     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6660       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6661       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6662       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6663     }
6664 
6665     // FIXME memcpy is used way more than necessary.  Correctness first.
6666     // Note: "by value" is code for passing a structure by value, not
6667     // basic types.
6668     if (Flags.isByVal()) {
6669       unsigned Size = Flags.getByValSize();
6670       // Very small objects are passed right-justified.  Everything else is
6671       // passed left-justified.
6672       if (Size==1 || Size==2) {
6673         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6674         if (GPR_idx != NumGPRs) {
6675           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6676                                         MachinePointerInfo(), VT);
6677           MemOpChains.push_back(Load.getValue(1));
6678           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6679 
6680           ArgOffset += PtrByteSize;
6681         } else {
6682           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6683                                           PtrOff.getValueType());
6684           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6685           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6686                                                             CallSeqStart,
6687                                                             Flags, DAG, dl);
6688           ArgOffset += PtrByteSize;
6689         }
6690         continue;
6691       }
6692       // Copy entire object into memory.  There are cases where gcc-generated
6693       // code assumes it is there, even if it could be put entirely into
6694       // registers.  (This is not what the doc says.)
6695       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6696                                                         CallSeqStart,
6697                                                         Flags, DAG, dl);
6698 
6699       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6700       // copy the pieces of the object that fit into registers from the
6701       // parameter save area.
6702       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6703         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6704         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6705         if (GPR_idx != NumGPRs) {
6706           SDValue Load =
6707               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6708           MemOpChains.push_back(Load.getValue(1));
6709           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6710           ArgOffset += PtrByteSize;
6711         } else {
6712           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6713           break;
6714         }
6715       }
6716       continue;
6717     }
6718 
6719     switch (Arg.getSimpleValueType().SimpleTy) {
6720     default: llvm_unreachable("Unexpected ValueType for argument!");
6721     case MVT::i1:
6722     case MVT::i32:
6723     case MVT::i64:
6724       if (GPR_idx != NumGPRs) {
6725         if (Arg.getValueType() == MVT::i1)
6726           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6727 
6728         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6729       } else {
6730         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6731                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6732                          TailCallArguments, dl);
6733       }
6734       ArgOffset += PtrByteSize;
6735       break;
6736     case MVT::f32:
6737     case MVT::f64:
6738       if (FPR_idx != NumFPRs) {
6739         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6740 
6741         if (CFlags.IsVarArg) {
6742           SDValue Store =
6743               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6744           MemOpChains.push_back(Store);
6745 
6746           // Float varargs are always shadowed in available integer registers
6747           if (GPR_idx != NumGPRs) {
6748             SDValue Load =
6749                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6750             MemOpChains.push_back(Load.getValue(1));
6751             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6752           }
6753           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6754             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6755             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6756             SDValue Load =
6757                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6758             MemOpChains.push_back(Load.getValue(1));
6759             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6760           }
6761         } else {
6762           // If we have any FPRs remaining, we may also have GPRs remaining.
6763           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6764           // GPRs.
6765           if (GPR_idx != NumGPRs)
6766             ++GPR_idx;
6767           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6768               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6769             ++GPR_idx;
6770         }
6771       } else
6772         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6773                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6774                          TailCallArguments, dl);
6775       if (isPPC64)
6776         ArgOffset += 8;
6777       else
6778         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6779       break;
6780     case MVT::v4f32:
6781     case MVT::v4i32:
6782     case MVT::v8i16:
6783     case MVT::v16i8:
6784       if (CFlags.IsVarArg) {
6785         // These go aligned on the stack, or in the corresponding R registers
6786         // when within range.  The Darwin PPC ABI doc claims they also go in
6787         // V registers; in fact gcc does this only for arguments that are
6788         // prototyped, not for those that match the ...  We do it for all
6789         // arguments, seems to work.
6790         while (ArgOffset % 16 !=0) {
6791           ArgOffset += PtrByteSize;
6792           if (GPR_idx != NumGPRs)
6793             GPR_idx++;
6794         }
6795         // We could elide this store in the case where the object fits
6796         // entirely in R registers.  Maybe later.
6797         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6798                              DAG.getConstant(ArgOffset, dl, PtrVT));
6799         SDValue Store =
6800             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6801         MemOpChains.push_back(Store);
6802         if (VR_idx != NumVRs) {
6803           SDValue Load =
6804               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6805           MemOpChains.push_back(Load.getValue(1));
6806           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6807         }
6808         ArgOffset += 16;
6809         for (unsigned i=0; i<16; i+=PtrByteSize) {
6810           if (GPR_idx == NumGPRs)
6811             break;
6812           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6813                                    DAG.getConstant(i, dl, PtrVT));
6814           SDValue Load =
6815               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6816           MemOpChains.push_back(Load.getValue(1));
6817           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6818         }
6819         break;
6820       }
6821 
6822       // Non-varargs Altivec params generally go in registers, but have
6823       // stack space allocated at the end.
6824       if (VR_idx != NumVRs) {
6825         // Doesn't have GPR space allocated.
6826         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6827       } else if (nAltivecParamsAtEnd==0) {
6828         // We are emitting Altivec params in order.
6829         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6830                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6831                          TailCallArguments, dl);
6832         ArgOffset += 16;
6833       }
6834       break;
6835     }
6836   }
6837   // If all Altivec parameters fit in registers, as they usually do,
6838   // they get stack space following the non-Altivec parameters.  We
6839   // don't track this here because nobody below needs it.
6840   // If there are more Altivec parameters than fit in registers emit
6841   // the stores here.
6842   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6843     unsigned j = 0;
6844     // Offset is aligned; skip 1st 12 params which go in V registers.
6845     ArgOffset = ((ArgOffset+15)/16)*16;
6846     ArgOffset += 12*16;
6847     for (unsigned i = 0; i != NumOps; ++i) {
6848       SDValue Arg = OutVals[i];
6849       EVT ArgType = Outs[i].VT;
6850       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6851           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6852         if (++j > NumVRs) {
6853           SDValue PtrOff;
6854           // We are emitting Altivec params in order.
6855           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6856                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6857                            TailCallArguments, dl);
6858           ArgOffset += 16;
6859         }
6860       }
6861     }
6862   }
6863 
6864   if (!MemOpChains.empty())
6865     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6866 
6867   // On Darwin, R12 must contain the address of an indirect callee.  This does
6868   // not mean the MTCTR instruction must use R12; it's easier to model this as
6869   // an extra parameter, so do that.
6870   if (CFlags.IsIndirect) {
6871     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6872     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6873                                                    PPC::R12), Callee));
6874   }
6875 
6876   // Build a sequence of copy-to-reg nodes chained together with token chain
6877   // and flag operands which copy the outgoing args into the appropriate regs.
6878   SDValue InFlag;
6879   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6880     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6881                              RegsToPass[i].second, InFlag);
6882     InFlag = Chain.getValue(1);
6883   }
6884 
6885   if (CFlags.IsTailCall)
6886     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6887                     TailCallArguments);
6888 
6889   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6890                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6891 }
6892 
6893 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6894                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6895                    CCState &State) {
6896 
6897   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6898       State.getMachineFunction().getSubtarget());
6899   const bool IsPPC64 = Subtarget.isPPC64();
6900   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6901   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6902 
6903   assert((!ValVT.isInteger() ||
6904           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6905          "Integer argument exceeds register size: should have been legalized");
6906 
6907   if (ValVT == MVT::f128)
6908     report_fatal_error("f128 is unimplemented on AIX.");
6909 
6910   if (ArgFlags.isNest())
6911     report_fatal_error("Nest arguments are unimplemented.");
6912 
6913   if (ValVT.isVector() || LocVT.isVector())
6914     report_fatal_error("Vector arguments are unimplemented on AIX.");
6915 
6916   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6917                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6918                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6919   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6920                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6921                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6922 
6923   if (ArgFlags.isByVal()) {
6924     if (ArgFlags.getNonZeroByValAlign() > PtrByteSize)
6925       report_fatal_error("Pass-by-value arguments with alignment greater than "
6926                          "register width are not supported.");
6927 
6928     const unsigned ByValSize = ArgFlags.getByValSize();
6929 
6930     // An empty aggregate parameter takes up no storage and no registers,
6931     // but needs a MemLoc for a stack slot for the formal arguments side.
6932     if (ByValSize == 0) {
6933       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6934                                        State.getNextStackOffset(), RegVT,
6935                                        LocInfo));
6936       return false;
6937     }
6938 
6939     const unsigned StackSize = alignTo(ByValSize, PtrByteSize);
6940     unsigned Offset = State.AllocateStack(StackSize, PtrByteSize);
6941     for (const unsigned E = Offset + StackSize; Offset < E;
6942          Offset += PtrByteSize) {
6943       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6944         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6945       else {
6946         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6947                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6948                                          LocInfo));
6949         break;
6950       }
6951     }
6952     return false;
6953   }
6954 
6955   // Arguments always reserve parameter save area.
6956   switch (ValVT.SimpleTy) {
6957   default:
6958     report_fatal_error("Unhandled value type for argument.");
6959   case MVT::i64:
6960     // i64 arguments should have been split to i32 for PPC32.
6961     assert(IsPPC64 && "PPC32 should have split i64 values.");
6962     LLVM_FALLTHROUGH;
6963   case MVT::i1:
6964   case MVT::i32: {
6965     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
6966     // AIX integer arguments are always passed in register width.
6967     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6968       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6969                                   : CCValAssign::LocInfo::ZExt;
6970     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6971       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6972     else
6973       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6974 
6975     return false;
6976   }
6977   case MVT::f32:
6978   case MVT::f64: {
6979     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6980     const unsigned StoreSize = LocVT.getStoreSize();
6981     // Floats are always 4-byte aligned in the PSA on AIX.
6982     // This includes f64 in 64-bit mode for ABI compatibility.
6983     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6984     unsigned FReg = State.AllocateReg(FPR);
6985     if (FReg)
6986       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6987 
6988     // Reserve and initialize GPRs or initialize the PSA as required.
6989     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
6990       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6991         assert(FReg && "An FPR should be available when a GPR is reserved.");
6992         if (State.isVarArg()) {
6993           // Successfully reserved GPRs are only initialized for vararg calls.
6994           // Custom handling is required for:
6995           //   f64 in PPC32 needs to be split into 2 GPRs.
6996           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6997           State.addLoc(
6998               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6999         }
7000       } else {
7001         // If there are insufficient GPRs, the PSA needs to be initialized.
7002         // Initialization occurs even if an FPR was initialized for
7003         // compatibility with the AIX XL compiler. The full memory for the
7004         // argument will be initialized even if a prior word is saved in GPR.
7005         // A custom memLoc is used when the argument also passes in FPR so
7006         // that the callee handling can skip over it easily.
7007         State.addLoc(
7008             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7009                                              LocInfo)
7010                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7011         break;
7012       }
7013     }
7014 
7015     return false;
7016   }
7017   }
7018   return true;
7019 }
7020 
7021 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7022                                                     bool IsPPC64) {
7023   assert((IsPPC64 || SVT != MVT::i64) &&
7024          "i64 should have been split for 32-bit codegen.");
7025 
7026   switch (SVT) {
7027   default:
7028     report_fatal_error("Unexpected value type for formal argument");
7029   case MVT::i1:
7030   case MVT::i32:
7031   case MVT::i64:
7032     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7033   case MVT::f32:
7034     return &PPC::F4RCRegClass;
7035   case MVT::f64:
7036     return &PPC::F8RCRegClass;
7037   }
7038 }
7039 
7040 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7041                                         SelectionDAG &DAG, SDValue ArgValue,
7042                                         MVT LocVT, const SDLoc &dl) {
7043   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7044   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7045 
7046   if (Flags.isSExt())
7047     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7048                            DAG.getValueType(ValVT));
7049   else if (Flags.isZExt())
7050     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7051                            DAG.getValueType(ValVT));
7052 
7053   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7054 }
7055 
7056 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7057   const unsigned LASize = FL->getLinkageSize();
7058 
7059   if (PPC::GPRCRegClass.contains(Reg)) {
7060     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7061            "Reg must be a valid argument register!");
7062     return LASize + 4 * (Reg - PPC::R3);
7063   }
7064 
7065   if (PPC::G8RCRegClass.contains(Reg)) {
7066     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7067            "Reg must be a valid argument register!");
7068     return LASize + 8 * (Reg - PPC::X3);
7069   }
7070 
7071   llvm_unreachable("Only general purpose registers expected.");
7072 }
7073 
7074 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7075     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7076     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7077     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7078 
7079   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7080           CallConv == CallingConv::Fast) &&
7081          "Unexpected calling convention!");
7082 
7083   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7084     report_fatal_error("Tail call support is unimplemented on AIX.");
7085 
7086   if (useSoftFloat())
7087     report_fatal_error("Soft float support is unimplemented on AIX.");
7088 
7089   const PPCSubtarget &Subtarget =
7090       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7091   if (Subtarget.hasQPX())
7092     report_fatal_error("QPX support is not supported on AIX.");
7093 
7094   const bool IsPPC64 = Subtarget.isPPC64();
7095   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7096 
7097   // Assign locations to all of the incoming arguments.
7098   SmallVector<CCValAssign, 16> ArgLocs;
7099   MachineFunction &MF = DAG.getMachineFunction();
7100   MachineFrameInfo &MFI = MF.getFrameInfo();
7101   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7102 
7103   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7104   // Reserve space for the linkage area on the stack.
7105   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7106   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7107   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7108 
7109   SmallVector<SDValue, 8> MemOps;
7110 
7111   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7112     CCValAssign &VA = ArgLocs[I++];
7113     MVT LocVT = VA.getLocVT();
7114     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7115 
7116     // For compatibility with the AIX XL compiler, the float args in the
7117     // parameter save area are initialized even if the argument is available
7118     // in register.  The caller is required to initialize both the register
7119     // and memory, however, the callee can choose to expect it in either.
7120     // The memloc is dismissed here because the argument is retrieved from
7121     // the register.
7122     if (VA.isMemLoc() && VA.needsCustom())
7123       continue;
7124 
7125     if (Flags.isByVal() && VA.isMemLoc()) {
7126       if (Flags.getByValSize() != 0)
7127         report_fatal_error(
7128             "ByVal arguments passed on stack not implemented yet");
7129 
7130       const int FI = MF.getFrameInfo().CreateFixedObject(
7131           PtrByteSize, VA.getLocMemOffset(), /* IsImmutable */ false,
7132           /* IsAliased */ true);
7133       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7134       InVals.push_back(FIN);
7135 
7136       continue;
7137     }
7138 
7139     if (Flags.isByVal()) {
7140       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7141 
7142       const MCPhysReg ArgReg = VA.getLocReg();
7143       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7144 
7145       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7146         report_fatal_error("Over aligned byvals not supported yet.");
7147 
7148       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7149       const int FI = MF.getFrameInfo().CreateFixedObject(
7150           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7151           /* IsAliased */ true);
7152       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7153       InVals.push_back(FIN);
7154 
7155       // Add live ins for all the RegLocs for the same ByVal.
7156       const TargetRegisterClass *RegClass =
7157           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7158 
7159       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7160                                                unsigned Offset) {
7161         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7162         // Since the callers side has left justified the aggregate in the
7163         // register, we can simply store the entire register into the stack
7164         // slot.
7165         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7166         // The store to the fixedstack object is needed becuase accessing a
7167         // field of the ByVal will use a gep and load. Ideally we will optimize
7168         // to extracting the value from the register directly, and elide the
7169         // stores when the arguments address is not taken, but that will need to
7170         // be future work.
7171         SDValue Store =
7172             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7173                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7174                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7175 
7176         MemOps.push_back(Store);
7177       };
7178 
7179       unsigned Offset = 0;
7180       HandleRegLoc(VA.getLocReg(), Offset);
7181       Offset += PtrByteSize;
7182       for (; Offset != StackSize; Offset += PtrByteSize) {
7183         assert(I != End &&
7184                "Expecting enough RegLocs to copy entire ByVal arg.");
7185 
7186         if (!ArgLocs[I].isRegLoc())
7187           report_fatal_error("Passing ByVals split between registers and stack "
7188                              "not yet implemented.");
7189 
7190         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7191                "Expecting more RegLocs for ByVal argument.");
7192 
7193         const CCValAssign RL = ArgLocs[I++];
7194         HandleRegLoc(RL.getLocReg(), Offset);
7195       }
7196       continue;
7197     }
7198 
7199     EVT ValVT = VA.getValVT();
7200     if (VA.isRegLoc() && !VA.needsCustom()) {
7201       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7202       unsigned VReg =
7203           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7204       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7205       if (ValVT.isScalarInteger() &&
7206           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7207         ArgValue =
7208             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7209       }
7210       InVals.push_back(ArgValue);
7211       continue;
7212     }
7213     if (VA.isMemLoc()) {
7214       const unsigned LocSize = LocVT.getStoreSize();
7215       const unsigned ValSize = ValVT.getStoreSize();
7216       assert((ValSize <= LocSize) &&
7217              "Object size is larger than size of MemLoc");
7218       int CurArgOffset = VA.getLocMemOffset();
7219       // Objects are right-justified because AIX is big-endian.
7220       if (LocSize > ValSize)
7221         CurArgOffset += LocSize - ValSize;
7222       // Potential tail calls could cause overwriting of argument stack slots.
7223       const bool IsImmutable =
7224           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7225             (CallConv == CallingConv::Fast));
7226       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7227       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7228       SDValue ArgValue =
7229           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7230       InVals.push_back(ArgValue);
7231       continue;
7232     }
7233   }
7234 
7235   // On AIX a minimum of 8 words is saved to the parameter save area.
7236   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7237   // Area that is at least reserved in the caller of this function.
7238   unsigned CallerReservedArea =
7239       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7240 
7241   // Set the size that is at least reserved in caller of this function. Tail
7242   // call optimized function's reserved stack space needs to be aligned so
7243   // that taking the difference between two stack areas will result in an
7244   // aligned stack.
7245   CallerReservedArea =
7246       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7247   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7248   FuncInfo->setMinReservedArea(CallerReservedArea);
7249 
7250   if (isVarArg) {
7251     FuncInfo->setVarArgsFrameIndex(
7252         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7253     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7254 
7255     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7256                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7257 
7258     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7259                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7260     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7261 
7262     // The fixed integer arguments of a variadic function are stored to the
7263     // VarArgsFrameIndex on the stack so that they may be loaded by
7264     // dereferencing the result of va_next.
7265     for (unsigned GPRIndex =
7266              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7267          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7268 
7269       const unsigned VReg =
7270           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7271                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7272 
7273       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7274       SDValue Store =
7275           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7276       MemOps.push_back(Store);
7277       // Increment the address for the next argument to store.
7278       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7279       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7280     }
7281   }
7282 
7283   if (!MemOps.empty())
7284     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7285 
7286   return Chain;
7287 }
7288 
7289 SDValue PPCTargetLowering::LowerCall_AIX(
7290     SDValue Chain, SDValue Callee, CallFlags CFlags,
7291     const SmallVectorImpl<ISD::OutputArg> &Outs,
7292     const SmallVectorImpl<SDValue> &OutVals,
7293     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7294     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7295     const CallBase *CB) const {
7296 
7297   assert((CFlags.CallConv == CallingConv::C ||
7298           CFlags.CallConv == CallingConv::Cold ||
7299           CFlags.CallConv == CallingConv::Fast) &&
7300          "Unexpected calling convention!");
7301 
7302   if (CFlags.IsPatchPoint)
7303     report_fatal_error("This call type is unimplemented on AIX.");
7304 
7305   const PPCSubtarget& Subtarget =
7306       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7307   if (Subtarget.hasQPX())
7308     report_fatal_error("QPX is not supported on AIX.");
7309   if (Subtarget.hasAltivec())
7310     report_fatal_error("Altivec support is unimplemented on AIX.");
7311 
7312   MachineFunction &MF = DAG.getMachineFunction();
7313   SmallVector<CCValAssign, 16> ArgLocs;
7314   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7315                  *DAG.getContext());
7316 
7317   // Reserve space for the linkage save area (LSA) on the stack.
7318   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7319   //   [SP][CR][LR][2 x reserved][TOC].
7320   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7321   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7322   const bool IsPPC64 = Subtarget.isPPC64();
7323   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7324   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7325   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7326   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7327 
7328   // The prolog code of the callee may store up to 8 GPR argument registers to
7329   // the stack, allowing va_start to index over them in memory if the callee
7330   // is variadic.
7331   // Because we cannot tell if this is needed on the caller side, we have to
7332   // conservatively assume that it is needed.  As such, make sure we have at
7333   // least enough stack space for the caller to store the 8 GPRs.
7334   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7335   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7336                                      CCInfo.getNextStackOffset());
7337 
7338   // Adjust the stack pointer for the new arguments...
7339   // These operations are automatically eliminated by the prolog/epilog pass.
7340   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7341   SDValue CallSeqStart = Chain;
7342 
7343   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7344   SmallVector<SDValue, 8> MemOpChains;
7345 
7346   // Set up a copy of the stack pointer for loading and storing any
7347   // arguments that may not fit in the registers available for argument
7348   // passing.
7349   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7350                                    : DAG.getRegister(PPC::R1, MVT::i32);
7351 
7352   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7353     const unsigned ValNo = ArgLocs[I].getValNo();
7354     SDValue Arg = OutVals[ValNo];
7355     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7356 
7357     if (Flags.isByVal()) {
7358       const unsigned ByValSize = Flags.getByValSize();
7359 
7360       // Nothing to do for zero-sized ByVals on the caller side.
7361       if (!ByValSize) {
7362         ++I;
7363         continue;
7364       }
7365 
7366       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7367         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7368                               (LoadOffset != 0)
7369                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7370                                   : Arg,
7371                               MachinePointerInfo(), VT);
7372       };
7373 
7374       unsigned LoadOffset = 0;
7375 
7376       // Initialize registers, which are fully occupied by the by-val argument.
7377       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7378         SDValue Load = GetLoad(PtrVT, LoadOffset);
7379         MemOpChains.push_back(Load.getValue(1));
7380         LoadOffset += PtrByteSize;
7381         const CCValAssign &ByValVA = ArgLocs[I++];
7382         assert(ByValVA.getValNo() == ValNo &&
7383                "Unexpected location for pass-by-value argument.");
7384         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7385       }
7386 
7387       if (LoadOffset == ByValSize)
7388         continue;
7389 
7390       // There must be one more loc to handle the remainder.
7391       assert(ArgLocs[I].getValNo() == ValNo &&
7392              "Expected additional location for by-value argument.");
7393 
7394       if (ArgLocs[I].isMemLoc()) {
7395         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7396         const CCValAssign &ByValVA = ArgLocs[I++];
7397         ISD::ArgFlagsTy MemcpyFlags = Flags;
7398         // Only memcpy the bytes that don't pass in register.
7399         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7400         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7401             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7402                               : Arg,
7403             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7404             CallSeqStart, MemcpyFlags, DAG, dl);
7405         continue;
7406       }
7407 
7408       // Initialize the final register residue.
7409       // Any residue that occupies the final by-val arg register must be
7410       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7411       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7412       // 2 and 1 byte loads.
7413       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7414       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7415              "Unexpected register residue for by-value argument.");
7416       SDValue ResidueVal;
7417       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7418         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7419         const MVT VT =
7420             N == 1 ? MVT::i8
7421                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7422         SDValue Load = GetLoad(VT, LoadOffset);
7423         MemOpChains.push_back(Load.getValue(1));
7424         LoadOffset += N;
7425         Bytes += N;
7426 
7427         // By-val arguments are passed left-justfied in register.
7428         // Every load here needs to be shifted, otherwise a full register load
7429         // should have been used.
7430         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7431                "Unexpected load emitted during handling of pass-by-value "
7432                "argument.");
7433         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7434         EVT ShiftAmountTy =
7435             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7436         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7437         SDValue ShiftedLoad =
7438             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7439         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7440                                               ShiftedLoad)
7441                                 : ShiftedLoad;
7442       }
7443 
7444       const CCValAssign &ByValVA = ArgLocs[I++];
7445       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7446       continue;
7447     }
7448 
7449     CCValAssign &VA = ArgLocs[I++];
7450     const MVT LocVT = VA.getLocVT();
7451     const MVT ValVT = VA.getValVT();
7452 
7453     switch (VA.getLocInfo()) {
7454     default:
7455       report_fatal_error("Unexpected argument extension type.");
7456     case CCValAssign::Full:
7457       break;
7458     case CCValAssign::ZExt:
7459       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7460       break;
7461     case CCValAssign::SExt:
7462       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7463       break;
7464     }
7465 
7466     if (VA.isRegLoc() && !VA.needsCustom()) {
7467       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7468       continue;
7469     }
7470 
7471     if (VA.isMemLoc()) {
7472       SDValue PtrOff =
7473           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7474       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7475       MemOpChains.push_back(
7476           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7477 
7478       continue;
7479     }
7480 
7481     // Custom handling is used for GPR initializations for vararg float
7482     // arguments.
7483     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7484            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7485            "Unexpected register handling for calling convention.");
7486 
7487     SDValue ArgAsInt =
7488         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7489 
7490     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7491       // f32 in 32-bit GPR
7492       // f64 in 64-bit GPR
7493       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7494     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7495       // f32 in 64-bit GPR.
7496       RegsToPass.push_back(std::make_pair(
7497           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7498     else {
7499       // f64 in two 32-bit GPRs
7500       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7501       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7502              "Unexpected custom register for argument!");
7503       CCValAssign &GPR1 = VA;
7504       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7505                                      DAG.getConstant(32, dl, MVT::i8));
7506       RegsToPass.push_back(std::make_pair(
7507           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7508 
7509       if (I != E) {
7510         // If only 1 GPR was available, there will only be one custom GPR and
7511         // the argument will also pass in memory.
7512         CCValAssign &PeekArg = ArgLocs[I];
7513         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7514           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7515           CCValAssign &GPR2 = ArgLocs[I++];
7516           RegsToPass.push_back(std::make_pair(
7517               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7518         }
7519       }
7520     }
7521   }
7522 
7523   if (!MemOpChains.empty())
7524     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7525 
7526   // For indirect calls, we need to save the TOC base to the stack for
7527   // restoration after the call.
7528   if (CFlags.IsIndirect) {
7529     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7530     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7531     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7532     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7533     const unsigned TOCSaveOffset =
7534         Subtarget.getFrameLowering()->getTOCSaveOffset();
7535 
7536     setUsesTOCBasePtr(DAG);
7537     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7538     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7539     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7540     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7541     Chain = DAG.getStore(
7542         Val.getValue(1), dl, Val, AddPtr,
7543         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7544   }
7545 
7546   // Build a sequence of copy-to-reg nodes chained together with token chain
7547   // and flag operands which copy the outgoing args into the appropriate regs.
7548   SDValue InFlag;
7549   for (auto Reg : RegsToPass) {
7550     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7551     InFlag = Chain.getValue(1);
7552   }
7553 
7554   const int SPDiff = 0;
7555   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7556                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7557 }
7558 
7559 bool
7560 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7561                                   MachineFunction &MF, bool isVarArg,
7562                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7563                                   LLVMContext &Context) const {
7564   SmallVector<CCValAssign, 16> RVLocs;
7565   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7566   return CCInfo.CheckReturn(
7567       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7568                 ? RetCC_PPC_Cold
7569                 : RetCC_PPC);
7570 }
7571 
7572 SDValue
7573 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7574                                bool isVarArg,
7575                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7576                                const SmallVectorImpl<SDValue> &OutVals,
7577                                const SDLoc &dl, SelectionDAG &DAG) const {
7578   SmallVector<CCValAssign, 16> RVLocs;
7579   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7580                  *DAG.getContext());
7581   CCInfo.AnalyzeReturn(Outs,
7582                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7583                            ? RetCC_PPC_Cold
7584                            : RetCC_PPC);
7585 
7586   SDValue Flag;
7587   SmallVector<SDValue, 4> RetOps(1, Chain);
7588 
7589   // Copy the result values into the output registers.
7590   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7591     CCValAssign &VA = RVLocs[i];
7592     assert(VA.isRegLoc() && "Can only return in registers!");
7593 
7594     SDValue Arg = OutVals[RealResIdx];
7595 
7596     switch (VA.getLocInfo()) {
7597     default: llvm_unreachable("Unknown loc info!");
7598     case CCValAssign::Full: break;
7599     case CCValAssign::AExt:
7600       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7601       break;
7602     case CCValAssign::ZExt:
7603       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7604       break;
7605     case CCValAssign::SExt:
7606       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7607       break;
7608     }
7609     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7610       bool isLittleEndian = Subtarget.isLittleEndian();
7611       // Legalize ret f64 -> ret 2 x i32.
7612       SDValue SVal =
7613           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7614                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7615       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7616       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7617       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7618                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7619       Flag = Chain.getValue(1);
7620       VA = RVLocs[++i]; // skip ahead to next loc
7621       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7622     } else
7623       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7624     Flag = Chain.getValue(1);
7625     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7626   }
7627 
7628   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7629   const MCPhysReg *I =
7630     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7631   if (I) {
7632     for (; *I; ++I) {
7633 
7634       if (PPC::G8RCRegClass.contains(*I))
7635         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7636       else if (PPC::F8RCRegClass.contains(*I))
7637         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7638       else if (PPC::CRRCRegClass.contains(*I))
7639         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7640       else if (PPC::VRRCRegClass.contains(*I))
7641         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7642       else
7643         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7644     }
7645   }
7646 
7647   RetOps[0] = Chain;  // Update chain.
7648 
7649   // Add the flag if we have it.
7650   if (Flag.getNode())
7651     RetOps.push_back(Flag);
7652 
7653   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7654 }
7655 
7656 SDValue
7657 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7658                                                 SelectionDAG &DAG) const {
7659   SDLoc dl(Op);
7660 
7661   // Get the correct type for integers.
7662   EVT IntVT = Op.getValueType();
7663 
7664   // Get the inputs.
7665   SDValue Chain = Op.getOperand(0);
7666   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7667   // Build a DYNAREAOFFSET node.
7668   SDValue Ops[2] = {Chain, FPSIdx};
7669   SDVTList VTs = DAG.getVTList(IntVT);
7670   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7671 }
7672 
7673 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7674                                              SelectionDAG &DAG) const {
7675   // When we pop the dynamic allocation we need to restore the SP link.
7676   SDLoc dl(Op);
7677 
7678   // Get the correct type for pointers.
7679   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7680 
7681   // Construct the stack pointer operand.
7682   bool isPPC64 = Subtarget.isPPC64();
7683   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7684   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7685 
7686   // Get the operands for the STACKRESTORE.
7687   SDValue Chain = Op.getOperand(0);
7688   SDValue SaveSP = Op.getOperand(1);
7689 
7690   // Load the old link SP.
7691   SDValue LoadLinkSP =
7692       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7693 
7694   // Restore the stack pointer.
7695   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7696 
7697   // Store the old link SP.
7698   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7699 }
7700 
7701 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7702   MachineFunction &MF = DAG.getMachineFunction();
7703   bool isPPC64 = Subtarget.isPPC64();
7704   EVT PtrVT = getPointerTy(MF.getDataLayout());
7705 
7706   // Get current frame pointer save index.  The users of this index will be
7707   // primarily DYNALLOC instructions.
7708   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7709   int RASI = FI->getReturnAddrSaveIndex();
7710 
7711   // If the frame pointer save index hasn't been defined yet.
7712   if (!RASI) {
7713     // Find out what the fix offset of the frame pointer save area.
7714     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7715     // Allocate the frame index for frame pointer save area.
7716     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7717     // Save the result.
7718     FI->setReturnAddrSaveIndex(RASI);
7719   }
7720   return DAG.getFrameIndex(RASI, PtrVT);
7721 }
7722 
7723 SDValue
7724 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7725   MachineFunction &MF = DAG.getMachineFunction();
7726   bool isPPC64 = Subtarget.isPPC64();
7727   EVT PtrVT = getPointerTy(MF.getDataLayout());
7728 
7729   // Get current frame pointer save index.  The users of this index will be
7730   // primarily DYNALLOC instructions.
7731   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7732   int FPSI = FI->getFramePointerSaveIndex();
7733 
7734   // If the frame pointer save index hasn't been defined yet.
7735   if (!FPSI) {
7736     // Find out what the fix offset of the frame pointer save area.
7737     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7738     // Allocate the frame index for frame pointer save area.
7739     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7740     // Save the result.
7741     FI->setFramePointerSaveIndex(FPSI);
7742   }
7743   return DAG.getFrameIndex(FPSI, PtrVT);
7744 }
7745 
7746 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7747                                                    SelectionDAG &DAG) const {
7748   // Get the inputs.
7749   SDValue Chain = Op.getOperand(0);
7750   SDValue Size  = Op.getOperand(1);
7751   SDLoc dl(Op);
7752 
7753   // Get the correct type for pointers.
7754   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7755   // Negate the size.
7756   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7757                                 DAG.getConstant(0, dl, PtrVT), Size);
7758   // Construct a node for the frame pointer save index.
7759   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7760   // Build a DYNALLOC node.
7761   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7762   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7763   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7764 }
7765 
7766 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7767                                                      SelectionDAG &DAG) const {
7768   MachineFunction &MF = DAG.getMachineFunction();
7769 
7770   bool isPPC64 = Subtarget.isPPC64();
7771   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7772 
7773   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7774   return DAG.getFrameIndex(FI, PtrVT);
7775 }
7776 
7777 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7778                                                SelectionDAG &DAG) const {
7779   SDLoc DL(Op);
7780   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7781                      DAG.getVTList(MVT::i32, MVT::Other),
7782                      Op.getOperand(0), Op.getOperand(1));
7783 }
7784 
7785 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7786                                                 SelectionDAG &DAG) const {
7787   SDLoc DL(Op);
7788   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7789                      Op.getOperand(0), Op.getOperand(1));
7790 }
7791 
7792 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7793   if (Op.getValueType().isVector())
7794     return LowerVectorLoad(Op, DAG);
7795 
7796   assert(Op.getValueType() == MVT::i1 &&
7797          "Custom lowering only for i1 loads");
7798 
7799   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7800 
7801   SDLoc dl(Op);
7802   LoadSDNode *LD = cast<LoadSDNode>(Op);
7803 
7804   SDValue Chain = LD->getChain();
7805   SDValue BasePtr = LD->getBasePtr();
7806   MachineMemOperand *MMO = LD->getMemOperand();
7807 
7808   SDValue NewLD =
7809       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7810                      BasePtr, MVT::i8, MMO);
7811   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7812 
7813   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7814   return DAG.getMergeValues(Ops, dl);
7815 }
7816 
7817 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7818   if (Op.getOperand(1).getValueType().isVector())
7819     return LowerVectorStore(Op, DAG);
7820 
7821   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7822          "Custom lowering only for i1 stores");
7823 
7824   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7825 
7826   SDLoc dl(Op);
7827   StoreSDNode *ST = cast<StoreSDNode>(Op);
7828 
7829   SDValue Chain = ST->getChain();
7830   SDValue BasePtr = ST->getBasePtr();
7831   SDValue Value = ST->getValue();
7832   MachineMemOperand *MMO = ST->getMemOperand();
7833 
7834   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7835                       Value);
7836   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7837 }
7838 
7839 // FIXME: Remove this once the ANDI glue bug is fixed:
7840 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7841   assert(Op.getValueType() == MVT::i1 &&
7842          "Custom lowering only for i1 results");
7843 
7844   SDLoc DL(Op);
7845   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7846 }
7847 
7848 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7849                                                SelectionDAG &DAG) const {
7850 
7851   // Implements a vector truncate that fits in a vector register as a shuffle.
7852   // We want to legalize vector truncates down to where the source fits in
7853   // a vector register (and target is therefore smaller than vector register
7854   // size).  At that point legalization will try to custom lower the sub-legal
7855   // result and get here - where we can contain the truncate as a single target
7856   // operation.
7857 
7858   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7859   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7860   //
7861   // We will implement it for big-endian ordering as this (where x denotes
7862   // undefined):
7863   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7864   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7865   //
7866   // The same operation in little-endian ordering will be:
7867   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7868   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7869 
7870   assert(Op.getValueType().isVector() && "Vector type expected.");
7871 
7872   SDLoc DL(Op);
7873   SDValue N1 = Op.getOperand(0);
7874   unsigned SrcSize = N1.getValueType().getSizeInBits();
7875   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7876   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7877 
7878   EVT TrgVT = Op.getValueType();
7879   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7880   EVT EltVT = TrgVT.getVectorElementType();
7881   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7882   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7883 
7884   // First list the elements we want to keep.
7885   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7886   SmallVector<int, 16> ShuffV;
7887   if (Subtarget.isLittleEndian())
7888     for (unsigned i = 0; i < TrgNumElts; ++i)
7889       ShuffV.push_back(i * SizeMult);
7890   else
7891     for (unsigned i = 1; i <= TrgNumElts; ++i)
7892       ShuffV.push_back(i * SizeMult - 1);
7893 
7894   // Populate the remaining elements with undefs.
7895   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7896     // ShuffV.push_back(i + WideNumElts);
7897     ShuffV.push_back(WideNumElts + 1);
7898 
7899   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7900   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7901 }
7902 
7903 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7904 /// possible.
7905 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7906   // Not FP? Not a fsel.
7907   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7908       !Op.getOperand(2).getValueType().isFloatingPoint())
7909     return Op;
7910 
7911   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7912 
7913   EVT ResVT = Op.getValueType();
7914   EVT CmpVT = Op.getOperand(0).getValueType();
7915   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7916   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7917   SDLoc dl(Op);
7918 
7919   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7920   // presence of infinities.
7921   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7922     switch (CC) {
7923     default:
7924       break;
7925     case ISD::SETOGT:
7926     case ISD::SETGT:
7927       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7928     case ISD::SETOLT:
7929     case ISD::SETLT:
7930       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7931     }
7932   }
7933 
7934   // We might be able to do better than this under some circumstances, but in
7935   // general, fsel-based lowering of select is a finite-math-only optimization.
7936   // For more information, see section F.3 of the 2.06 ISA specification.
7937   // With ISA 3.0
7938   if (!DAG.getTarget().Options.NoInfsFPMath ||
7939       !DAG.getTarget().Options.NoNaNsFPMath)
7940     return Op;
7941 
7942   // TODO: Propagate flags from the select rather than global settings.
7943   SDNodeFlags Flags;
7944   Flags.setNoInfs(true);
7945   Flags.setNoNaNs(true);
7946 
7947   // If the RHS of the comparison is a 0.0, we don't need to do the
7948   // subtraction at all.
7949   SDValue Sel1;
7950   if (isFloatingPointZero(RHS))
7951     switch (CC) {
7952     default: break;       // SETUO etc aren't handled by fsel.
7953     case ISD::SETNE:
7954       std::swap(TV, FV);
7955       LLVM_FALLTHROUGH;
7956     case ISD::SETEQ:
7957       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7958         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7959       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7960       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7961         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7962       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7963                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7964     case ISD::SETULT:
7965     case ISD::SETLT:
7966       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7967       LLVM_FALLTHROUGH;
7968     case ISD::SETOGE:
7969     case ISD::SETGE:
7970       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7971         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7972       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7973     case ISD::SETUGT:
7974     case ISD::SETGT:
7975       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7976       LLVM_FALLTHROUGH;
7977     case ISD::SETOLE:
7978     case ISD::SETLE:
7979       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7980         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7981       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7982                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7983     }
7984 
7985   SDValue Cmp;
7986   switch (CC) {
7987   default: break;       // SETUO etc aren't handled by fsel.
7988   case ISD::SETNE:
7989     std::swap(TV, FV);
7990     LLVM_FALLTHROUGH;
7991   case ISD::SETEQ:
7992     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7993     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7994       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7995     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7996     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7997       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7998     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7999                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8000   case ISD::SETULT:
8001   case ISD::SETLT:
8002     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8003     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8004       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8005     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8006   case ISD::SETOGE:
8007   case ISD::SETGE:
8008     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8009     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8010       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8011     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8012   case ISD::SETUGT:
8013   case ISD::SETGT:
8014     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8015     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8016       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8017     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8018   case ISD::SETOLE:
8019   case ISD::SETLE:
8020     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8021     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8022       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8023     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8024   }
8025   return Op;
8026 }
8027 
8028 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8029                                                SelectionDAG &DAG,
8030                                                const SDLoc &dl) const {
8031   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8032   SDValue Src = Op.getOperand(0);
8033   if (Src.getValueType() == MVT::f32)
8034     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8035 
8036   SDValue Tmp;
8037   switch (Op.getSimpleValueType().SimpleTy) {
8038   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8039   case MVT::i32:
8040     Tmp = DAG.getNode(
8041         Op.getOpcode() == ISD::FP_TO_SINT
8042             ? PPCISD::FCTIWZ
8043             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8044         dl, MVT::f64, Src);
8045     break;
8046   case MVT::i64:
8047     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8048            "i64 FP_TO_UINT is supported only with FPCVT");
8049     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8050                                                         PPCISD::FCTIDUZ,
8051                       dl, MVT::f64, Src);
8052     break;
8053   }
8054 
8055   // Convert the FP value to an int value through memory.
8056   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8057     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8058   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8059   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8060   MachinePointerInfo MPI =
8061       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8062 
8063   // Emit a store to the stack slot.
8064   SDValue Chain;
8065   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8066   if (i32Stack) {
8067     MachineFunction &MF = DAG.getMachineFunction();
8068     Alignment = Align(4);
8069     MachineMemOperand *MMO =
8070         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8071     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8072     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8073               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8074   } else
8075     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8076 
8077   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8078   // add in a bias on big endian.
8079   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8080     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8081                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8082     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8083   }
8084 
8085   RLI.Chain = Chain;
8086   RLI.Ptr = FIPtr;
8087   RLI.MPI = MPI;
8088   RLI.Alignment = Alignment;
8089 }
8090 
8091 /// Custom lowers floating point to integer conversions to use
8092 /// the direct move instructions available in ISA 2.07 to avoid the
8093 /// need for load/store combinations.
8094 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8095                                                     SelectionDAG &DAG,
8096                                                     const SDLoc &dl) const {
8097   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8098   SDValue Src = Op.getOperand(0);
8099 
8100   if (Src.getValueType() == MVT::f32)
8101     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8102 
8103   SDValue Tmp;
8104   switch (Op.getSimpleValueType().SimpleTy) {
8105   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8106   case MVT::i32:
8107     Tmp = DAG.getNode(
8108         Op.getOpcode() == ISD::FP_TO_SINT
8109             ? PPCISD::FCTIWZ
8110             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8111         dl, MVT::f64, Src);
8112     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8113     break;
8114   case MVT::i64:
8115     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8116            "i64 FP_TO_UINT is supported only with FPCVT");
8117     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8118                                                         PPCISD::FCTIDUZ,
8119                       dl, MVT::f64, Src);
8120     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8121     break;
8122   }
8123   return Tmp;
8124 }
8125 
8126 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8127                                           const SDLoc &dl) const {
8128 
8129   // FP to INT conversions are legal for f128.
8130   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8131     return Op;
8132 
8133   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8134   // PPC (the libcall is not available).
8135   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8136     if (Op.getValueType() == MVT::i32) {
8137       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8138         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8139                                  MVT::f64, Op.getOperand(0),
8140                                  DAG.getIntPtrConstant(0, dl));
8141         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8142                                  MVT::f64, Op.getOperand(0),
8143                                  DAG.getIntPtrConstant(1, dl));
8144 
8145         // Add the two halves of the long double in round-to-zero mode.
8146         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8147 
8148         // Now use a smaller FP_TO_SINT.
8149         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8150       }
8151       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8152         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8153         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8154         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8155         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8156         // FIXME: generated code sucks.
8157         // TODO: Are there fast-math-flags to propagate to this FSUB?
8158         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8159                                    Op.getOperand(0), Tmp);
8160         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8161         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8162                            DAG.getConstant(0x80000000, dl, MVT::i32));
8163         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8164                                     Op.getOperand(0));
8165         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8166                                ISD::SETGE);
8167       }
8168     }
8169 
8170     return SDValue();
8171   }
8172 
8173   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8174     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8175 
8176   ReuseLoadInfo RLI;
8177   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8178 
8179   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8180                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8181 }
8182 
8183 // We're trying to insert a regular store, S, and then a load, L. If the
8184 // incoming value, O, is a load, we might just be able to have our load use the
8185 // address used by O. However, we don't know if anything else will store to
8186 // that address before we can load from it. To prevent this situation, we need
8187 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8188 // the same chain operand as O, we create a token factor from the chain results
8189 // of O and L, and we replace all uses of O's chain result with that token
8190 // factor (see spliceIntoChain below for this last part).
8191 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8192                                             ReuseLoadInfo &RLI,
8193                                             SelectionDAG &DAG,
8194                                             ISD::LoadExtType ET) const {
8195   SDLoc dl(Op);
8196   if (ET == ISD::NON_EXTLOAD &&
8197       (Op.getOpcode() == ISD::FP_TO_UINT ||
8198        Op.getOpcode() == ISD::FP_TO_SINT) &&
8199       isOperationLegalOrCustom(Op.getOpcode(),
8200                                Op.getOperand(0).getValueType())) {
8201 
8202     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8203     return true;
8204   }
8205 
8206   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8207   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8208       LD->isNonTemporal())
8209     return false;
8210   if (LD->getMemoryVT() != MemVT)
8211     return false;
8212 
8213   RLI.Ptr = LD->getBasePtr();
8214   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8215     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8216            "Non-pre-inc AM on PPC?");
8217     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8218                           LD->getOffset());
8219   }
8220 
8221   RLI.Chain = LD->getChain();
8222   RLI.MPI = LD->getPointerInfo();
8223   RLI.IsDereferenceable = LD->isDereferenceable();
8224   RLI.IsInvariant = LD->isInvariant();
8225   RLI.Alignment = LD->getAlign();
8226   RLI.AAInfo = LD->getAAInfo();
8227   RLI.Ranges = LD->getRanges();
8228 
8229   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8230   return true;
8231 }
8232 
8233 // Given the head of the old chain, ResChain, insert a token factor containing
8234 // it and NewResChain, and make users of ResChain now be users of that token
8235 // factor.
8236 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8237 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8238                                         SDValue NewResChain,
8239                                         SelectionDAG &DAG) const {
8240   if (!ResChain)
8241     return;
8242 
8243   SDLoc dl(NewResChain);
8244 
8245   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8246                            NewResChain, DAG.getUNDEF(MVT::Other));
8247   assert(TF.getNode() != NewResChain.getNode() &&
8248          "A new TF really is required here");
8249 
8250   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8251   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8252 }
8253 
8254 /// Analyze profitability of direct move
8255 /// prefer float load to int load plus direct move
8256 /// when there is no integer use of int load
8257 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8258   SDNode *Origin = Op.getOperand(0).getNode();
8259   if (Origin->getOpcode() != ISD::LOAD)
8260     return true;
8261 
8262   // If there is no LXSIBZX/LXSIHZX, like Power8,
8263   // prefer direct move if the memory size is 1 or 2 bytes.
8264   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8265   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8266     return true;
8267 
8268   for (SDNode::use_iterator UI = Origin->use_begin(),
8269                             UE = Origin->use_end();
8270        UI != UE; ++UI) {
8271 
8272     // Only look at the users of the loaded value.
8273     if (UI.getUse().get().getResNo() != 0)
8274       continue;
8275 
8276     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8277         UI->getOpcode() != ISD::UINT_TO_FP)
8278       return true;
8279   }
8280 
8281   return false;
8282 }
8283 
8284 /// Custom lowers integer to floating point conversions to use
8285 /// the direct move instructions available in ISA 2.07 to avoid the
8286 /// need for load/store combinations.
8287 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8288                                                     SelectionDAG &DAG,
8289                                                     const SDLoc &dl) const {
8290   assert((Op.getValueType() == MVT::f32 ||
8291           Op.getValueType() == MVT::f64) &&
8292          "Invalid floating point type as target of conversion");
8293   assert(Subtarget.hasFPCVT() &&
8294          "Int to FP conversions with direct moves require FPCVT");
8295   SDValue FP;
8296   SDValue Src = Op.getOperand(0);
8297   bool SinglePrec = Op.getValueType() == MVT::f32;
8298   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8299   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8300   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8301                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8302 
8303   if (WordInt) {
8304     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8305                      dl, MVT::f64, Src);
8306     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8307   }
8308   else {
8309     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8310     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8311   }
8312 
8313   return FP;
8314 }
8315 
8316 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8317 
8318   EVT VecVT = Vec.getValueType();
8319   assert(VecVT.isVector() && "Expected a vector type.");
8320   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8321 
8322   EVT EltVT = VecVT.getVectorElementType();
8323   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8324   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8325 
8326   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8327   SmallVector<SDValue, 16> Ops(NumConcat);
8328   Ops[0] = Vec;
8329   SDValue UndefVec = DAG.getUNDEF(VecVT);
8330   for (unsigned i = 1; i < NumConcat; ++i)
8331     Ops[i] = UndefVec;
8332 
8333   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8334 }
8335 
8336 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8337                                                 const SDLoc &dl) const {
8338 
8339   unsigned Opc = Op.getOpcode();
8340   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8341          "Unexpected conversion type");
8342   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8343          "Supports conversions to v2f64/v4f32 only.");
8344 
8345   bool SignedConv = Opc == ISD::SINT_TO_FP;
8346   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8347 
8348   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8349   EVT WideVT = Wide.getValueType();
8350   unsigned WideNumElts = WideVT.getVectorNumElements();
8351   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8352 
8353   SmallVector<int, 16> ShuffV;
8354   for (unsigned i = 0; i < WideNumElts; ++i)
8355     ShuffV.push_back(i + WideNumElts);
8356 
8357   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8358   int SaveElts = FourEltRes ? 4 : 2;
8359   if (Subtarget.isLittleEndian())
8360     for (int i = 0; i < SaveElts; i++)
8361       ShuffV[i * Stride] = i;
8362   else
8363     for (int i = 1; i <= SaveElts; i++)
8364       ShuffV[i * Stride - 1] = i - 1;
8365 
8366   SDValue ShuffleSrc2 =
8367       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8368   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8369 
8370   SDValue Extend;
8371   if (SignedConv) {
8372     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8373     EVT ExtVT = Op.getOperand(0).getValueType();
8374     if (Subtarget.hasP9Altivec())
8375       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8376                                IntermediateVT.getVectorNumElements());
8377 
8378     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8379                          DAG.getValueType(ExtVT));
8380   } else
8381     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8382 
8383   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8384 }
8385 
8386 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8387                                           SelectionDAG &DAG) const {
8388   SDLoc dl(Op);
8389 
8390   EVT InVT = Op.getOperand(0).getValueType();
8391   EVT OutVT = Op.getValueType();
8392   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8393       isOperationCustom(Op.getOpcode(), InVT))
8394     return LowerINT_TO_FPVector(Op, DAG, dl);
8395 
8396   // Conversions to f128 are legal.
8397   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8398     return Op;
8399 
8400   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8401     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8402       return SDValue();
8403 
8404     SDValue Value = Op.getOperand(0);
8405     // The values are now known to be -1 (false) or 1 (true). To convert this
8406     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8407     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8408     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8409 
8410     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8411 
8412     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8413 
8414     if (Op.getValueType() != MVT::v4f64)
8415       Value = DAG.getNode(ISD::FP_ROUND, dl,
8416                           Op.getValueType(), Value,
8417                           DAG.getIntPtrConstant(1, dl));
8418     return Value;
8419   }
8420 
8421   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8422   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8423     return SDValue();
8424 
8425   if (Op.getOperand(0).getValueType() == MVT::i1)
8426     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8427                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8428                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8429 
8430   // If we have direct moves, we can do all the conversion, skip the store/load
8431   // however, without FPCVT we can't do most conversions.
8432   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8433       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8434     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8435 
8436   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8437          "UINT_TO_FP is supported only with FPCVT");
8438 
8439   // If we have FCFIDS, then use it when converting to single-precision.
8440   // Otherwise, convert to double-precision and then round.
8441   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8442                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8443                                                             : PPCISD::FCFIDS)
8444                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8445                                                             : PPCISD::FCFID);
8446   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8447                   ? MVT::f32
8448                   : MVT::f64;
8449 
8450   if (Op.getOperand(0).getValueType() == MVT::i64) {
8451     SDValue SINT = Op.getOperand(0);
8452     // When converting to single-precision, we actually need to convert
8453     // to double-precision first and then round to single-precision.
8454     // To avoid double-rounding effects during that operation, we have
8455     // to prepare the input operand.  Bits that might be truncated when
8456     // converting to double-precision are replaced by a bit that won't
8457     // be lost at this stage, but is below the single-precision rounding
8458     // position.
8459     //
8460     // However, if -enable-unsafe-fp-math is in effect, accept double
8461     // rounding to avoid the extra overhead.
8462     if (Op.getValueType() == MVT::f32 &&
8463         !Subtarget.hasFPCVT() &&
8464         !DAG.getTarget().Options.UnsafeFPMath) {
8465 
8466       // Twiddle input to make sure the low 11 bits are zero.  (If this
8467       // is the case, we are guaranteed the value will fit into the 53 bit
8468       // mantissa of an IEEE double-precision value without rounding.)
8469       // If any of those low 11 bits were not zero originally, make sure
8470       // bit 12 (value 2048) is set instead, so that the final rounding
8471       // to single-precision gets the correct result.
8472       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8473                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8474       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8475                           Round, DAG.getConstant(2047, dl, MVT::i64));
8476       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8477       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8478                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8479 
8480       // However, we cannot use that value unconditionally: if the magnitude
8481       // of the input value is small, the bit-twiddling we did above might
8482       // end up visibly changing the output.  Fortunately, in that case, we
8483       // don't need to twiddle bits since the original input will convert
8484       // exactly to double-precision floating-point already.  Therefore,
8485       // construct a conditional to use the original value if the top 11
8486       // bits are all sign-bit copies, and use the rounded value computed
8487       // above otherwise.
8488       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8489                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8490       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8491                          Cond, DAG.getConstant(1, dl, MVT::i64));
8492       Cond = DAG.getSetCC(
8493           dl,
8494           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8495           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8496 
8497       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8498     }
8499 
8500     ReuseLoadInfo RLI;
8501     SDValue Bits;
8502 
8503     MachineFunction &MF = DAG.getMachineFunction();
8504     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8505       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8506                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8507       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8508     } else if (Subtarget.hasLFIWAX() &&
8509                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8510       MachineMemOperand *MMO =
8511         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8512                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8513       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8514       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8515                                      DAG.getVTList(MVT::f64, MVT::Other),
8516                                      Ops, MVT::i32, MMO);
8517       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8518     } else if (Subtarget.hasFPCVT() &&
8519                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8520       MachineMemOperand *MMO =
8521         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8522                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8523       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8524       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8525                                      DAG.getVTList(MVT::f64, MVT::Other),
8526                                      Ops, MVT::i32, MMO);
8527       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8528     } else if (((Subtarget.hasLFIWAX() &&
8529                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8530                 (Subtarget.hasFPCVT() &&
8531                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8532                SINT.getOperand(0).getValueType() == MVT::i32) {
8533       MachineFrameInfo &MFI = MF.getFrameInfo();
8534       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8535 
8536       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8537       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8538 
8539       SDValue Store =
8540           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8541                        MachinePointerInfo::getFixedStack(
8542                            DAG.getMachineFunction(), FrameIdx));
8543 
8544       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8545              "Expected an i32 store");
8546 
8547       RLI.Ptr = FIdx;
8548       RLI.Chain = Store;
8549       RLI.MPI =
8550           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8551       RLI.Alignment = Align(4);
8552 
8553       MachineMemOperand *MMO =
8554         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8555                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8556       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8557       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8558                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8559                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8560                                      Ops, MVT::i32, MMO);
8561     } else
8562       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8563 
8564     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8565 
8566     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8567       FP = DAG.getNode(ISD::FP_ROUND, dl,
8568                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8569     return FP;
8570   }
8571 
8572   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8573          "Unhandled INT_TO_FP type in custom expander!");
8574   // Since we only generate this in 64-bit mode, we can take advantage of
8575   // 64-bit registers.  In particular, sign extend the input value into the
8576   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8577   // then lfd it and fcfid it.
8578   MachineFunction &MF = DAG.getMachineFunction();
8579   MachineFrameInfo &MFI = MF.getFrameInfo();
8580   EVT PtrVT = getPointerTy(MF.getDataLayout());
8581 
8582   SDValue Ld;
8583   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8584     ReuseLoadInfo RLI;
8585     bool ReusingLoad;
8586     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8587                                             DAG))) {
8588       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8589       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8590 
8591       SDValue Store =
8592           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8593                        MachinePointerInfo::getFixedStack(
8594                            DAG.getMachineFunction(), FrameIdx));
8595 
8596       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8597              "Expected an i32 store");
8598 
8599       RLI.Ptr = FIdx;
8600       RLI.Chain = Store;
8601       RLI.MPI =
8602           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8603       RLI.Alignment = Align(4);
8604     }
8605 
8606     MachineMemOperand *MMO =
8607       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8608                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8609     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8610     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8611                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8612                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8613                                  Ops, MVT::i32, MMO);
8614     if (ReusingLoad)
8615       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8616   } else {
8617     assert(Subtarget.isPPC64() &&
8618            "i32->FP without LFIWAX supported only on PPC64");
8619 
8620     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8621     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8622 
8623     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8624                                 Op.getOperand(0));
8625 
8626     // STD the extended value into the stack slot.
8627     SDValue Store = DAG.getStore(
8628         DAG.getEntryNode(), dl, Ext64, FIdx,
8629         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8630 
8631     // Load the value as a double.
8632     Ld = DAG.getLoad(
8633         MVT::f64, dl, Store, FIdx,
8634         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8635   }
8636 
8637   // FCFID it and return it.
8638   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8639   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8640     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8641                      DAG.getIntPtrConstant(0, dl));
8642   return FP;
8643 }
8644 
8645 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8646                                             SelectionDAG &DAG) const {
8647   SDLoc dl(Op);
8648   /*
8649    The rounding mode is in bits 30:31 of FPSR, and has the following
8650    settings:
8651      00 Round to nearest
8652      01 Round to 0
8653      10 Round to +inf
8654      11 Round to -inf
8655 
8656   FLT_ROUNDS, on the other hand, expects the following:
8657     -1 Undefined
8658      0 Round to 0
8659      1 Round to nearest
8660      2 Round to +inf
8661      3 Round to -inf
8662 
8663   To perform the conversion, we do:
8664     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8665   */
8666 
8667   MachineFunction &MF = DAG.getMachineFunction();
8668   EVT VT = Op.getValueType();
8669   EVT PtrVT = getPointerTy(MF.getDataLayout());
8670 
8671   // Save FP Control Word to register
8672   SDValue Chain = Op.getOperand(0);
8673   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8674   Chain = MFFS.getValue(1);
8675 
8676   // Save FP register to stack slot
8677   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8678   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8679   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8680 
8681   // Load FP Control Word from low 32 bits of stack slot.
8682   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8683   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8684   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8685   Chain = CWD.getValue(1);
8686 
8687   // Transform as necessary
8688   SDValue CWD1 =
8689     DAG.getNode(ISD::AND, dl, MVT::i32,
8690                 CWD, DAG.getConstant(3, dl, MVT::i32));
8691   SDValue CWD2 =
8692     DAG.getNode(ISD::SRL, dl, MVT::i32,
8693                 DAG.getNode(ISD::AND, dl, MVT::i32,
8694                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8695                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8696                             DAG.getConstant(3, dl, MVT::i32)),
8697                 DAG.getConstant(1, dl, MVT::i32));
8698 
8699   SDValue RetVal =
8700     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8701 
8702   RetVal =
8703       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8704                   dl, VT, RetVal);
8705 
8706   return DAG.getMergeValues({RetVal, Chain}, dl);
8707 }
8708 
8709 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8710   EVT VT = Op.getValueType();
8711   unsigned BitWidth = VT.getSizeInBits();
8712   SDLoc dl(Op);
8713   assert(Op.getNumOperands() == 3 &&
8714          VT == Op.getOperand(1).getValueType() &&
8715          "Unexpected SHL!");
8716 
8717   // Expand into a bunch of logical ops.  Note that these ops
8718   // depend on the PPC behavior for oversized shift amounts.
8719   SDValue Lo = Op.getOperand(0);
8720   SDValue Hi = Op.getOperand(1);
8721   SDValue Amt = Op.getOperand(2);
8722   EVT AmtVT = Amt.getValueType();
8723 
8724   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8725                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8726   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8727   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8728   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8729   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8730                              DAG.getConstant(-BitWidth, dl, AmtVT));
8731   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8732   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8733   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8734   SDValue OutOps[] = { OutLo, OutHi };
8735   return DAG.getMergeValues(OutOps, dl);
8736 }
8737 
8738 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8739   EVT VT = Op.getValueType();
8740   SDLoc dl(Op);
8741   unsigned BitWidth = VT.getSizeInBits();
8742   assert(Op.getNumOperands() == 3 &&
8743          VT == Op.getOperand(1).getValueType() &&
8744          "Unexpected SRL!");
8745 
8746   // Expand into a bunch of logical ops.  Note that these ops
8747   // depend on the PPC behavior for oversized shift amounts.
8748   SDValue Lo = Op.getOperand(0);
8749   SDValue Hi = Op.getOperand(1);
8750   SDValue Amt = Op.getOperand(2);
8751   EVT AmtVT = Amt.getValueType();
8752 
8753   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8754                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8755   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8756   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8757   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8758   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8759                              DAG.getConstant(-BitWidth, dl, AmtVT));
8760   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8761   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8762   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8763   SDValue OutOps[] = { OutLo, OutHi };
8764   return DAG.getMergeValues(OutOps, dl);
8765 }
8766 
8767 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8768   SDLoc dl(Op);
8769   EVT VT = Op.getValueType();
8770   unsigned BitWidth = VT.getSizeInBits();
8771   assert(Op.getNumOperands() == 3 &&
8772          VT == Op.getOperand(1).getValueType() &&
8773          "Unexpected SRA!");
8774 
8775   // Expand into a bunch of logical ops, followed by a select_cc.
8776   SDValue Lo = Op.getOperand(0);
8777   SDValue Hi = Op.getOperand(1);
8778   SDValue Amt = Op.getOperand(2);
8779   EVT AmtVT = Amt.getValueType();
8780 
8781   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8782                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8783   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8784   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8785   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8786   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8787                              DAG.getConstant(-BitWidth, dl, AmtVT));
8788   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8789   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8790   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8791                                   Tmp4, Tmp6, ISD::SETLE);
8792   SDValue OutOps[] = { OutLo, OutHi };
8793   return DAG.getMergeValues(OutOps, dl);
8794 }
8795 
8796 //===----------------------------------------------------------------------===//
8797 // Vector related lowering.
8798 //
8799 
8800 /// BuildSplatI - Build a canonical splati of Val with an element size of
8801 /// SplatSize.  Cast the result to VT.
8802 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8803                            SelectionDAG &DAG, const SDLoc &dl) {
8804   static const MVT VTys[] = { // canonical VT to use for each size.
8805     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8806   };
8807 
8808   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8809 
8810   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8811   if (Val == -1)
8812     SplatSize = 1;
8813 
8814   EVT CanonicalVT = VTys[SplatSize-1];
8815 
8816   // Build a canonical splat for this value.
8817   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8818 }
8819 
8820 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8821 /// specified intrinsic ID.
8822 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8823                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8824   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8825   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8826                      DAG.getConstant(IID, dl, MVT::i32), Op);
8827 }
8828 
8829 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8830 /// specified intrinsic ID.
8831 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8832                                 SelectionDAG &DAG, const SDLoc &dl,
8833                                 EVT DestVT = MVT::Other) {
8834   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8835   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8836                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8837 }
8838 
8839 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8840 /// specified intrinsic ID.
8841 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8842                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8843                                 EVT DestVT = MVT::Other) {
8844   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8845   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8846                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8847 }
8848 
8849 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8850 /// amount.  The result has the specified value type.
8851 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8852                            SelectionDAG &DAG, const SDLoc &dl) {
8853   // Force LHS/RHS to be the right type.
8854   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8855   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8856 
8857   int Ops[16];
8858   for (unsigned i = 0; i != 16; ++i)
8859     Ops[i] = i + Amt;
8860   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8861   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8862 }
8863 
8864 /// Do we have an efficient pattern in a .td file for this node?
8865 ///
8866 /// \param V - pointer to the BuildVectorSDNode being matched
8867 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8868 ///
8869 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8870 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8871 /// the opposite is true (expansion is beneficial) are:
8872 /// - The node builds a vector out of integers that are not 32 or 64-bits
8873 /// - The node builds a vector out of constants
8874 /// - The node is a "load-and-splat"
8875 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8876 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8877                                             bool HasDirectMove,
8878                                             bool HasP8Vector) {
8879   EVT VecVT = V->getValueType(0);
8880   bool RightType = VecVT == MVT::v2f64 ||
8881     (HasP8Vector && VecVT == MVT::v4f32) ||
8882     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8883   if (!RightType)
8884     return false;
8885 
8886   bool IsSplat = true;
8887   bool IsLoad = false;
8888   SDValue Op0 = V->getOperand(0);
8889 
8890   // This function is called in a block that confirms the node is not a constant
8891   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8892   // different constants.
8893   if (V->isConstant())
8894     return false;
8895   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8896     if (V->getOperand(i).isUndef())
8897       return false;
8898     // We want to expand nodes that represent load-and-splat even if the
8899     // loaded value is a floating point truncation or conversion to int.
8900     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8901         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8902          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8903         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8904          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8905         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8906          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8907       IsLoad = true;
8908     // If the operands are different or the input is not a load and has more
8909     // uses than just this BV node, then it isn't a splat.
8910     if (V->getOperand(i) != Op0 ||
8911         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8912       IsSplat = false;
8913   }
8914   return !(IsSplat && IsLoad);
8915 }
8916 
8917 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8918 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8919 
8920   SDLoc dl(Op);
8921   SDValue Op0 = Op->getOperand(0);
8922 
8923   if (!EnableQuadPrecision ||
8924       (Op.getValueType() != MVT::f128 ) ||
8925       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8926       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8927       (Op0.getOperand(1).getValueType() != MVT::i64))
8928     return SDValue();
8929 
8930   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8931                      Op0.getOperand(1));
8932 }
8933 
8934 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8935   const SDValue *InputLoad = &Op;
8936   if (InputLoad->getOpcode() == ISD::BITCAST)
8937     InputLoad = &InputLoad->getOperand(0);
8938   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8939     InputLoad = &InputLoad->getOperand(0);
8940   if (InputLoad->getOpcode() != ISD::LOAD)
8941     return nullptr;
8942   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8943   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8944 }
8945 
8946 // If this is a case we can't handle, return null and let the default
8947 // expansion code take care of it.  If we CAN select this case, and if it
8948 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8949 // this case more efficiently than a constant pool load, lower it to the
8950 // sequence of ops that should be used.
8951 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8952                                              SelectionDAG &DAG) const {
8953   SDLoc dl(Op);
8954   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8955   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8956 
8957   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8958     // We first build an i32 vector, load it into a QPX register,
8959     // then convert it to a floating-point vector and compare it
8960     // to a zero vector to get the boolean result.
8961     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8962     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8963     MachinePointerInfo PtrInfo =
8964         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8965     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8966     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8967 
8968     assert(BVN->getNumOperands() == 4 &&
8969       "BUILD_VECTOR for v4i1 does not have 4 operands");
8970 
8971     bool IsConst = true;
8972     for (unsigned i = 0; i < 4; ++i) {
8973       if (BVN->getOperand(i).isUndef()) continue;
8974       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8975         IsConst = false;
8976         break;
8977       }
8978     }
8979 
8980     if (IsConst) {
8981       Constant *One =
8982         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8983       Constant *NegOne =
8984         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8985 
8986       Constant *CV[4];
8987       for (unsigned i = 0; i < 4; ++i) {
8988         if (BVN->getOperand(i).isUndef())
8989           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8990         else if (isNullConstant(BVN->getOperand(i)))
8991           CV[i] = NegOne;
8992         else
8993           CV[i] = One;
8994       }
8995 
8996       Constant *CP = ConstantVector::get(CV);
8997       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8998                                           16 /* alignment */);
8999 
9000       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9001       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9002       return DAG.getMemIntrinsicNode(
9003           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9004           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9005     }
9006 
9007     SmallVector<SDValue, 4> Stores;
9008     for (unsigned i = 0; i < 4; ++i) {
9009       if (BVN->getOperand(i).isUndef()) continue;
9010 
9011       unsigned Offset = 4*i;
9012       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9013       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9014 
9015       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9016       if (StoreSize > 4) {
9017         Stores.push_back(
9018             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9019                               PtrInfo.getWithOffset(Offset), MVT::i32));
9020       } else {
9021         SDValue StoreValue = BVN->getOperand(i);
9022         if (StoreSize < 4)
9023           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9024 
9025         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9026                                       PtrInfo.getWithOffset(Offset)));
9027       }
9028     }
9029 
9030     SDValue StoreChain;
9031     if (!Stores.empty())
9032       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9033     else
9034       StoreChain = DAG.getEntryNode();
9035 
9036     // Now load from v4i32 into the QPX register; this will extend it to
9037     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9038     // is typed as v4f64 because the QPX register integer states are not
9039     // explicitly represented.
9040 
9041     SDValue Ops[] = {StoreChain,
9042                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9043                      FIdx};
9044     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9045 
9046     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9047       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9048     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9049       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9050       LoadedVect);
9051 
9052     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9053 
9054     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9055   }
9056 
9057   // All other QPX vectors are handled by generic code.
9058   if (Subtarget.hasQPX())
9059     return SDValue();
9060 
9061   // Check if this is a splat of a constant value.
9062   APInt APSplatBits, APSplatUndef;
9063   unsigned SplatBitSize;
9064   bool HasAnyUndefs;
9065   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9066                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9067       SplatBitSize > 32) {
9068 
9069     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9070     // Handle load-and-splat patterns as we have instructions that will do this
9071     // in one go.
9072     if (InputLoad && DAG.isSplatValue(Op, true)) {
9073       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9074 
9075       // We have handling for 4 and 8 byte elements.
9076       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9077 
9078       // Checking for a single use of this load, we have to check for vector
9079       // width (128 bits) / ElementSize uses (since each operand of the
9080       // BUILD_VECTOR is a separate use of the value.
9081       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9082           ((Subtarget.hasVSX() && ElementSize == 64) ||
9083            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9084         SDValue Ops[] = {
9085           LD->getChain(),    // Chain
9086           LD->getBasePtr(),  // Ptr
9087           DAG.getValueType(Op.getValueType()) // VT
9088         };
9089         return
9090           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9091                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9092                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9093       }
9094     }
9095 
9096     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9097     // lowered to VSX instructions under certain conditions.
9098     // Without VSX, there is no pattern more efficient than expanding the node.
9099     if (Subtarget.hasVSX() &&
9100         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9101                                         Subtarget.hasP8Vector()))
9102       return Op;
9103     return SDValue();
9104   }
9105 
9106   unsigned SplatBits = APSplatBits.getZExtValue();
9107   unsigned SplatUndef = APSplatUndef.getZExtValue();
9108   unsigned SplatSize = SplatBitSize / 8;
9109 
9110   // First, handle single instruction cases.
9111 
9112   // All zeros?
9113   if (SplatBits == 0) {
9114     // Canonicalize all zero vectors to be v4i32.
9115     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9116       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9117       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9118     }
9119     return Op;
9120   }
9121 
9122   // We have XXSPLTIB for constant splats one byte wide
9123   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9124   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9125   if (Subtarget.hasP9Vector() && SplatSize == 1)
9126     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9127 
9128   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9129   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9130                     (32-SplatBitSize));
9131   if (SextVal >= -16 && SextVal <= 15)
9132     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9133 
9134   // Two instruction sequences.
9135 
9136   // If this value is in the range [-32,30] and is even, use:
9137   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9138   // If this value is in the range [17,31] and is odd, use:
9139   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9140   // If this value is in the range [-31,-17] and is odd, use:
9141   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9142   // Note the last two are three-instruction sequences.
9143   if (SextVal >= -32 && SextVal <= 31) {
9144     // To avoid having these optimizations undone by constant folding,
9145     // we convert to a pseudo that will be expanded later into one of
9146     // the above forms.
9147     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9148     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9149               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9150     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9151     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9152     if (VT == Op.getValueType())
9153       return RetVal;
9154     else
9155       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9156   }
9157 
9158   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9159   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9160   // for fneg/fabs.
9161   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9162     // Make -1 and vspltisw -1:
9163     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9164 
9165     // Make the VSLW intrinsic, computing 0x8000_0000.
9166     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9167                                    OnesV, DAG, dl);
9168 
9169     // xor by OnesV to invert it.
9170     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9171     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9172   }
9173 
9174   // Check to see if this is a wide variety of vsplti*, binop self cases.
9175   static const signed char SplatCsts[] = {
9176     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9177     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9178   };
9179 
9180   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9181     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9182     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9183     int i = SplatCsts[idx];
9184 
9185     // Figure out what shift amount will be used by altivec if shifted by i in
9186     // this splat size.
9187     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9188 
9189     // vsplti + shl self.
9190     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9191       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9192       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9193         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9194         Intrinsic::ppc_altivec_vslw
9195       };
9196       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9197       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9198     }
9199 
9200     // vsplti + srl self.
9201     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9202       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9203       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9204         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9205         Intrinsic::ppc_altivec_vsrw
9206       };
9207       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9208       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9209     }
9210 
9211     // vsplti + sra self.
9212     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9213       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9214       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9215         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9216         Intrinsic::ppc_altivec_vsraw
9217       };
9218       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9219       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9220     }
9221 
9222     // vsplti + rol self.
9223     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9224                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9225       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9226       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9227         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9228         Intrinsic::ppc_altivec_vrlw
9229       };
9230       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9231       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9232     }
9233 
9234     // t = vsplti c, result = vsldoi t, t, 1
9235     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9236       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9237       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9238       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9239     }
9240     // t = vsplti c, result = vsldoi t, t, 2
9241     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9242       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9243       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9244       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9245     }
9246     // t = vsplti c, result = vsldoi t, t, 3
9247     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9248       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9249       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9250       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9251     }
9252   }
9253 
9254   return SDValue();
9255 }
9256 
9257 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9258 /// the specified operations to build the shuffle.
9259 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9260                                       SDValue RHS, SelectionDAG &DAG,
9261                                       const SDLoc &dl) {
9262   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9263   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9264   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9265 
9266   enum {
9267     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9268     OP_VMRGHW,
9269     OP_VMRGLW,
9270     OP_VSPLTISW0,
9271     OP_VSPLTISW1,
9272     OP_VSPLTISW2,
9273     OP_VSPLTISW3,
9274     OP_VSLDOI4,
9275     OP_VSLDOI8,
9276     OP_VSLDOI12
9277   };
9278 
9279   if (OpNum == OP_COPY) {
9280     if (LHSID == (1*9+2)*9+3) return LHS;
9281     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9282     return RHS;
9283   }
9284 
9285   SDValue OpLHS, OpRHS;
9286   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9287   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9288 
9289   int ShufIdxs[16];
9290   switch (OpNum) {
9291   default: llvm_unreachable("Unknown i32 permute!");
9292   case OP_VMRGHW:
9293     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9294     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9295     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9296     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9297     break;
9298   case OP_VMRGLW:
9299     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9300     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9301     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9302     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9303     break;
9304   case OP_VSPLTISW0:
9305     for (unsigned i = 0; i != 16; ++i)
9306       ShufIdxs[i] = (i&3)+0;
9307     break;
9308   case OP_VSPLTISW1:
9309     for (unsigned i = 0; i != 16; ++i)
9310       ShufIdxs[i] = (i&3)+4;
9311     break;
9312   case OP_VSPLTISW2:
9313     for (unsigned i = 0; i != 16; ++i)
9314       ShufIdxs[i] = (i&3)+8;
9315     break;
9316   case OP_VSPLTISW3:
9317     for (unsigned i = 0; i != 16; ++i)
9318       ShufIdxs[i] = (i&3)+12;
9319     break;
9320   case OP_VSLDOI4:
9321     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9322   case OP_VSLDOI8:
9323     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9324   case OP_VSLDOI12:
9325     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9326   }
9327   EVT VT = OpLHS.getValueType();
9328   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9329   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9330   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9331   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9332 }
9333 
9334 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9335 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9336 /// SDValue.
9337 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9338                                            SelectionDAG &DAG) const {
9339   const unsigned BytesInVector = 16;
9340   bool IsLE = Subtarget.isLittleEndian();
9341   SDLoc dl(N);
9342   SDValue V1 = N->getOperand(0);
9343   SDValue V2 = N->getOperand(1);
9344   unsigned ShiftElts = 0, InsertAtByte = 0;
9345   bool Swap = false;
9346 
9347   // Shifts required to get the byte we want at element 7.
9348   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9349                                    0, 15, 14, 13, 12, 11, 10, 9};
9350   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9351                                 1, 2,  3,  4,  5,  6,  7,  8};
9352 
9353   ArrayRef<int> Mask = N->getMask();
9354   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9355 
9356   // For each mask element, find out if we're just inserting something
9357   // from V2 into V1 or vice versa.
9358   // Possible permutations inserting an element from V2 into V1:
9359   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9360   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9361   //   ...
9362   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9363   // Inserting from V1 into V2 will be similar, except mask range will be
9364   // [16,31].
9365 
9366   bool FoundCandidate = false;
9367   // If both vector operands for the shuffle are the same vector, the mask
9368   // will contain only elements from the first one and the second one will be
9369   // undef.
9370   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9371   // Go through the mask of half-words to find an element that's being moved
9372   // from one vector to the other.
9373   for (unsigned i = 0; i < BytesInVector; ++i) {
9374     unsigned CurrentElement = Mask[i];
9375     // If 2nd operand is undefined, we should only look for element 7 in the
9376     // Mask.
9377     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9378       continue;
9379 
9380     bool OtherElementsInOrder = true;
9381     // Examine the other elements in the Mask to see if they're in original
9382     // order.
9383     for (unsigned j = 0; j < BytesInVector; ++j) {
9384       if (j == i)
9385         continue;
9386       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9387       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9388       // in which we always assume we're always picking from the 1st operand.
9389       int MaskOffset =
9390           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9391       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9392         OtherElementsInOrder = false;
9393         break;
9394       }
9395     }
9396     // If other elements are in original order, we record the number of shifts
9397     // we need to get the element we want into element 7. Also record which byte
9398     // in the vector we should insert into.
9399     if (OtherElementsInOrder) {
9400       // If 2nd operand is undefined, we assume no shifts and no swapping.
9401       if (V2.isUndef()) {
9402         ShiftElts = 0;
9403         Swap = false;
9404       } else {
9405         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9406         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9407                          : BigEndianShifts[CurrentElement & 0xF];
9408         Swap = CurrentElement < BytesInVector;
9409       }
9410       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9411       FoundCandidate = true;
9412       break;
9413     }
9414   }
9415 
9416   if (!FoundCandidate)
9417     return SDValue();
9418 
9419   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9420   // optionally with VECSHL if shift is required.
9421   if (Swap)
9422     std::swap(V1, V2);
9423   if (V2.isUndef())
9424     V2 = V1;
9425   if (ShiftElts) {
9426     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9427                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9428     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9429                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9430   }
9431   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9432                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9433 }
9434 
9435 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9436 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9437 /// SDValue.
9438 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9439                                            SelectionDAG &DAG) const {
9440   const unsigned NumHalfWords = 8;
9441   const unsigned BytesInVector = NumHalfWords * 2;
9442   // Check that the shuffle is on half-words.
9443   if (!isNByteElemShuffleMask(N, 2, 1))
9444     return SDValue();
9445 
9446   bool IsLE = Subtarget.isLittleEndian();
9447   SDLoc dl(N);
9448   SDValue V1 = N->getOperand(0);
9449   SDValue V2 = N->getOperand(1);
9450   unsigned ShiftElts = 0, InsertAtByte = 0;
9451   bool Swap = false;
9452 
9453   // Shifts required to get the half-word we want at element 3.
9454   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9455   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9456 
9457   uint32_t Mask = 0;
9458   uint32_t OriginalOrderLow = 0x1234567;
9459   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9460   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9461   // 32-bit space, only need 4-bit nibbles per element.
9462   for (unsigned i = 0; i < NumHalfWords; ++i) {
9463     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9464     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9465   }
9466 
9467   // For each mask element, find out if we're just inserting something
9468   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9469   // from V2 into V1:
9470   //   X, 1, 2, 3, 4, 5, 6, 7
9471   //   0, X, 2, 3, 4, 5, 6, 7
9472   //   0, 1, X, 3, 4, 5, 6, 7
9473   //   0, 1, 2, X, 4, 5, 6, 7
9474   //   0, 1, 2, 3, X, 5, 6, 7
9475   //   0, 1, 2, 3, 4, X, 6, 7
9476   //   0, 1, 2, 3, 4, 5, X, 7
9477   //   0, 1, 2, 3, 4, 5, 6, X
9478   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9479 
9480   bool FoundCandidate = false;
9481   // Go through the mask of half-words to find an element that's being moved
9482   // from one vector to the other.
9483   for (unsigned i = 0; i < NumHalfWords; ++i) {
9484     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9485     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9486     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9487     uint32_t TargetOrder = 0x0;
9488 
9489     // If both vector operands for the shuffle are the same vector, the mask
9490     // will contain only elements from the first one and the second one will be
9491     // undef.
9492     if (V2.isUndef()) {
9493       ShiftElts = 0;
9494       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9495       TargetOrder = OriginalOrderLow;
9496       Swap = false;
9497       // Skip if not the correct element or mask of other elements don't equal
9498       // to our expected order.
9499       if (MaskOneElt == VINSERTHSrcElem &&
9500           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9501         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9502         FoundCandidate = true;
9503         break;
9504       }
9505     } else { // If both operands are defined.
9506       // Target order is [8,15] if the current mask is between [0,7].
9507       TargetOrder =
9508           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9509       // Skip if mask of other elements don't equal our expected order.
9510       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9511         // We only need the last 3 bits for the number of shifts.
9512         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9513                          : BigEndianShifts[MaskOneElt & 0x7];
9514         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9515         Swap = MaskOneElt < NumHalfWords;
9516         FoundCandidate = true;
9517         break;
9518       }
9519     }
9520   }
9521 
9522   if (!FoundCandidate)
9523     return SDValue();
9524 
9525   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9526   // optionally with VECSHL if shift is required.
9527   if (Swap)
9528     std::swap(V1, V2);
9529   if (V2.isUndef())
9530     V2 = V1;
9531   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9532   if (ShiftElts) {
9533     // Double ShiftElts because we're left shifting on v16i8 type.
9534     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9535                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9536     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9537     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9538                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9539     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9540   }
9541   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9542   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9543                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9544   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9545 }
9546 
9547 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9548 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9549 /// return the code it can be lowered into.  Worst case, it can always be
9550 /// lowered into a vperm.
9551 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9552                                                SelectionDAG &DAG) const {
9553   SDLoc dl(Op);
9554   SDValue V1 = Op.getOperand(0);
9555   SDValue V2 = Op.getOperand(1);
9556   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9557   EVT VT = Op.getValueType();
9558   bool isLittleEndian = Subtarget.isLittleEndian();
9559 
9560   unsigned ShiftElts, InsertAtByte;
9561   bool Swap = false;
9562 
9563   // If this is a load-and-splat, we can do that with a single instruction
9564   // in some cases. However if the load has multiple uses, we don't want to
9565   // combine it because that will just produce multiple loads.
9566   const SDValue *InputLoad = getNormalLoadInput(V1);
9567   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9568       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9569       InputLoad->hasOneUse()) {
9570     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9571     int SplatIdx =
9572       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9573 
9574     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9575     // For 4-byte load-and-splat, we need Power9.
9576     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9577       uint64_t Offset = 0;
9578       if (IsFourByte)
9579         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9580       else
9581         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9582       SDValue BasePtr = LD->getBasePtr();
9583       if (Offset != 0)
9584         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9585                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9586       SDValue Ops[] = {
9587         LD->getChain(),    // Chain
9588         BasePtr,           // BasePtr
9589         DAG.getValueType(Op.getValueType()) // VT
9590       };
9591       SDVTList VTL =
9592         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9593       SDValue LdSplt =
9594         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9595                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9596       if (LdSplt.getValueType() != SVOp->getValueType(0))
9597         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9598       return LdSplt;
9599     }
9600   }
9601   if (Subtarget.hasP9Vector() &&
9602       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9603                            isLittleEndian)) {
9604     if (Swap)
9605       std::swap(V1, V2);
9606     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9607     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9608     if (ShiftElts) {
9609       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9610                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9611       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9612                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9613       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9614     }
9615     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9616                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9617     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9618   }
9619 
9620   if (Subtarget.hasP9Altivec()) {
9621     SDValue NewISDNode;
9622     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9623       return NewISDNode;
9624 
9625     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9626       return NewISDNode;
9627   }
9628 
9629   if (Subtarget.hasVSX() &&
9630       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9631     if (Swap)
9632       std::swap(V1, V2);
9633     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9634     SDValue Conv2 =
9635         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9636 
9637     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9638                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9639     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9640   }
9641 
9642   if (Subtarget.hasVSX() &&
9643     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9644     if (Swap)
9645       std::swap(V1, V2);
9646     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9647     SDValue Conv2 =
9648         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9649 
9650     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9651                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9652     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9653   }
9654 
9655   if (Subtarget.hasP9Vector()) {
9656      if (PPC::isXXBRHShuffleMask(SVOp)) {
9657       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9658       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9659       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9660     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9661       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9662       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9663       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9664     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9665       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9666       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9667       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9668     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9669       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9670       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9671       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9672     }
9673   }
9674 
9675   if (Subtarget.hasVSX()) {
9676     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9677       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9678 
9679       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9680       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9681                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9682       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9683     }
9684 
9685     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9686     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9687       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9688       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9689       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9690     }
9691   }
9692 
9693   if (Subtarget.hasQPX()) {
9694     if (VT.getVectorNumElements() != 4)
9695       return SDValue();
9696 
9697     if (V2.isUndef()) V2 = V1;
9698 
9699     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9700     if (AlignIdx != -1) {
9701       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9702                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9703     } else if (SVOp->isSplat()) {
9704       int SplatIdx = SVOp->getSplatIndex();
9705       if (SplatIdx >= 4) {
9706         std::swap(V1, V2);
9707         SplatIdx -= 4;
9708       }
9709 
9710       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9711                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9712     }
9713 
9714     // Lower this into a qvgpci/qvfperm pair.
9715 
9716     // Compute the qvgpci literal
9717     unsigned idx = 0;
9718     for (unsigned i = 0; i < 4; ++i) {
9719       int m = SVOp->getMaskElt(i);
9720       unsigned mm = m >= 0 ? (unsigned) m : i;
9721       idx |= mm << (3-i)*3;
9722     }
9723 
9724     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9725                              DAG.getConstant(idx, dl, MVT::i32));
9726     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9727   }
9728 
9729   // Cases that are handled by instructions that take permute immediates
9730   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9731   // selected by the instruction selector.
9732   if (V2.isUndef()) {
9733     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9734         PPC::isSplatShuffleMask(SVOp, 2) ||
9735         PPC::isSplatShuffleMask(SVOp, 4) ||
9736         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9737         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9738         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9739         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9740         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9741         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9742         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9743         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9744         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9745         (Subtarget.hasP8Altivec() && (
9746          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9747          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9748          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9749       return Op;
9750     }
9751   }
9752 
9753   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9754   // and produce a fixed permutation.  If any of these match, do not lower to
9755   // VPERM.
9756   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9757   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9758       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9759       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9760       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9761       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9762       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9763       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9764       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9765       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9766       (Subtarget.hasP8Altivec() && (
9767        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9768        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9769        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9770     return Op;
9771 
9772   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9773   // perfect shuffle table to emit an optimal matching sequence.
9774   ArrayRef<int> PermMask = SVOp->getMask();
9775 
9776   unsigned PFIndexes[4];
9777   bool isFourElementShuffle = true;
9778   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9779     unsigned EltNo = 8;   // Start out undef.
9780     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9781       if (PermMask[i*4+j] < 0)
9782         continue;   // Undef, ignore it.
9783 
9784       unsigned ByteSource = PermMask[i*4+j];
9785       if ((ByteSource & 3) != j) {
9786         isFourElementShuffle = false;
9787         break;
9788       }
9789 
9790       if (EltNo == 8) {
9791         EltNo = ByteSource/4;
9792       } else if (EltNo != ByteSource/4) {
9793         isFourElementShuffle = false;
9794         break;
9795       }
9796     }
9797     PFIndexes[i] = EltNo;
9798   }
9799 
9800   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9801   // perfect shuffle vector to determine if it is cost effective to do this as
9802   // discrete instructions, or whether we should use a vperm.
9803   // For now, we skip this for little endian until such time as we have a
9804   // little-endian perfect shuffle table.
9805   if (isFourElementShuffle && !isLittleEndian) {
9806     // Compute the index in the perfect shuffle table.
9807     unsigned PFTableIndex =
9808       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9809 
9810     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9811     unsigned Cost  = (PFEntry >> 30);
9812 
9813     // Determining when to avoid vperm is tricky.  Many things affect the cost
9814     // of vperm, particularly how many times the perm mask needs to be computed.
9815     // For example, if the perm mask can be hoisted out of a loop or is already
9816     // used (perhaps because there are multiple permutes with the same shuffle
9817     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9818     // the loop requires an extra register.
9819     //
9820     // As a compromise, we only emit discrete instructions if the shuffle can be
9821     // generated in 3 or fewer operations.  When we have loop information
9822     // available, if this block is within a loop, we should avoid using vperm
9823     // for 3-operation perms and use a constant pool load instead.
9824     if (Cost < 3)
9825       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9826   }
9827 
9828   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9829   // vector that will get spilled to the constant pool.
9830   if (V2.isUndef()) V2 = V1;
9831 
9832   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9833   // that it is in input element units, not in bytes.  Convert now.
9834 
9835   // For little endian, the order of the input vectors is reversed, and
9836   // the permutation mask is complemented with respect to 31.  This is
9837   // necessary to produce proper semantics with the big-endian-biased vperm
9838   // instruction.
9839   EVT EltVT = V1.getValueType().getVectorElementType();
9840   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9841 
9842   SmallVector<SDValue, 16> ResultMask;
9843   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9844     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9845 
9846     for (unsigned j = 0; j != BytesPerElement; ++j)
9847       if (isLittleEndian)
9848         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9849                                              dl, MVT::i32));
9850       else
9851         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9852                                              MVT::i32));
9853   }
9854 
9855   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9856   if (isLittleEndian)
9857     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9858                        V2, V1, VPermMask);
9859   else
9860     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9861                        V1, V2, VPermMask);
9862 }
9863 
9864 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9865 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9866 /// information about the intrinsic.
9867 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9868                                  bool &isDot, const PPCSubtarget &Subtarget) {
9869   unsigned IntrinsicID =
9870       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9871   CompareOpc = -1;
9872   isDot = false;
9873   switch (IntrinsicID) {
9874   default:
9875     return false;
9876   // Comparison predicates.
9877   case Intrinsic::ppc_altivec_vcmpbfp_p:
9878     CompareOpc = 966;
9879     isDot = true;
9880     break;
9881   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9882     CompareOpc = 198;
9883     isDot = true;
9884     break;
9885   case Intrinsic::ppc_altivec_vcmpequb_p:
9886     CompareOpc = 6;
9887     isDot = true;
9888     break;
9889   case Intrinsic::ppc_altivec_vcmpequh_p:
9890     CompareOpc = 70;
9891     isDot = true;
9892     break;
9893   case Intrinsic::ppc_altivec_vcmpequw_p:
9894     CompareOpc = 134;
9895     isDot = true;
9896     break;
9897   case Intrinsic::ppc_altivec_vcmpequd_p:
9898     if (Subtarget.hasP8Altivec()) {
9899       CompareOpc = 199;
9900       isDot = true;
9901     } else
9902       return false;
9903     break;
9904   case Intrinsic::ppc_altivec_vcmpneb_p:
9905   case Intrinsic::ppc_altivec_vcmpneh_p:
9906   case Intrinsic::ppc_altivec_vcmpnew_p:
9907   case Intrinsic::ppc_altivec_vcmpnezb_p:
9908   case Intrinsic::ppc_altivec_vcmpnezh_p:
9909   case Intrinsic::ppc_altivec_vcmpnezw_p:
9910     if (Subtarget.hasP9Altivec()) {
9911       switch (IntrinsicID) {
9912       default:
9913         llvm_unreachable("Unknown comparison intrinsic.");
9914       case Intrinsic::ppc_altivec_vcmpneb_p:
9915         CompareOpc = 7;
9916         break;
9917       case Intrinsic::ppc_altivec_vcmpneh_p:
9918         CompareOpc = 71;
9919         break;
9920       case Intrinsic::ppc_altivec_vcmpnew_p:
9921         CompareOpc = 135;
9922         break;
9923       case Intrinsic::ppc_altivec_vcmpnezb_p:
9924         CompareOpc = 263;
9925         break;
9926       case Intrinsic::ppc_altivec_vcmpnezh_p:
9927         CompareOpc = 327;
9928         break;
9929       case Intrinsic::ppc_altivec_vcmpnezw_p:
9930         CompareOpc = 391;
9931         break;
9932       }
9933       isDot = true;
9934     } else
9935       return false;
9936     break;
9937   case Intrinsic::ppc_altivec_vcmpgefp_p:
9938     CompareOpc = 454;
9939     isDot = true;
9940     break;
9941   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9942     CompareOpc = 710;
9943     isDot = true;
9944     break;
9945   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9946     CompareOpc = 774;
9947     isDot = true;
9948     break;
9949   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9950     CompareOpc = 838;
9951     isDot = true;
9952     break;
9953   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9954     CompareOpc = 902;
9955     isDot = true;
9956     break;
9957   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9958     if (Subtarget.hasP8Altivec()) {
9959       CompareOpc = 967;
9960       isDot = true;
9961     } else
9962       return false;
9963     break;
9964   case Intrinsic::ppc_altivec_vcmpgtub_p:
9965     CompareOpc = 518;
9966     isDot = true;
9967     break;
9968   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9969     CompareOpc = 582;
9970     isDot = true;
9971     break;
9972   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9973     CompareOpc = 646;
9974     isDot = true;
9975     break;
9976   case Intrinsic::ppc_altivec_vcmpgtud_p:
9977     if (Subtarget.hasP8Altivec()) {
9978       CompareOpc = 711;
9979       isDot = true;
9980     } else
9981       return false;
9982     break;
9983 
9984   // VSX predicate comparisons use the same infrastructure
9985   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9986   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9987   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9988   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9989   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9990   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9991     if (Subtarget.hasVSX()) {
9992       switch (IntrinsicID) {
9993       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9994         CompareOpc = 99;
9995         break;
9996       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9997         CompareOpc = 115;
9998         break;
9999       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10000         CompareOpc = 107;
10001         break;
10002       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10003         CompareOpc = 67;
10004         break;
10005       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10006         CompareOpc = 83;
10007         break;
10008       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10009         CompareOpc = 75;
10010         break;
10011       }
10012       isDot = true;
10013     } else
10014       return false;
10015     break;
10016 
10017   // Normal Comparisons.
10018   case Intrinsic::ppc_altivec_vcmpbfp:
10019     CompareOpc = 966;
10020     break;
10021   case Intrinsic::ppc_altivec_vcmpeqfp:
10022     CompareOpc = 198;
10023     break;
10024   case Intrinsic::ppc_altivec_vcmpequb:
10025     CompareOpc = 6;
10026     break;
10027   case Intrinsic::ppc_altivec_vcmpequh:
10028     CompareOpc = 70;
10029     break;
10030   case Intrinsic::ppc_altivec_vcmpequw:
10031     CompareOpc = 134;
10032     break;
10033   case Intrinsic::ppc_altivec_vcmpequd:
10034     if (Subtarget.hasP8Altivec())
10035       CompareOpc = 199;
10036     else
10037       return false;
10038     break;
10039   case Intrinsic::ppc_altivec_vcmpneb:
10040   case Intrinsic::ppc_altivec_vcmpneh:
10041   case Intrinsic::ppc_altivec_vcmpnew:
10042   case Intrinsic::ppc_altivec_vcmpnezb:
10043   case Intrinsic::ppc_altivec_vcmpnezh:
10044   case Intrinsic::ppc_altivec_vcmpnezw:
10045     if (Subtarget.hasP9Altivec())
10046       switch (IntrinsicID) {
10047       default:
10048         llvm_unreachable("Unknown comparison intrinsic.");
10049       case Intrinsic::ppc_altivec_vcmpneb:
10050         CompareOpc = 7;
10051         break;
10052       case Intrinsic::ppc_altivec_vcmpneh:
10053         CompareOpc = 71;
10054         break;
10055       case Intrinsic::ppc_altivec_vcmpnew:
10056         CompareOpc = 135;
10057         break;
10058       case Intrinsic::ppc_altivec_vcmpnezb:
10059         CompareOpc = 263;
10060         break;
10061       case Intrinsic::ppc_altivec_vcmpnezh:
10062         CompareOpc = 327;
10063         break;
10064       case Intrinsic::ppc_altivec_vcmpnezw:
10065         CompareOpc = 391;
10066         break;
10067       }
10068     else
10069       return false;
10070     break;
10071   case Intrinsic::ppc_altivec_vcmpgefp:
10072     CompareOpc = 454;
10073     break;
10074   case Intrinsic::ppc_altivec_vcmpgtfp:
10075     CompareOpc = 710;
10076     break;
10077   case Intrinsic::ppc_altivec_vcmpgtsb:
10078     CompareOpc = 774;
10079     break;
10080   case Intrinsic::ppc_altivec_vcmpgtsh:
10081     CompareOpc = 838;
10082     break;
10083   case Intrinsic::ppc_altivec_vcmpgtsw:
10084     CompareOpc = 902;
10085     break;
10086   case Intrinsic::ppc_altivec_vcmpgtsd:
10087     if (Subtarget.hasP8Altivec())
10088       CompareOpc = 967;
10089     else
10090       return false;
10091     break;
10092   case Intrinsic::ppc_altivec_vcmpgtub:
10093     CompareOpc = 518;
10094     break;
10095   case Intrinsic::ppc_altivec_vcmpgtuh:
10096     CompareOpc = 582;
10097     break;
10098   case Intrinsic::ppc_altivec_vcmpgtuw:
10099     CompareOpc = 646;
10100     break;
10101   case Intrinsic::ppc_altivec_vcmpgtud:
10102     if (Subtarget.hasP8Altivec())
10103       CompareOpc = 711;
10104     else
10105       return false;
10106     break;
10107   }
10108   return true;
10109 }
10110 
10111 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10112 /// lower, do it, otherwise return null.
10113 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10114                                                    SelectionDAG &DAG) const {
10115   unsigned IntrinsicID =
10116     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10117 
10118   SDLoc dl(Op);
10119 
10120   if (IntrinsicID == Intrinsic::thread_pointer) {
10121     // Reads the thread pointer register, used for __builtin_thread_pointer.
10122     if (Subtarget.isPPC64())
10123       return DAG.getRegister(PPC::X13, MVT::i64);
10124     return DAG.getRegister(PPC::R2, MVT::i32);
10125   }
10126 
10127   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10128   // opcode number of the comparison.
10129   int CompareOpc;
10130   bool isDot;
10131   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10132     return SDValue();    // Don't custom lower most intrinsics.
10133 
10134   // If this is a non-dot comparison, make the VCMP node and we are done.
10135   if (!isDot) {
10136     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10137                               Op.getOperand(1), Op.getOperand(2),
10138                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10139     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10140   }
10141 
10142   // Create the PPCISD altivec 'dot' comparison node.
10143   SDValue Ops[] = {
10144     Op.getOperand(2),  // LHS
10145     Op.getOperand(3),  // RHS
10146     DAG.getConstant(CompareOpc, dl, MVT::i32)
10147   };
10148   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10149   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10150 
10151   // Now that we have the comparison, emit a copy from the CR to a GPR.
10152   // This is flagged to the above dot comparison.
10153   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10154                                 DAG.getRegister(PPC::CR6, MVT::i32),
10155                                 CompNode.getValue(1));
10156 
10157   // Unpack the result based on how the target uses it.
10158   unsigned BitNo;   // Bit # of CR6.
10159   bool InvertBit;   // Invert result?
10160   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10161   default:  // Can't happen, don't crash on invalid number though.
10162   case 0:   // Return the value of the EQ bit of CR6.
10163     BitNo = 0; InvertBit = false;
10164     break;
10165   case 1:   // Return the inverted value of the EQ bit of CR6.
10166     BitNo = 0; InvertBit = true;
10167     break;
10168   case 2:   // Return the value of the LT bit of CR6.
10169     BitNo = 2; InvertBit = false;
10170     break;
10171   case 3:   // Return the inverted value of the LT bit of CR6.
10172     BitNo = 2; InvertBit = true;
10173     break;
10174   }
10175 
10176   // Shift the bit into the low position.
10177   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10178                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10179   // Isolate the bit.
10180   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10181                       DAG.getConstant(1, dl, MVT::i32));
10182 
10183   // If we are supposed to, toggle the bit.
10184   if (InvertBit)
10185     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10186                         DAG.getConstant(1, dl, MVT::i32));
10187   return Flags;
10188 }
10189 
10190 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10191                                                SelectionDAG &DAG) const {
10192   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10193   // the beginning of the argument list.
10194   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10195   SDLoc DL(Op);
10196   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10197   case Intrinsic::ppc_cfence: {
10198     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10199     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10200     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10201                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10202                                                   Op.getOperand(ArgStart + 1)),
10203                                       Op.getOperand(0)),
10204                    0);
10205   }
10206   default:
10207     break;
10208   }
10209   return SDValue();
10210 }
10211 
10212 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10213   // Check for a DIV with the same operands as this REM.
10214   for (auto UI : Op.getOperand(1)->uses()) {
10215     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10216         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10217       if (UI->getOperand(0) == Op.getOperand(0) &&
10218           UI->getOperand(1) == Op.getOperand(1))
10219         return SDValue();
10220   }
10221   return Op;
10222 }
10223 
10224 // Lower scalar BSWAP64 to xxbrd.
10225 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10226   SDLoc dl(Op);
10227   // MTVSRDD
10228   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10229                    Op.getOperand(0));
10230   // XXBRD
10231   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10232   // MFVSRD
10233   int VectorIndex = 0;
10234   if (Subtarget.isLittleEndian())
10235     VectorIndex = 1;
10236   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10237                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10238   return Op;
10239 }
10240 
10241 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10242 // compared to a value that is atomically loaded (atomic loads zero-extend).
10243 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10244                                                 SelectionDAG &DAG) const {
10245   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10246          "Expecting an atomic compare-and-swap here.");
10247   SDLoc dl(Op);
10248   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10249   EVT MemVT = AtomicNode->getMemoryVT();
10250   if (MemVT.getSizeInBits() >= 32)
10251     return Op;
10252 
10253   SDValue CmpOp = Op.getOperand(2);
10254   // If this is already correctly zero-extended, leave it alone.
10255   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10256   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10257     return Op;
10258 
10259   // Clear the high bits of the compare operand.
10260   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10261   SDValue NewCmpOp =
10262     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10263                 DAG.getConstant(MaskVal, dl, MVT::i32));
10264 
10265   // Replace the existing compare operand with the properly zero-extended one.
10266   SmallVector<SDValue, 4> Ops;
10267   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10268     Ops.push_back(AtomicNode->getOperand(i));
10269   Ops[2] = NewCmpOp;
10270   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10271   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10272   auto NodeTy =
10273     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10274   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10275 }
10276 
10277 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10278                                                  SelectionDAG &DAG) const {
10279   SDLoc dl(Op);
10280   // Create a stack slot that is 16-byte aligned.
10281   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10282   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10283   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10284   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10285 
10286   // Store the input value into Value#0 of the stack slot.
10287   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10288                                MachinePointerInfo());
10289   // Load it out.
10290   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10291 }
10292 
10293 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10294                                                   SelectionDAG &DAG) const {
10295   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10296          "Should only be called for ISD::INSERT_VECTOR_ELT");
10297 
10298   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10299   // We have legal lowering for constant indices but not for variable ones.
10300   if (!C)
10301     return SDValue();
10302 
10303   EVT VT = Op.getValueType();
10304   SDLoc dl(Op);
10305   SDValue V1 = Op.getOperand(0);
10306   SDValue V2 = Op.getOperand(1);
10307   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10308   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10309     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10310     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10311     unsigned InsertAtElement = C->getZExtValue();
10312     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10313     if (Subtarget.isLittleEndian()) {
10314       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10315     }
10316     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10317                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10318   }
10319   return Op;
10320 }
10321 
10322 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10323                                                    SelectionDAG &DAG) const {
10324   SDLoc dl(Op);
10325   SDNode *N = Op.getNode();
10326 
10327   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10328          "Unknown extract_vector_elt type");
10329 
10330   SDValue Value = N->getOperand(0);
10331 
10332   // The first part of this is like the store lowering except that we don't
10333   // need to track the chain.
10334 
10335   // The values are now known to be -1 (false) or 1 (true). To convert this
10336   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10337   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10338   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10339 
10340   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10341   // understand how to form the extending load.
10342   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10343 
10344   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10345 
10346   // Now convert to an integer and store.
10347   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10348     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10349     Value);
10350 
10351   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10352   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10353   MachinePointerInfo PtrInfo =
10354       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10355   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10356   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10357 
10358   SDValue StoreChain = DAG.getEntryNode();
10359   SDValue Ops[] = {StoreChain,
10360                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10361                    Value, FIdx};
10362   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10363 
10364   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10365     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10366 
10367   // Extract the value requested.
10368   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10369   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10370   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10371 
10372   SDValue IntVal =
10373       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10374 
10375   if (!Subtarget.useCRBits())
10376     return IntVal;
10377 
10378   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10379 }
10380 
10381 /// Lowering for QPX v4i1 loads
10382 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10383                                            SelectionDAG &DAG) const {
10384   SDLoc dl(Op);
10385   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10386   SDValue LoadChain = LN->getChain();
10387   SDValue BasePtr = LN->getBasePtr();
10388 
10389   if (Op.getValueType() == MVT::v4f64 ||
10390       Op.getValueType() == MVT::v4f32) {
10391     EVT MemVT = LN->getMemoryVT();
10392     unsigned Alignment = LN->getAlignment();
10393 
10394     // If this load is properly aligned, then it is legal.
10395     if (Alignment >= MemVT.getStoreSize())
10396       return Op;
10397 
10398     EVT ScalarVT = Op.getValueType().getScalarType(),
10399         ScalarMemVT = MemVT.getScalarType();
10400     unsigned Stride = ScalarMemVT.getStoreSize();
10401 
10402     SDValue Vals[4], LoadChains[4];
10403     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10404       SDValue Load;
10405       if (ScalarVT != ScalarMemVT)
10406         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10407                               BasePtr,
10408                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10409                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10410                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10411       else
10412         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10413                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10414                            MinAlign(Alignment, Idx * Stride),
10415                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10416 
10417       if (Idx == 0 && LN->isIndexed()) {
10418         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10419                "Unknown addressing mode on vector load");
10420         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10421                                   LN->getAddressingMode());
10422       }
10423 
10424       Vals[Idx] = Load;
10425       LoadChains[Idx] = Load.getValue(1);
10426 
10427       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10428                             DAG.getConstant(Stride, dl,
10429                                             BasePtr.getValueType()));
10430     }
10431 
10432     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10433     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10434 
10435     if (LN->isIndexed()) {
10436       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10437       return DAG.getMergeValues(RetOps, dl);
10438     }
10439 
10440     SDValue RetOps[] = { Value, TF };
10441     return DAG.getMergeValues(RetOps, dl);
10442   }
10443 
10444   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10445   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10446 
10447   // To lower v4i1 from a byte array, we load the byte elements of the
10448   // vector and then reuse the BUILD_VECTOR logic.
10449 
10450   SDValue VectElmts[4], VectElmtChains[4];
10451   for (unsigned i = 0; i < 4; ++i) {
10452     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10453     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10454 
10455     VectElmts[i] = DAG.getExtLoad(
10456         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10457         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10458         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10459     VectElmtChains[i] = VectElmts[i].getValue(1);
10460   }
10461 
10462   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10463   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10464 
10465   SDValue RVals[] = { Value, LoadChain };
10466   return DAG.getMergeValues(RVals, dl);
10467 }
10468 
10469 /// Lowering for QPX v4i1 stores
10470 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10471                                             SelectionDAG &DAG) const {
10472   SDLoc dl(Op);
10473   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10474   SDValue StoreChain = SN->getChain();
10475   SDValue BasePtr = SN->getBasePtr();
10476   SDValue Value = SN->getValue();
10477 
10478   if (Value.getValueType() == MVT::v4f64 ||
10479       Value.getValueType() == MVT::v4f32) {
10480     EVT MemVT = SN->getMemoryVT();
10481     unsigned Alignment = SN->getAlignment();
10482 
10483     // If this store is properly aligned, then it is legal.
10484     if (Alignment >= MemVT.getStoreSize())
10485       return Op;
10486 
10487     EVT ScalarVT = Value.getValueType().getScalarType(),
10488         ScalarMemVT = MemVT.getScalarType();
10489     unsigned Stride = ScalarMemVT.getStoreSize();
10490 
10491     SDValue Stores[4];
10492     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10493       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10494                                DAG.getVectorIdxConstant(Idx, dl));
10495       SDValue Store;
10496       if (ScalarVT != ScalarMemVT)
10497         Store =
10498             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10499                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10500                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10501                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10502       else
10503         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10504                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10505                              MinAlign(Alignment, Idx * Stride),
10506                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10507 
10508       if (Idx == 0 && SN->isIndexed()) {
10509         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10510                "Unknown addressing mode on vector store");
10511         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10512                                     SN->getAddressingMode());
10513       }
10514 
10515       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10516                             DAG.getConstant(Stride, dl,
10517                                             BasePtr.getValueType()));
10518       Stores[Idx] = Store;
10519     }
10520 
10521     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10522 
10523     if (SN->isIndexed()) {
10524       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10525       return DAG.getMergeValues(RetOps, dl);
10526     }
10527 
10528     return TF;
10529   }
10530 
10531   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10532   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10533 
10534   // The values are now known to be -1 (false) or 1 (true). To convert this
10535   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10536   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10537   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10538 
10539   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10540   // understand how to form the extending load.
10541   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10542 
10543   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10544 
10545   // Now convert to an integer and store.
10546   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10547     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10548     Value);
10549 
10550   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10551   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10552   MachinePointerInfo PtrInfo =
10553       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10554   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10555   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10556 
10557   SDValue Ops[] = {StoreChain,
10558                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10559                    Value, FIdx};
10560   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10561 
10562   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10563     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10564 
10565   // Move data into the byte array.
10566   SDValue Loads[4], LoadChains[4];
10567   for (unsigned i = 0; i < 4; ++i) {
10568     unsigned Offset = 4*i;
10569     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10570     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10571 
10572     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10573                            PtrInfo.getWithOffset(Offset));
10574     LoadChains[i] = Loads[i].getValue(1);
10575   }
10576 
10577   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10578 
10579   SDValue Stores[4];
10580   for (unsigned i = 0; i < 4; ++i) {
10581     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10582     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10583 
10584     Stores[i] = DAG.getTruncStore(
10585         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10586         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10587         SN->getAAInfo());
10588   }
10589 
10590   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10591 
10592   return StoreChain;
10593 }
10594 
10595 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10596   SDLoc dl(Op);
10597   if (Op.getValueType() == MVT::v4i32) {
10598     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10599 
10600     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10601     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10602 
10603     SDValue RHSSwap =   // = vrlw RHS, 16
10604       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10605 
10606     // Shrinkify inputs to v8i16.
10607     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10608     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10609     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10610 
10611     // Low parts multiplied together, generating 32-bit results (we ignore the
10612     // top parts).
10613     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10614                                         LHS, RHS, DAG, dl, MVT::v4i32);
10615 
10616     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10617                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10618     // Shift the high parts up 16 bits.
10619     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10620                               Neg16, DAG, dl);
10621     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10622   } else if (Op.getValueType() == MVT::v16i8) {
10623     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10624     bool isLittleEndian = Subtarget.isLittleEndian();
10625 
10626     // Multiply the even 8-bit parts, producing 16-bit sums.
10627     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10628                                            LHS, RHS, DAG, dl, MVT::v8i16);
10629     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10630 
10631     // Multiply the odd 8-bit parts, producing 16-bit sums.
10632     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10633                                           LHS, RHS, DAG, dl, MVT::v8i16);
10634     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10635 
10636     // Merge the results together.  Because vmuleub and vmuloub are
10637     // instructions with a big-endian bias, we must reverse the
10638     // element numbering and reverse the meaning of "odd" and "even"
10639     // when generating little endian code.
10640     int Ops[16];
10641     for (unsigned i = 0; i != 8; ++i) {
10642       if (isLittleEndian) {
10643         Ops[i*2  ] = 2*i;
10644         Ops[i*2+1] = 2*i+16;
10645       } else {
10646         Ops[i*2  ] = 2*i+1;
10647         Ops[i*2+1] = 2*i+1+16;
10648       }
10649     }
10650     if (isLittleEndian)
10651       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10652     else
10653       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10654   } else {
10655     llvm_unreachable("Unknown mul to lower!");
10656   }
10657 }
10658 
10659 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10660 
10661   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10662 
10663   EVT VT = Op.getValueType();
10664   assert(VT.isVector() &&
10665          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10666   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10667           VT == MVT::v16i8) &&
10668          "Unexpected vector element type!");
10669   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10670          "Current subtarget doesn't support smax v2i64!");
10671 
10672   // For vector abs, it can be lowered to:
10673   // abs x
10674   // ==>
10675   // y = -x
10676   // smax(x, y)
10677 
10678   SDLoc dl(Op);
10679   SDValue X = Op.getOperand(0);
10680   SDValue Zero = DAG.getConstant(0, dl, VT);
10681   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10682 
10683   // SMAX patch https://reviews.llvm.org/D47332
10684   // hasn't landed yet, so use intrinsic first here.
10685   // TODO: Should use SMAX directly once SMAX patch landed
10686   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10687   if (VT == MVT::v2i64)
10688     BifID = Intrinsic::ppc_altivec_vmaxsd;
10689   else if (VT == MVT::v8i16)
10690     BifID = Intrinsic::ppc_altivec_vmaxsh;
10691   else if (VT == MVT::v16i8)
10692     BifID = Intrinsic::ppc_altivec_vmaxsb;
10693 
10694   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10695 }
10696 
10697 // Custom lowering for fpext vf32 to v2f64
10698 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10699 
10700   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10701          "Should only be called for ISD::FP_EXTEND");
10702 
10703   // We only want to custom lower an extend from v2f32 to v2f64.
10704   if (Op.getValueType() != MVT::v2f64 ||
10705       Op.getOperand(0).getValueType() != MVT::v2f32)
10706     return SDValue();
10707 
10708   SDLoc dl(Op);
10709   SDValue Op0 = Op.getOperand(0);
10710 
10711   switch (Op0.getOpcode()) {
10712   default:
10713     return SDValue();
10714   case ISD::EXTRACT_SUBVECTOR: {
10715     assert(Op0.getNumOperands() == 2 &&
10716            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10717            "Node should have 2 operands with second one being a constant!");
10718 
10719     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10720       return SDValue();
10721 
10722     // Custom lower is only done for high or low doubleword.
10723     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10724     if (Idx % 2 != 0)
10725       return SDValue();
10726 
10727     // Since input is v4f32, at this point Idx is either 0 or 2.
10728     // Shift to get the doubleword position we want.
10729     int DWord = Idx >> 1;
10730 
10731     // High and low word positions are different on little endian.
10732     if (Subtarget.isLittleEndian())
10733       DWord ^= 0x1;
10734 
10735     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10736                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10737   }
10738   case ISD::FADD:
10739   case ISD::FMUL:
10740   case ISD::FSUB: {
10741     SDValue NewLoad[2];
10742     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10743       // Ensure both input are loads.
10744       SDValue LdOp = Op0.getOperand(i);
10745       if (LdOp.getOpcode() != ISD::LOAD)
10746         return SDValue();
10747       // Generate new load node.
10748       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10749       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10750       NewLoad[i] = DAG.getMemIntrinsicNode(
10751           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10752           LD->getMemoryVT(), LD->getMemOperand());
10753     }
10754     SDValue NewOp =
10755         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10756                     NewLoad[1], Op0.getNode()->getFlags());
10757     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10758                        DAG.getConstant(0, dl, MVT::i32));
10759   }
10760   case ISD::LOAD: {
10761     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10762     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10763     SDValue NewLd = DAG.getMemIntrinsicNode(
10764         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10765         LD->getMemoryVT(), LD->getMemOperand());
10766     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10767                        DAG.getConstant(0, dl, MVT::i32));
10768   }
10769   }
10770   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10771 }
10772 
10773 /// LowerOperation - Provide custom lowering hooks for some operations.
10774 ///
10775 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10776   switch (Op.getOpcode()) {
10777   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10778   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10779   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10780   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10781   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10782   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10783   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10784   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10785   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10786 
10787   // Variable argument lowering.
10788   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10789   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10790   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10791 
10792   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10793   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10794   case ISD::GET_DYNAMIC_AREA_OFFSET:
10795     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10796 
10797   // Exception handling lowering.
10798   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10799   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10800   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10801 
10802   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10803   case ISD::STORE:              return LowerSTORE(Op, DAG);
10804   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10805   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10806   case ISD::FP_TO_UINT:
10807   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10808   case ISD::UINT_TO_FP:
10809   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10810   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10811 
10812   // Lower 64-bit shifts.
10813   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10814   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10815   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10816 
10817   // Vector-related lowering.
10818   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10819   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10820   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10821   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10822   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10823   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10824   case ISD::MUL:                return LowerMUL(Op, DAG);
10825   case ISD::ABS:                return LowerABS(Op, DAG);
10826   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10827 
10828   // For counter-based loop handling.
10829   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10830 
10831   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10832 
10833   // Frame & Return address.
10834   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10835   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10836 
10837   case ISD::INTRINSIC_VOID:
10838     return LowerINTRINSIC_VOID(Op, DAG);
10839   case ISD::SREM:
10840   case ISD::UREM:
10841     return LowerREM(Op, DAG);
10842   case ISD::BSWAP:
10843     return LowerBSWAP(Op, DAG);
10844   case ISD::ATOMIC_CMP_SWAP:
10845     return LowerATOMIC_CMP_SWAP(Op, DAG);
10846   }
10847 }
10848 
10849 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10850                                            SmallVectorImpl<SDValue>&Results,
10851                                            SelectionDAG &DAG) const {
10852   SDLoc dl(N);
10853   switch (N->getOpcode()) {
10854   default:
10855     llvm_unreachable("Do not know how to custom type legalize this operation!");
10856   case ISD::READCYCLECOUNTER: {
10857     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10858     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10859 
10860     Results.push_back(
10861         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10862     Results.push_back(RTB.getValue(2));
10863     break;
10864   }
10865   case ISD::INTRINSIC_W_CHAIN: {
10866     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10867         Intrinsic::loop_decrement)
10868       break;
10869 
10870     assert(N->getValueType(0) == MVT::i1 &&
10871            "Unexpected result type for CTR decrement intrinsic");
10872     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10873                                  N->getValueType(0));
10874     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10875     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10876                                  N->getOperand(1));
10877 
10878     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10879     Results.push_back(NewInt.getValue(1));
10880     break;
10881   }
10882   case ISD::VAARG: {
10883     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10884       return;
10885 
10886     EVT VT = N->getValueType(0);
10887 
10888     if (VT == MVT::i64) {
10889       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10890 
10891       Results.push_back(NewNode);
10892       Results.push_back(NewNode.getValue(1));
10893     }
10894     return;
10895   }
10896   case ISD::FP_TO_SINT:
10897   case ISD::FP_TO_UINT:
10898     // LowerFP_TO_INT() can only handle f32 and f64.
10899     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10900       return;
10901     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10902     return;
10903   case ISD::TRUNCATE: {
10904     EVT TrgVT = N->getValueType(0);
10905     EVT OpVT = N->getOperand(0).getValueType();
10906     if (TrgVT.isVector() &&
10907         isOperationCustom(N->getOpcode(), TrgVT) &&
10908         OpVT.getSizeInBits() <= 128 &&
10909         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10910       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10911     return;
10912   }
10913   case ISD::BITCAST:
10914     // Don't handle bitcast here.
10915     return;
10916   }
10917 }
10918 
10919 //===----------------------------------------------------------------------===//
10920 //  Other Lowering Code
10921 //===----------------------------------------------------------------------===//
10922 
10923 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10924   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10925   Function *Func = Intrinsic::getDeclaration(M, Id);
10926   return Builder.CreateCall(Func, {});
10927 }
10928 
10929 // The mappings for emitLeading/TrailingFence is taken from
10930 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10931 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10932                                                  Instruction *Inst,
10933                                                  AtomicOrdering Ord) const {
10934   if (Ord == AtomicOrdering::SequentiallyConsistent)
10935     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10936   if (isReleaseOrStronger(Ord))
10937     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10938   return nullptr;
10939 }
10940 
10941 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10942                                                   Instruction *Inst,
10943                                                   AtomicOrdering Ord) const {
10944   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10945     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10946     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10947     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10948     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10949       return Builder.CreateCall(
10950           Intrinsic::getDeclaration(
10951               Builder.GetInsertBlock()->getParent()->getParent(),
10952               Intrinsic::ppc_cfence, {Inst->getType()}),
10953           {Inst});
10954     // FIXME: Can use isync for rmw operation.
10955     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10956   }
10957   return nullptr;
10958 }
10959 
10960 MachineBasicBlock *
10961 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10962                                     unsigned AtomicSize,
10963                                     unsigned BinOpcode,
10964                                     unsigned CmpOpcode,
10965                                     unsigned CmpPred) const {
10966   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10967   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10968 
10969   auto LoadMnemonic = PPC::LDARX;
10970   auto StoreMnemonic = PPC::STDCX;
10971   switch (AtomicSize) {
10972   default:
10973     llvm_unreachable("Unexpected size of atomic entity");
10974   case 1:
10975     LoadMnemonic = PPC::LBARX;
10976     StoreMnemonic = PPC::STBCX;
10977     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10978     break;
10979   case 2:
10980     LoadMnemonic = PPC::LHARX;
10981     StoreMnemonic = PPC::STHCX;
10982     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10983     break;
10984   case 4:
10985     LoadMnemonic = PPC::LWARX;
10986     StoreMnemonic = PPC::STWCX;
10987     break;
10988   case 8:
10989     LoadMnemonic = PPC::LDARX;
10990     StoreMnemonic = PPC::STDCX;
10991     break;
10992   }
10993 
10994   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10995   MachineFunction *F = BB->getParent();
10996   MachineFunction::iterator It = ++BB->getIterator();
10997 
10998   Register dest = MI.getOperand(0).getReg();
10999   Register ptrA = MI.getOperand(1).getReg();
11000   Register ptrB = MI.getOperand(2).getReg();
11001   Register incr = MI.getOperand(3).getReg();
11002   DebugLoc dl = MI.getDebugLoc();
11003 
11004   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11005   MachineBasicBlock *loop2MBB =
11006     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11007   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11008   F->insert(It, loopMBB);
11009   if (CmpOpcode)
11010     F->insert(It, loop2MBB);
11011   F->insert(It, exitMBB);
11012   exitMBB->splice(exitMBB->begin(), BB,
11013                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11014   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11015 
11016   MachineRegisterInfo &RegInfo = F->getRegInfo();
11017   Register TmpReg = (!BinOpcode) ? incr :
11018     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11019                                            : &PPC::GPRCRegClass);
11020 
11021   //  thisMBB:
11022   //   ...
11023   //   fallthrough --> loopMBB
11024   BB->addSuccessor(loopMBB);
11025 
11026   //  loopMBB:
11027   //   l[wd]arx dest, ptr
11028   //   add r0, dest, incr
11029   //   st[wd]cx. r0, ptr
11030   //   bne- loopMBB
11031   //   fallthrough --> exitMBB
11032 
11033   // For max/min...
11034   //  loopMBB:
11035   //   l[wd]arx dest, ptr
11036   //   cmpl?[wd] incr, dest
11037   //   bgt exitMBB
11038   //  loop2MBB:
11039   //   st[wd]cx. dest, ptr
11040   //   bne- loopMBB
11041   //   fallthrough --> exitMBB
11042 
11043   BB = loopMBB;
11044   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11045     .addReg(ptrA).addReg(ptrB);
11046   if (BinOpcode)
11047     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11048   if (CmpOpcode) {
11049     // Signed comparisons of byte or halfword values must be sign-extended.
11050     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11051       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11052       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11053               ExtReg).addReg(dest);
11054       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11055         .addReg(incr).addReg(ExtReg);
11056     } else
11057       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11058         .addReg(incr).addReg(dest);
11059 
11060     BuildMI(BB, dl, TII->get(PPC::BCC))
11061       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11062     BB->addSuccessor(loop2MBB);
11063     BB->addSuccessor(exitMBB);
11064     BB = loop2MBB;
11065   }
11066   BuildMI(BB, dl, TII->get(StoreMnemonic))
11067     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11068   BuildMI(BB, dl, TII->get(PPC::BCC))
11069     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11070   BB->addSuccessor(loopMBB);
11071   BB->addSuccessor(exitMBB);
11072 
11073   //  exitMBB:
11074   //   ...
11075   BB = exitMBB;
11076   return BB;
11077 }
11078 
11079 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11080     MachineInstr &MI, MachineBasicBlock *BB,
11081     bool is8bit, // operation
11082     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11083   // If we support part-word atomic mnemonics, just use them
11084   if (Subtarget.hasPartwordAtomics())
11085     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11086                             CmpPred);
11087 
11088   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11089   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11090   // In 64 bit mode we have to use 64 bits for addresses, even though the
11091   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11092   // registers without caring whether they're 32 or 64, but here we're
11093   // doing actual arithmetic on the addresses.
11094   bool is64bit = Subtarget.isPPC64();
11095   bool isLittleEndian = Subtarget.isLittleEndian();
11096   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11097 
11098   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11099   MachineFunction *F = BB->getParent();
11100   MachineFunction::iterator It = ++BB->getIterator();
11101 
11102   Register dest = MI.getOperand(0).getReg();
11103   Register ptrA = MI.getOperand(1).getReg();
11104   Register ptrB = MI.getOperand(2).getReg();
11105   Register incr = MI.getOperand(3).getReg();
11106   DebugLoc dl = MI.getDebugLoc();
11107 
11108   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11109   MachineBasicBlock *loop2MBB =
11110       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11111   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11112   F->insert(It, loopMBB);
11113   if (CmpOpcode)
11114     F->insert(It, loop2MBB);
11115   F->insert(It, exitMBB);
11116   exitMBB->splice(exitMBB->begin(), BB,
11117                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11118   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11119 
11120   MachineRegisterInfo &RegInfo = F->getRegInfo();
11121   const TargetRegisterClass *RC =
11122       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11123   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11124 
11125   Register PtrReg = RegInfo.createVirtualRegister(RC);
11126   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11127   Register ShiftReg =
11128       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11129   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11130   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11131   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11132   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11133   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11134   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11135   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11136   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11137   Register Ptr1Reg;
11138   Register TmpReg =
11139       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11140 
11141   //  thisMBB:
11142   //   ...
11143   //   fallthrough --> loopMBB
11144   BB->addSuccessor(loopMBB);
11145 
11146   // The 4-byte load must be aligned, while a char or short may be
11147   // anywhere in the word.  Hence all this nasty bookkeeping code.
11148   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11149   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11150   //   xori shift, shift1, 24 [16]
11151   //   rlwinm ptr, ptr1, 0, 0, 29
11152   //   slw incr2, incr, shift
11153   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11154   //   slw mask, mask2, shift
11155   //  loopMBB:
11156   //   lwarx tmpDest, ptr
11157   //   add tmp, tmpDest, incr2
11158   //   andc tmp2, tmpDest, mask
11159   //   and tmp3, tmp, mask
11160   //   or tmp4, tmp3, tmp2
11161   //   stwcx. tmp4, ptr
11162   //   bne- loopMBB
11163   //   fallthrough --> exitMBB
11164   //   srw dest, tmpDest, shift
11165   if (ptrA != ZeroReg) {
11166     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11167     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11168         .addReg(ptrA)
11169         .addReg(ptrB);
11170   } else {
11171     Ptr1Reg = ptrB;
11172   }
11173   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11174   // mode.
11175   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11176       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11177       .addImm(3)
11178       .addImm(27)
11179       .addImm(is8bit ? 28 : 27);
11180   if (!isLittleEndian)
11181     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11182         .addReg(Shift1Reg)
11183         .addImm(is8bit ? 24 : 16);
11184   if (is64bit)
11185     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11186         .addReg(Ptr1Reg)
11187         .addImm(0)
11188         .addImm(61);
11189   else
11190     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11191         .addReg(Ptr1Reg)
11192         .addImm(0)
11193         .addImm(0)
11194         .addImm(29);
11195   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11196   if (is8bit)
11197     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11198   else {
11199     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11200     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11201         .addReg(Mask3Reg)
11202         .addImm(65535);
11203   }
11204   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11205       .addReg(Mask2Reg)
11206       .addReg(ShiftReg);
11207 
11208   BB = loopMBB;
11209   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11210       .addReg(ZeroReg)
11211       .addReg(PtrReg);
11212   if (BinOpcode)
11213     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11214         .addReg(Incr2Reg)
11215         .addReg(TmpDestReg);
11216   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11217       .addReg(TmpDestReg)
11218       .addReg(MaskReg);
11219   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11220   if (CmpOpcode) {
11221     // For unsigned comparisons, we can directly compare the shifted values.
11222     // For signed comparisons we shift and sign extend.
11223     Register SReg = RegInfo.createVirtualRegister(GPRC);
11224     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11225         .addReg(TmpDestReg)
11226         .addReg(MaskReg);
11227     unsigned ValueReg = SReg;
11228     unsigned CmpReg = Incr2Reg;
11229     if (CmpOpcode == PPC::CMPW) {
11230       ValueReg = RegInfo.createVirtualRegister(GPRC);
11231       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11232           .addReg(SReg)
11233           .addReg(ShiftReg);
11234       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11235       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11236           .addReg(ValueReg);
11237       ValueReg = ValueSReg;
11238       CmpReg = incr;
11239     }
11240     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11241         .addReg(CmpReg)
11242         .addReg(ValueReg);
11243     BuildMI(BB, dl, TII->get(PPC::BCC))
11244         .addImm(CmpPred)
11245         .addReg(PPC::CR0)
11246         .addMBB(exitMBB);
11247     BB->addSuccessor(loop2MBB);
11248     BB->addSuccessor(exitMBB);
11249     BB = loop2MBB;
11250   }
11251   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11252   BuildMI(BB, dl, TII->get(PPC::STWCX))
11253       .addReg(Tmp4Reg)
11254       .addReg(ZeroReg)
11255       .addReg(PtrReg);
11256   BuildMI(BB, dl, TII->get(PPC::BCC))
11257       .addImm(PPC::PRED_NE)
11258       .addReg(PPC::CR0)
11259       .addMBB(loopMBB);
11260   BB->addSuccessor(loopMBB);
11261   BB->addSuccessor(exitMBB);
11262 
11263   //  exitMBB:
11264   //   ...
11265   BB = exitMBB;
11266   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11267       .addReg(TmpDestReg)
11268       .addReg(ShiftReg);
11269   return BB;
11270 }
11271 
11272 llvm::MachineBasicBlock *
11273 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11274                                     MachineBasicBlock *MBB) const {
11275   DebugLoc DL = MI.getDebugLoc();
11276   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11277   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11278 
11279   MachineFunction *MF = MBB->getParent();
11280   MachineRegisterInfo &MRI = MF->getRegInfo();
11281 
11282   const BasicBlock *BB = MBB->getBasicBlock();
11283   MachineFunction::iterator I = ++MBB->getIterator();
11284 
11285   Register DstReg = MI.getOperand(0).getReg();
11286   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11287   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11288   Register mainDstReg = MRI.createVirtualRegister(RC);
11289   Register restoreDstReg = MRI.createVirtualRegister(RC);
11290 
11291   MVT PVT = getPointerTy(MF->getDataLayout());
11292   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11293          "Invalid Pointer Size!");
11294   // For v = setjmp(buf), we generate
11295   //
11296   // thisMBB:
11297   //  SjLjSetup mainMBB
11298   //  bl mainMBB
11299   //  v_restore = 1
11300   //  b sinkMBB
11301   //
11302   // mainMBB:
11303   //  buf[LabelOffset] = LR
11304   //  v_main = 0
11305   //
11306   // sinkMBB:
11307   //  v = phi(main, restore)
11308   //
11309 
11310   MachineBasicBlock *thisMBB = MBB;
11311   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11312   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11313   MF->insert(I, mainMBB);
11314   MF->insert(I, sinkMBB);
11315 
11316   MachineInstrBuilder MIB;
11317 
11318   // Transfer the remainder of BB and its successor edges to sinkMBB.
11319   sinkMBB->splice(sinkMBB->begin(), MBB,
11320                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11321   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11322 
11323   // Note that the structure of the jmp_buf used here is not compatible
11324   // with that used by libc, and is not designed to be. Specifically, it
11325   // stores only those 'reserved' registers that LLVM does not otherwise
11326   // understand how to spill. Also, by convention, by the time this
11327   // intrinsic is called, Clang has already stored the frame address in the
11328   // first slot of the buffer and stack address in the third. Following the
11329   // X86 target code, we'll store the jump address in the second slot. We also
11330   // need to save the TOC pointer (R2) to handle jumps between shared
11331   // libraries, and that will be stored in the fourth slot. The thread
11332   // identifier (R13) is not affected.
11333 
11334   // thisMBB:
11335   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11336   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11337   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11338 
11339   // Prepare IP either in reg.
11340   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11341   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11342   Register BufReg = MI.getOperand(1).getReg();
11343 
11344   if (Subtarget.is64BitELFABI()) {
11345     setUsesTOCBasePtr(*MBB->getParent());
11346     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11347               .addReg(PPC::X2)
11348               .addImm(TOCOffset)
11349               .addReg(BufReg)
11350               .cloneMemRefs(MI);
11351   }
11352 
11353   // Naked functions never have a base pointer, and so we use r1. For all
11354   // other functions, this decision must be delayed until during PEI.
11355   unsigned BaseReg;
11356   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11357     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11358   else
11359     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11360 
11361   MIB = BuildMI(*thisMBB, MI, DL,
11362                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11363             .addReg(BaseReg)
11364             .addImm(BPOffset)
11365             .addReg(BufReg)
11366             .cloneMemRefs(MI);
11367 
11368   // Setup
11369   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11370   MIB.addRegMask(TRI->getNoPreservedMask());
11371 
11372   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11373 
11374   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11375           .addMBB(mainMBB);
11376   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11377 
11378   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11379   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11380 
11381   // mainMBB:
11382   //  mainDstReg = 0
11383   MIB =
11384       BuildMI(mainMBB, DL,
11385               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11386 
11387   // Store IP
11388   if (Subtarget.isPPC64()) {
11389     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11390             .addReg(LabelReg)
11391             .addImm(LabelOffset)
11392             .addReg(BufReg);
11393   } else {
11394     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11395             .addReg(LabelReg)
11396             .addImm(LabelOffset)
11397             .addReg(BufReg);
11398   }
11399   MIB.cloneMemRefs(MI);
11400 
11401   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11402   mainMBB->addSuccessor(sinkMBB);
11403 
11404   // sinkMBB:
11405   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11406           TII->get(PPC::PHI), DstReg)
11407     .addReg(mainDstReg).addMBB(mainMBB)
11408     .addReg(restoreDstReg).addMBB(thisMBB);
11409 
11410   MI.eraseFromParent();
11411   return sinkMBB;
11412 }
11413 
11414 MachineBasicBlock *
11415 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11416                                      MachineBasicBlock *MBB) const {
11417   DebugLoc DL = MI.getDebugLoc();
11418   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11419 
11420   MachineFunction *MF = MBB->getParent();
11421   MachineRegisterInfo &MRI = MF->getRegInfo();
11422 
11423   MVT PVT = getPointerTy(MF->getDataLayout());
11424   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11425          "Invalid Pointer Size!");
11426 
11427   const TargetRegisterClass *RC =
11428     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11429   Register Tmp = MRI.createVirtualRegister(RC);
11430   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11431   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11432   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11433   unsigned BP =
11434       (PVT == MVT::i64)
11435           ? PPC::X30
11436           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11437                                                               : PPC::R30);
11438 
11439   MachineInstrBuilder MIB;
11440 
11441   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11442   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11443   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11444   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11445 
11446   Register BufReg = MI.getOperand(0).getReg();
11447 
11448   // Reload FP (the jumped-to function may not have had a
11449   // frame pointer, and if so, then its r31 will be restored
11450   // as necessary).
11451   if (PVT == MVT::i64) {
11452     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11453             .addImm(0)
11454             .addReg(BufReg);
11455   } else {
11456     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11457             .addImm(0)
11458             .addReg(BufReg);
11459   }
11460   MIB.cloneMemRefs(MI);
11461 
11462   // Reload IP
11463   if (PVT == MVT::i64) {
11464     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11465             .addImm(LabelOffset)
11466             .addReg(BufReg);
11467   } else {
11468     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11469             .addImm(LabelOffset)
11470             .addReg(BufReg);
11471   }
11472   MIB.cloneMemRefs(MI);
11473 
11474   // Reload SP
11475   if (PVT == MVT::i64) {
11476     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11477             .addImm(SPOffset)
11478             .addReg(BufReg);
11479   } else {
11480     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11481             .addImm(SPOffset)
11482             .addReg(BufReg);
11483   }
11484   MIB.cloneMemRefs(MI);
11485 
11486   // Reload BP
11487   if (PVT == MVT::i64) {
11488     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11489             .addImm(BPOffset)
11490             .addReg(BufReg);
11491   } else {
11492     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11493             .addImm(BPOffset)
11494             .addReg(BufReg);
11495   }
11496   MIB.cloneMemRefs(MI);
11497 
11498   // Reload TOC
11499   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11500     setUsesTOCBasePtr(*MBB->getParent());
11501     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11502               .addImm(TOCOffset)
11503               .addReg(BufReg)
11504               .cloneMemRefs(MI);
11505   }
11506 
11507   // Jump
11508   BuildMI(*MBB, MI, DL,
11509           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11510   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11511 
11512   MI.eraseFromParent();
11513   return MBB;
11514 }
11515 
11516 MachineBasicBlock *
11517 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11518                                                MachineBasicBlock *BB) const {
11519   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11520       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11521     if (Subtarget.is64BitELFABI() &&
11522         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11523         !Subtarget.isUsingPCRelativeCalls()) {
11524       // Call lowering should have added an r2 operand to indicate a dependence
11525       // on the TOC base pointer value. It can't however, because there is no
11526       // way to mark the dependence as implicit there, and so the stackmap code
11527       // will confuse it with a regular operand. Instead, add the dependence
11528       // here.
11529       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11530     }
11531 
11532     return emitPatchPoint(MI, BB);
11533   }
11534 
11535   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11536       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11537     return emitEHSjLjSetJmp(MI, BB);
11538   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11539              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11540     return emitEHSjLjLongJmp(MI, BB);
11541   }
11542 
11543   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11544 
11545   // To "insert" these instructions we actually have to insert their
11546   // control-flow patterns.
11547   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11548   MachineFunction::iterator It = ++BB->getIterator();
11549 
11550   MachineFunction *F = BB->getParent();
11551 
11552   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11553       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11554       MI.getOpcode() == PPC::SELECT_I8) {
11555     SmallVector<MachineOperand, 2> Cond;
11556     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11557         MI.getOpcode() == PPC::SELECT_CC_I8)
11558       Cond.push_back(MI.getOperand(4));
11559     else
11560       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11561     Cond.push_back(MI.getOperand(1));
11562 
11563     DebugLoc dl = MI.getDebugLoc();
11564     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11565                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11566   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11567              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11568              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11569              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11570              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11571              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11572              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11573              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11574              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11575              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11576              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11577              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11578              MI.getOpcode() == PPC::SELECT_F4 ||
11579              MI.getOpcode() == PPC::SELECT_F8 ||
11580              MI.getOpcode() == PPC::SELECT_F16 ||
11581              MI.getOpcode() == PPC::SELECT_QFRC ||
11582              MI.getOpcode() == PPC::SELECT_QSRC ||
11583              MI.getOpcode() == PPC::SELECT_QBRC ||
11584              MI.getOpcode() == PPC::SELECT_SPE ||
11585              MI.getOpcode() == PPC::SELECT_SPE4 ||
11586              MI.getOpcode() == PPC::SELECT_VRRC ||
11587              MI.getOpcode() == PPC::SELECT_VSFRC ||
11588              MI.getOpcode() == PPC::SELECT_VSSRC ||
11589              MI.getOpcode() == PPC::SELECT_VSRC) {
11590     // The incoming instruction knows the destination vreg to set, the
11591     // condition code register to branch on, the true/false values to
11592     // select between, and a branch opcode to use.
11593 
11594     //  thisMBB:
11595     //  ...
11596     //   TrueVal = ...
11597     //   cmpTY ccX, r1, r2
11598     //   bCC copy1MBB
11599     //   fallthrough --> copy0MBB
11600     MachineBasicBlock *thisMBB = BB;
11601     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11602     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11603     DebugLoc dl = MI.getDebugLoc();
11604     F->insert(It, copy0MBB);
11605     F->insert(It, sinkMBB);
11606 
11607     // Transfer the remainder of BB and its successor edges to sinkMBB.
11608     sinkMBB->splice(sinkMBB->begin(), BB,
11609                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11610     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11611 
11612     // Next, add the true and fallthrough blocks as its successors.
11613     BB->addSuccessor(copy0MBB);
11614     BB->addSuccessor(sinkMBB);
11615 
11616     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11617         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11618         MI.getOpcode() == PPC::SELECT_F16 ||
11619         MI.getOpcode() == PPC::SELECT_SPE4 ||
11620         MI.getOpcode() == PPC::SELECT_SPE ||
11621         MI.getOpcode() == PPC::SELECT_QFRC ||
11622         MI.getOpcode() == PPC::SELECT_QSRC ||
11623         MI.getOpcode() == PPC::SELECT_QBRC ||
11624         MI.getOpcode() == PPC::SELECT_VRRC ||
11625         MI.getOpcode() == PPC::SELECT_VSFRC ||
11626         MI.getOpcode() == PPC::SELECT_VSSRC ||
11627         MI.getOpcode() == PPC::SELECT_VSRC) {
11628       BuildMI(BB, dl, TII->get(PPC::BC))
11629           .addReg(MI.getOperand(1).getReg())
11630           .addMBB(sinkMBB);
11631     } else {
11632       unsigned SelectPred = MI.getOperand(4).getImm();
11633       BuildMI(BB, dl, TII->get(PPC::BCC))
11634           .addImm(SelectPred)
11635           .addReg(MI.getOperand(1).getReg())
11636           .addMBB(sinkMBB);
11637     }
11638 
11639     //  copy0MBB:
11640     //   %FalseValue = ...
11641     //   # fallthrough to sinkMBB
11642     BB = copy0MBB;
11643 
11644     // Update machine-CFG edges
11645     BB->addSuccessor(sinkMBB);
11646 
11647     //  sinkMBB:
11648     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11649     //  ...
11650     BB = sinkMBB;
11651     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11652         .addReg(MI.getOperand(3).getReg())
11653         .addMBB(copy0MBB)
11654         .addReg(MI.getOperand(2).getReg())
11655         .addMBB(thisMBB);
11656   } else if (MI.getOpcode() == PPC::ReadTB) {
11657     // To read the 64-bit time-base register on a 32-bit target, we read the
11658     // two halves. Should the counter have wrapped while it was being read, we
11659     // need to try again.
11660     // ...
11661     // readLoop:
11662     // mfspr Rx,TBU # load from TBU
11663     // mfspr Ry,TB  # load from TB
11664     // mfspr Rz,TBU # load from TBU
11665     // cmpw crX,Rx,Rz # check if 'old'='new'
11666     // bne readLoop   # branch if they're not equal
11667     // ...
11668 
11669     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11670     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11671     DebugLoc dl = MI.getDebugLoc();
11672     F->insert(It, readMBB);
11673     F->insert(It, sinkMBB);
11674 
11675     // Transfer the remainder of BB and its successor edges to sinkMBB.
11676     sinkMBB->splice(sinkMBB->begin(), BB,
11677                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11678     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11679 
11680     BB->addSuccessor(readMBB);
11681     BB = readMBB;
11682 
11683     MachineRegisterInfo &RegInfo = F->getRegInfo();
11684     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11685     Register LoReg = MI.getOperand(0).getReg();
11686     Register HiReg = MI.getOperand(1).getReg();
11687 
11688     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11689     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11690     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11691 
11692     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11693 
11694     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11695         .addReg(HiReg)
11696         .addReg(ReadAgainReg);
11697     BuildMI(BB, dl, TII->get(PPC::BCC))
11698         .addImm(PPC::PRED_NE)
11699         .addReg(CmpReg)
11700         .addMBB(readMBB);
11701 
11702     BB->addSuccessor(readMBB);
11703     BB->addSuccessor(sinkMBB);
11704   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11705     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11706   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11707     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11708   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11709     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11710   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11711     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11712 
11713   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11714     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11715   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11716     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11717   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11718     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11719   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11720     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11721 
11722   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11723     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11724   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11725     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11726   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11727     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11728   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11729     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11730 
11731   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11732     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11733   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11734     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11735   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11736     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11737   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11738     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11739 
11740   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11741     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11742   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11743     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11744   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11745     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11746   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11747     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11748 
11749   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11750     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11751   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11752     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11753   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11754     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11755   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11756     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11757 
11758   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11759     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11760   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11761     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11762   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11763     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11764   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11765     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11766 
11767   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11768     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11769   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11770     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11771   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11772     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11773   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11774     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11775 
11776   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11777     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11778   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11779     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11780   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11781     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11782   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11783     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11784 
11785   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11786     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11787   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11788     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11789   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11790     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11791   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11792     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11793 
11794   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11795     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11796   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11797     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11798   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11799     BB = EmitAtomicBinary(MI, BB, 4, 0);
11800   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11801     BB = EmitAtomicBinary(MI, BB, 8, 0);
11802   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11803            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11804            (Subtarget.hasPartwordAtomics() &&
11805             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11806            (Subtarget.hasPartwordAtomics() &&
11807             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11808     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11809 
11810     auto LoadMnemonic = PPC::LDARX;
11811     auto StoreMnemonic = PPC::STDCX;
11812     switch (MI.getOpcode()) {
11813     default:
11814       llvm_unreachable("Compare and swap of unknown size");
11815     case PPC::ATOMIC_CMP_SWAP_I8:
11816       LoadMnemonic = PPC::LBARX;
11817       StoreMnemonic = PPC::STBCX;
11818       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11819       break;
11820     case PPC::ATOMIC_CMP_SWAP_I16:
11821       LoadMnemonic = PPC::LHARX;
11822       StoreMnemonic = PPC::STHCX;
11823       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11824       break;
11825     case PPC::ATOMIC_CMP_SWAP_I32:
11826       LoadMnemonic = PPC::LWARX;
11827       StoreMnemonic = PPC::STWCX;
11828       break;
11829     case PPC::ATOMIC_CMP_SWAP_I64:
11830       LoadMnemonic = PPC::LDARX;
11831       StoreMnemonic = PPC::STDCX;
11832       break;
11833     }
11834     Register dest = MI.getOperand(0).getReg();
11835     Register ptrA = MI.getOperand(1).getReg();
11836     Register ptrB = MI.getOperand(2).getReg();
11837     Register oldval = MI.getOperand(3).getReg();
11838     Register newval = MI.getOperand(4).getReg();
11839     DebugLoc dl = MI.getDebugLoc();
11840 
11841     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11842     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11843     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11844     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11845     F->insert(It, loop1MBB);
11846     F->insert(It, loop2MBB);
11847     F->insert(It, midMBB);
11848     F->insert(It, exitMBB);
11849     exitMBB->splice(exitMBB->begin(), BB,
11850                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11851     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11852 
11853     //  thisMBB:
11854     //   ...
11855     //   fallthrough --> loopMBB
11856     BB->addSuccessor(loop1MBB);
11857 
11858     // loop1MBB:
11859     //   l[bhwd]arx dest, ptr
11860     //   cmp[wd] dest, oldval
11861     //   bne- midMBB
11862     // loop2MBB:
11863     //   st[bhwd]cx. newval, ptr
11864     //   bne- loopMBB
11865     //   b exitBB
11866     // midMBB:
11867     //   st[bhwd]cx. dest, ptr
11868     // exitBB:
11869     BB = loop1MBB;
11870     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11871     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11872         .addReg(oldval)
11873         .addReg(dest);
11874     BuildMI(BB, dl, TII->get(PPC::BCC))
11875         .addImm(PPC::PRED_NE)
11876         .addReg(PPC::CR0)
11877         .addMBB(midMBB);
11878     BB->addSuccessor(loop2MBB);
11879     BB->addSuccessor(midMBB);
11880 
11881     BB = loop2MBB;
11882     BuildMI(BB, dl, TII->get(StoreMnemonic))
11883         .addReg(newval)
11884         .addReg(ptrA)
11885         .addReg(ptrB);
11886     BuildMI(BB, dl, TII->get(PPC::BCC))
11887         .addImm(PPC::PRED_NE)
11888         .addReg(PPC::CR0)
11889         .addMBB(loop1MBB);
11890     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11891     BB->addSuccessor(loop1MBB);
11892     BB->addSuccessor(exitMBB);
11893 
11894     BB = midMBB;
11895     BuildMI(BB, dl, TII->get(StoreMnemonic))
11896         .addReg(dest)
11897         .addReg(ptrA)
11898         .addReg(ptrB);
11899     BB->addSuccessor(exitMBB);
11900 
11901     //  exitMBB:
11902     //   ...
11903     BB = exitMBB;
11904   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11905              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11906     // We must use 64-bit registers for addresses when targeting 64-bit,
11907     // since we're actually doing arithmetic on them.  Other registers
11908     // can be 32-bit.
11909     bool is64bit = Subtarget.isPPC64();
11910     bool isLittleEndian = Subtarget.isLittleEndian();
11911     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11912 
11913     Register dest = MI.getOperand(0).getReg();
11914     Register ptrA = MI.getOperand(1).getReg();
11915     Register ptrB = MI.getOperand(2).getReg();
11916     Register oldval = MI.getOperand(3).getReg();
11917     Register newval = MI.getOperand(4).getReg();
11918     DebugLoc dl = MI.getDebugLoc();
11919 
11920     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11921     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11922     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11923     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11924     F->insert(It, loop1MBB);
11925     F->insert(It, loop2MBB);
11926     F->insert(It, midMBB);
11927     F->insert(It, exitMBB);
11928     exitMBB->splice(exitMBB->begin(), BB,
11929                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11930     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11931 
11932     MachineRegisterInfo &RegInfo = F->getRegInfo();
11933     const TargetRegisterClass *RC =
11934         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11935     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11936 
11937     Register PtrReg = RegInfo.createVirtualRegister(RC);
11938     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11939     Register ShiftReg =
11940         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11941     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11942     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11943     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11944     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11945     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11946     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11947     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11948     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11949     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11950     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11951     Register Ptr1Reg;
11952     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11953     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11954     //  thisMBB:
11955     //   ...
11956     //   fallthrough --> loopMBB
11957     BB->addSuccessor(loop1MBB);
11958 
11959     // The 4-byte load must be aligned, while a char or short may be
11960     // anywhere in the word.  Hence all this nasty bookkeeping code.
11961     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11962     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11963     //   xori shift, shift1, 24 [16]
11964     //   rlwinm ptr, ptr1, 0, 0, 29
11965     //   slw newval2, newval, shift
11966     //   slw oldval2, oldval,shift
11967     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11968     //   slw mask, mask2, shift
11969     //   and newval3, newval2, mask
11970     //   and oldval3, oldval2, mask
11971     // loop1MBB:
11972     //   lwarx tmpDest, ptr
11973     //   and tmp, tmpDest, mask
11974     //   cmpw tmp, oldval3
11975     //   bne- midMBB
11976     // loop2MBB:
11977     //   andc tmp2, tmpDest, mask
11978     //   or tmp4, tmp2, newval3
11979     //   stwcx. tmp4, ptr
11980     //   bne- loop1MBB
11981     //   b exitBB
11982     // midMBB:
11983     //   stwcx. tmpDest, ptr
11984     // exitBB:
11985     //   srw dest, tmpDest, shift
11986     if (ptrA != ZeroReg) {
11987       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11988       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11989           .addReg(ptrA)
11990           .addReg(ptrB);
11991     } else {
11992       Ptr1Reg = ptrB;
11993     }
11994 
11995     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11996     // mode.
11997     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11998         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11999         .addImm(3)
12000         .addImm(27)
12001         .addImm(is8bit ? 28 : 27);
12002     if (!isLittleEndian)
12003       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12004           .addReg(Shift1Reg)
12005           .addImm(is8bit ? 24 : 16);
12006     if (is64bit)
12007       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12008           .addReg(Ptr1Reg)
12009           .addImm(0)
12010           .addImm(61);
12011     else
12012       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12013           .addReg(Ptr1Reg)
12014           .addImm(0)
12015           .addImm(0)
12016           .addImm(29);
12017     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12018         .addReg(newval)
12019         .addReg(ShiftReg);
12020     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12021         .addReg(oldval)
12022         .addReg(ShiftReg);
12023     if (is8bit)
12024       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12025     else {
12026       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12027       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12028           .addReg(Mask3Reg)
12029           .addImm(65535);
12030     }
12031     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12032         .addReg(Mask2Reg)
12033         .addReg(ShiftReg);
12034     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12035         .addReg(NewVal2Reg)
12036         .addReg(MaskReg);
12037     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12038         .addReg(OldVal2Reg)
12039         .addReg(MaskReg);
12040 
12041     BB = loop1MBB;
12042     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12043         .addReg(ZeroReg)
12044         .addReg(PtrReg);
12045     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12046         .addReg(TmpDestReg)
12047         .addReg(MaskReg);
12048     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12049         .addReg(TmpReg)
12050         .addReg(OldVal3Reg);
12051     BuildMI(BB, dl, TII->get(PPC::BCC))
12052         .addImm(PPC::PRED_NE)
12053         .addReg(PPC::CR0)
12054         .addMBB(midMBB);
12055     BB->addSuccessor(loop2MBB);
12056     BB->addSuccessor(midMBB);
12057 
12058     BB = loop2MBB;
12059     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12060         .addReg(TmpDestReg)
12061         .addReg(MaskReg);
12062     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12063         .addReg(Tmp2Reg)
12064         .addReg(NewVal3Reg);
12065     BuildMI(BB, dl, TII->get(PPC::STWCX))
12066         .addReg(Tmp4Reg)
12067         .addReg(ZeroReg)
12068         .addReg(PtrReg);
12069     BuildMI(BB, dl, TII->get(PPC::BCC))
12070         .addImm(PPC::PRED_NE)
12071         .addReg(PPC::CR0)
12072         .addMBB(loop1MBB);
12073     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12074     BB->addSuccessor(loop1MBB);
12075     BB->addSuccessor(exitMBB);
12076 
12077     BB = midMBB;
12078     BuildMI(BB, dl, TII->get(PPC::STWCX))
12079         .addReg(TmpDestReg)
12080         .addReg(ZeroReg)
12081         .addReg(PtrReg);
12082     BB->addSuccessor(exitMBB);
12083 
12084     //  exitMBB:
12085     //   ...
12086     BB = exitMBB;
12087     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12088         .addReg(TmpReg)
12089         .addReg(ShiftReg);
12090   } else if (MI.getOpcode() == PPC::FADDrtz) {
12091     // This pseudo performs an FADD with rounding mode temporarily forced
12092     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12093     // is not modeled at the SelectionDAG level.
12094     Register Dest = MI.getOperand(0).getReg();
12095     Register Src1 = MI.getOperand(1).getReg();
12096     Register Src2 = MI.getOperand(2).getReg();
12097     DebugLoc dl = MI.getDebugLoc();
12098 
12099     MachineRegisterInfo &RegInfo = F->getRegInfo();
12100     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12101 
12102     // Save FPSCR value.
12103     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12104 
12105     // Set rounding mode to round-to-zero.
12106     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12107     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12108 
12109     // Perform addition.
12110     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12111 
12112     // Restore FPSCR value.
12113     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12114   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12115              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12116              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12117              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12118     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12119                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12120                           ? PPC::ANDI8_rec
12121                           : PPC::ANDI_rec;
12122     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12123                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12124 
12125     MachineRegisterInfo &RegInfo = F->getRegInfo();
12126     Register Dest = RegInfo.createVirtualRegister(
12127         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12128 
12129     DebugLoc Dl = MI.getDebugLoc();
12130     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12131         .addReg(MI.getOperand(1).getReg())
12132         .addImm(1);
12133     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12134             MI.getOperand(0).getReg())
12135         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12136   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12137     DebugLoc Dl = MI.getDebugLoc();
12138     MachineRegisterInfo &RegInfo = F->getRegInfo();
12139     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12140     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12141     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12142             MI.getOperand(0).getReg())
12143         .addReg(CRReg);
12144   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12145     DebugLoc Dl = MI.getDebugLoc();
12146     unsigned Imm = MI.getOperand(1).getImm();
12147     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12148     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12149             MI.getOperand(0).getReg())
12150         .addReg(PPC::CR0EQ);
12151   } else if (MI.getOpcode() == PPC::SETRNDi) {
12152     DebugLoc dl = MI.getDebugLoc();
12153     Register OldFPSCRReg = MI.getOperand(0).getReg();
12154 
12155     // Save FPSCR value.
12156     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12157 
12158     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12159     // the following settings:
12160     //   00 Round to nearest
12161     //   01 Round to 0
12162     //   10 Round to +inf
12163     //   11 Round to -inf
12164 
12165     // When the operand is immediate, using the two least significant bits of
12166     // the immediate to set the bits 62:63 of FPSCR.
12167     unsigned Mode = MI.getOperand(1).getImm();
12168     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12169       .addImm(31);
12170 
12171     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12172       .addImm(30);
12173   } else if (MI.getOpcode() == PPC::SETRND) {
12174     DebugLoc dl = MI.getDebugLoc();
12175 
12176     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12177     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12178     // If the target doesn't have DirectMove, we should use stack to do the
12179     // conversion, because the target doesn't have the instructions like mtvsrd
12180     // or mfvsrd to do this conversion directly.
12181     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12182       if (Subtarget.hasDirectMove()) {
12183         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12184           .addReg(SrcReg);
12185       } else {
12186         // Use stack to do the register copy.
12187         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12188         MachineRegisterInfo &RegInfo = F->getRegInfo();
12189         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12190         if (RC == &PPC::F8RCRegClass) {
12191           // Copy register from F8RCRegClass to G8RCRegclass.
12192           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12193                  "Unsupported RegClass.");
12194 
12195           StoreOp = PPC::STFD;
12196           LoadOp = PPC::LD;
12197         } else {
12198           // Copy register from G8RCRegClass to F8RCRegclass.
12199           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12200                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12201                  "Unsupported RegClass.");
12202         }
12203 
12204         MachineFrameInfo &MFI = F->getFrameInfo();
12205         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12206 
12207         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12208             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12209             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12210             MFI.getObjectAlign(FrameIdx));
12211 
12212         // Store the SrcReg into the stack.
12213         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12214           .addReg(SrcReg)
12215           .addImm(0)
12216           .addFrameIndex(FrameIdx)
12217           .addMemOperand(MMOStore);
12218 
12219         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12220             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12221             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12222             MFI.getObjectAlign(FrameIdx));
12223 
12224         // Load from the stack where SrcReg is stored, and save to DestReg,
12225         // so we have done the RegClass conversion from RegClass::SrcReg to
12226         // RegClass::DestReg.
12227         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12228           .addImm(0)
12229           .addFrameIndex(FrameIdx)
12230           .addMemOperand(MMOLoad);
12231       }
12232     };
12233 
12234     Register OldFPSCRReg = MI.getOperand(0).getReg();
12235 
12236     // Save FPSCR value.
12237     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12238 
12239     // When the operand is gprc register, use two least significant bits of the
12240     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12241     //
12242     // copy OldFPSCRTmpReg, OldFPSCRReg
12243     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12244     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12245     // copy NewFPSCRReg, NewFPSCRTmpReg
12246     // mtfsf 255, NewFPSCRReg
12247     MachineOperand SrcOp = MI.getOperand(1);
12248     MachineRegisterInfo &RegInfo = F->getRegInfo();
12249     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12250 
12251     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12252 
12253     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12254     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12255 
12256     // The first operand of INSERT_SUBREG should be a register which has
12257     // subregisters, we only care about its RegClass, so we should use an
12258     // IMPLICIT_DEF register.
12259     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12260     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12261       .addReg(ImDefReg)
12262       .add(SrcOp)
12263       .addImm(1);
12264 
12265     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12266     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12267       .addReg(OldFPSCRTmpReg)
12268       .addReg(ExtSrcReg)
12269       .addImm(0)
12270       .addImm(62);
12271 
12272     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12273     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12274 
12275     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12276     // bits of FPSCR.
12277     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12278       .addImm(255)
12279       .addReg(NewFPSCRReg)
12280       .addImm(0)
12281       .addImm(0);
12282   } else {
12283     llvm_unreachable("Unexpected instr type to insert");
12284   }
12285 
12286   MI.eraseFromParent(); // The pseudo instruction is gone now.
12287   return BB;
12288 }
12289 
12290 //===----------------------------------------------------------------------===//
12291 // Target Optimization Hooks
12292 //===----------------------------------------------------------------------===//
12293 
12294 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12295   // For the estimates, convergence is quadratic, so we essentially double the
12296   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12297   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12298   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12299   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12300   if (VT.getScalarType() == MVT::f64)
12301     RefinementSteps++;
12302   return RefinementSteps;
12303 }
12304 
12305 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12306                                            int Enabled, int &RefinementSteps,
12307                                            bool &UseOneConstNR,
12308                                            bool Reciprocal) const {
12309   EVT VT = Operand.getValueType();
12310   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12311       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12312       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12313       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12314       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12315       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12316     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12317       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12318 
12319     // The Newton-Raphson computation with a single constant does not provide
12320     // enough accuracy on some CPUs.
12321     UseOneConstNR = !Subtarget.needsTwoConstNR();
12322     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12323   }
12324   return SDValue();
12325 }
12326 
12327 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12328                                             int Enabled,
12329                                             int &RefinementSteps) const {
12330   EVT VT = Operand.getValueType();
12331   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12332       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12333       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12334       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12335       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12336       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12337     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12338       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12339     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12340   }
12341   return SDValue();
12342 }
12343 
12344 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12345   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12346   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12347   // enabled for division), this functionality is redundant with the default
12348   // combiner logic (once the division -> reciprocal/multiply transformation
12349   // has taken place). As a result, this matters more for older cores than for
12350   // newer ones.
12351 
12352   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12353   // reciprocal if there are two or more FDIVs (for embedded cores with only
12354   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12355   switch (Subtarget.getCPUDirective()) {
12356   default:
12357     return 3;
12358   case PPC::DIR_440:
12359   case PPC::DIR_A2:
12360   case PPC::DIR_E500:
12361   case PPC::DIR_E500mc:
12362   case PPC::DIR_E5500:
12363     return 2;
12364   }
12365 }
12366 
12367 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12368 // collapsed, and so we need to look through chains of them.
12369 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12370                                      int64_t& Offset, SelectionDAG &DAG) {
12371   if (DAG.isBaseWithConstantOffset(Loc)) {
12372     Base = Loc.getOperand(0);
12373     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12374 
12375     // The base might itself be a base plus an offset, and if so, accumulate
12376     // that as well.
12377     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12378   }
12379 }
12380 
12381 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12382                             unsigned Bytes, int Dist,
12383                             SelectionDAG &DAG) {
12384   if (VT.getSizeInBits() / 8 != Bytes)
12385     return false;
12386 
12387   SDValue BaseLoc = Base->getBasePtr();
12388   if (Loc.getOpcode() == ISD::FrameIndex) {
12389     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12390       return false;
12391     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12392     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12393     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12394     int FS  = MFI.getObjectSize(FI);
12395     int BFS = MFI.getObjectSize(BFI);
12396     if (FS != BFS || FS != (int)Bytes) return false;
12397     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12398   }
12399 
12400   SDValue Base1 = Loc, Base2 = BaseLoc;
12401   int64_t Offset1 = 0, Offset2 = 0;
12402   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12403   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12404   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12405     return true;
12406 
12407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12408   const GlobalValue *GV1 = nullptr;
12409   const GlobalValue *GV2 = nullptr;
12410   Offset1 = 0;
12411   Offset2 = 0;
12412   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12413   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12414   if (isGA1 && isGA2 && GV1 == GV2)
12415     return Offset1 == (Offset2 + Dist*Bytes);
12416   return false;
12417 }
12418 
12419 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12420 // not enforce equality of the chain operands.
12421 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12422                             unsigned Bytes, int Dist,
12423                             SelectionDAG &DAG) {
12424   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12425     EVT VT = LS->getMemoryVT();
12426     SDValue Loc = LS->getBasePtr();
12427     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12428   }
12429 
12430   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12431     EVT VT;
12432     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12433     default: return false;
12434     case Intrinsic::ppc_qpx_qvlfd:
12435     case Intrinsic::ppc_qpx_qvlfda:
12436       VT = MVT::v4f64;
12437       break;
12438     case Intrinsic::ppc_qpx_qvlfs:
12439     case Intrinsic::ppc_qpx_qvlfsa:
12440       VT = MVT::v4f32;
12441       break;
12442     case Intrinsic::ppc_qpx_qvlfcd:
12443     case Intrinsic::ppc_qpx_qvlfcda:
12444       VT = MVT::v2f64;
12445       break;
12446     case Intrinsic::ppc_qpx_qvlfcs:
12447     case Intrinsic::ppc_qpx_qvlfcsa:
12448       VT = MVT::v2f32;
12449       break;
12450     case Intrinsic::ppc_qpx_qvlfiwa:
12451     case Intrinsic::ppc_qpx_qvlfiwz:
12452     case Intrinsic::ppc_altivec_lvx:
12453     case Intrinsic::ppc_altivec_lvxl:
12454     case Intrinsic::ppc_vsx_lxvw4x:
12455     case Intrinsic::ppc_vsx_lxvw4x_be:
12456       VT = MVT::v4i32;
12457       break;
12458     case Intrinsic::ppc_vsx_lxvd2x:
12459     case Intrinsic::ppc_vsx_lxvd2x_be:
12460       VT = MVT::v2f64;
12461       break;
12462     case Intrinsic::ppc_altivec_lvebx:
12463       VT = MVT::i8;
12464       break;
12465     case Intrinsic::ppc_altivec_lvehx:
12466       VT = MVT::i16;
12467       break;
12468     case Intrinsic::ppc_altivec_lvewx:
12469       VT = MVT::i32;
12470       break;
12471     }
12472 
12473     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12474   }
12475 
12476   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12477     EVT VT;
12478     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12479     default: return false;
12480     case Intrinsic::ppc_qpx_qvstfd:
12481     case Intrinsic::ppc_qpx_qvstfda:
12482       VT = MVT::v4f64;
12483       break;
12484     case Intrinsic::ppc_qpx_qvstfs:
12485     case Intrinsic::ppc_qpx_qvstfsa:
12486       VT = MVT::v4f32;
12487       break;
12488     case Intrinsic::ppc_qpx_qvstfcd:
12489     case Intrinsic::ppc_qpx_qvstfcda:
12490       VT = MVT::v2f64;
12491       break;
12492     case Intrinsic::ppc_qpx_qvstfcs:
12493     case Intrinsic::ppc_qpx_qvstfcsa:
12494       VT = MVT::v2f32;
12495       break;
12496     case Intrinsic::ppc_qpx_qvstfiw:
12497     case Intrinsic::ppc_qpx_qvstfiwa:
12498     case Intrinsic::ppc_altivec_stvx:
12499     case Intrinsic::ppc_altivec_stvxl:
12500     case Intrinsic::ppc_vsx_stxvw4x:
12501       VT = MVT::v4i32;
12502       break;
12503     case Intrinsic::ppc_vsx_stxvd2x:
12504       VT = MVT::v2f64;
12505       break;
12506     case Intrinsic::ppc_vsx_stxvw4x_be:
12507       VT = MVT::v4i32;
12508       break;
12509     case Intrinsic::ppc_vsx_stxvd2x_be:
12510       VT = MVT::v2f64;
12511       break;
12512     case Intrinsic::ppc_altivec_stvebx:
12513       VT = MVT::i8;
12514       break;
12515     case Intrinsic::ppc_altivec_stvehx:
12516       VT = MVT::i16;
12517       break;
12518     case Intrinsic::ppc_altivec_stvewx:
12519       VT = MVT::i32;
12520       break;
12521     }
12522 
12523     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12524   }
12525 
12526   return false;
12527 }
12528 
12529 // Return true is there is a nearyby consecutive load to the one provided
12530 // (regardless of alignment). We search up and down the chain, looking though
12531 // token factors and other loads (but nothing else). As a result, a true result
12532 // indicates that it is safe to create a new consecutive load adjacent to the
12533 // load provided.
12534 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12535   SDValue Chain = LD->getChain();
12536   EVT VT = LD->getMemoryVT();
12537 
12538   SmallSet<SDNode *, 16> LoadRoots;
12539   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12540   SmallSet<SDNode *, 16> Visited;
12541 
12542   // First, search up the chain, branching to follow all token-factor operands.
12543   // If we find a consecutive load, then we're done, otherwise, record all
12544   // nodes just above the top-level loads and token factors.
12545   while (!Queue.empty()) {
12546     SDNode *ChainNext = Queue.pop_back_val();
12547     if (!Visited.insert(ChainNext).second)
12548       continue;
12549 
12550     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12551       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12552         return true;
12553 
12554       if (!Visited.count(ChainLD->getChain().getNode()))
12555         Queue.push_back(ChainLD->getChain().getNode());
12556     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12557       for (const SDUse &O : ChainNext->ops())
12558         if (!Visited.count(O.getNode()))
12559           Queue.push_back(O.getNode());
12560     } else
12561       LoadRoots.insert(ChainNext);
12562   }
12563 
12564   // Second, search down the chain, starting from the top-level nodes recorded
12565   // in the first phase. These top-level nodes are the nodes just above all
12566   // loads and token factors. Starting with their uses, recursively look though
12567   // all loads (just the chain uses) and token factors to find a consecutive
12568   // load.
12569   Visited.clear();
12570   Queue.clear();
12571 
12572   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12573        IE = LoadRoots.end(); I != IE; ++I) {
12574     Queue.push_back(*I);
12575 
12576     while (!Queue.empty()) {
12577       SDNode *LoadRoot = Queue.pop_back_val();
12578       if (!Visited.insert(LoadRoot).second)
12579         continue;
12580 
12581       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12582         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12583           return true;
12584 
12585       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12586            UE = LoadRoot->use_end(); UI != UE; ++UI)
12587         if (((isa<MemSDNode>(*UI) &&
12588             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12589             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12590           Queue.push_back(*UI);
12591     }
12592   }
12593 
12594   return false;
12595 }
12596 
12597 /// This function is called when we have proved that a SETCC node can be replaced
12598 /// by subtraction (and other supporting instructions) so that the result of
12599 /// comparison is kept in a GPR instead of CR. This function is purely for
12600 /// codegen purposes and has some flags to guide the codegen process.
12601 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12602                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12603   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12604 
12605   // Zero extend the operands to the largest legal integer. Originally, they
12606   // must be of a strictly smaller size.
12607   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12608                          DAG.getConstant(Size, DL, MVT::i32));
12609   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12610                          DAG.getConstant(Size, DL, MVT::i32));
12611 
12612   // Swap if needed. Depends on the condition code.
12613   if (Swap)
12614     std::swap(Op0, Op1);
12615 
12616   // Subtract extended integers.
12617   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12618 
12619   // Move the sign bit to the least significant position and zero out the rest.
12620   // Now the least significant bit carries the result of original comparison.
12621   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12622                              DAG.getConstant(Size - 1, DL, MVT::i32));
12623   auto Final = Shifted;
12624 
12625   // Complement the result if needed. Based on the condition code.
12626   if (Complement)
12627     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12628                         DAG.getConstant(1, DL, MVT::i64));
12629 
12630   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12631 }
12632 
12633 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12634                                                   DAGCombinerInfo &DCI) const {
12635   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12636 
12637   SelectionDAG &DAG = DCI.DAG;
12638   SDLoc DL(N);
12639 
12640   // Size of integers being compared has a critical role in the following
12641   // analysis, so we prefer to do this when all types are legal.
12642   if (!DCI.isAfterLegalizeDAG())
12643     return SDValue();
12644 
12645   // If all users of SETCC extend its value to a legal integer type
12646   // then we replace SETCC with a subtraction
12647   for (SDNode::use_iterator UI = N->use_begin(),
12648        UE = N->use_end(); UI != UE; ++UI) {
12649     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12650       return SDValue();
12651   }
12652 
12653   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12654   auto OpSize = N->getOperand(0).getValueSizeInBits();
12655 
12656   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12657 
12658   if (OpSize < Size) {
12659     switch (CC) {
12660     default: break;
12661     case ISD::SETULT:
12662       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12663     case ISD::SETULE:
12664       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12665     case ISD::SETUGT:
12666       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12667     case ISD::SETUGE:
12668       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12669     }
12670   }
12671 
12672   return SDValue();
12673 }
12674 
12675 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12676                                                   DAGCombinerInfo &DCI) const {
12677   SelectionDAG &DAG = DCI.DAG;
12678   SDLoc dl(N);
12679 
12680   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12681   // If we're tracking CR bits, we need to be careful that we don't have:
12682   //   trunc(binary-ops(zext(x), zext(y)))
12683   // or
12684   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12685   // such that we're unnecessarily moving things into GPRs when it would be
12686   // better to keep them in CR bits.
12687 
12688   // Note that trunc here can be an actual i1 trunc, or can be the effective
12689   // truncation that comes from a setcc or select_cc.
12690   if (N->getOpcode() == ISD::TRUNCATE &&
12691       N->getValueType(0) != MVT::i1)
12692     return SDValue();
12693 
12694   if (N->getOperand(0).getValueType() != MVT::i32 &&
12695       N->getOperand(0).getValueType() != MVT::i64)
12696     return SDValue();
12697 
12698   if (N->getOpcode() == ISD::SETCC ||
12699       N->getOpcode() == ISD::SELECT_CC) {
12700     // If we're looking at a comparison, then we need to make sure that the
12701     // high bits (all except for the first) don't matter the result.
12702     ISD::CondCode CC =
12703       cast<CondCodeSDNode>(N->getOperand(
12704         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12705     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12706 
12707     if (ISD::isSignedIntSetCC(CC)) {
12708       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12709           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12710         return SDValue();
12711     } else if (ISD::isUnsignedIntSetCC(CC)) {
12712       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12713                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12714           !DAG.MaskedValueIsZero(N->getOperand(1),
12715                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12716         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12717                                              : SDValue());
12718     } else {
12719       // This is neither a signed nor an unsigned comparison, just make sure
12720       // that the high bits are equal.
12721       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12722       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12723 
12724       // We don't really care about what is known about the first bit (if
12725       // anything), so clear it in all masks prior to comparing them.
12726       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12727       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12728 
12729       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12730         return SDValue();
12731     }
12732   }
12733 
12734   // We now know that the higher-order bits are irrelevant, we just need to
12735   // make sure that all of the intermediate operations are bit operations, and
12736   // all inputs are extensions.
12737   if (N->getOperand(0).getOpcode() != ISD::AND &&
12738       N->getOperand(0).getOpcode() != ISD::OR  &&
12739       N->getOperand(0).getOpcode() != ISD::XOR &&
12740       N->getOperand(0).getOpcode() != ISD::SELECT &&
12741       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12742       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12743       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12744       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12745       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12746     return SDValue();
12747 
12748   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12749       N->getOperand(1).getOpcode() != ISD::AND &&
12750       N->getOperand(1).getOpcode() != ISD::OR  &&
12751       N->getOperand(1).getOpcode() != ISD::XOR &&
12752       N->getOperand(1).getOpcode() != ISD::SELECT &&
12753       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12754       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12755       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12756       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12757       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12758     return SDValue();
12759 
12760   SmallVector<SDValue, 4> Inputs;
12761   SmallVector<SDValue, 8> BinOps, PromOps;
12762   SmallPtrSet<SDNode *, 16> Visited;
12763 
12764   for (unsigned i = 0; i < 2; ++i) {
12765     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12766           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12767           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12768           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12769         isa<ConstantSDNode>(N->getOperand(i)))
12770       Inputs.push_back(N->getOperand(i));
12771     else
12772       BinOps.push_back(N->getOperand(i));
12773 
12774     if (N->getOpcode() == ISD::TRUNCATE)
12775       break;
12776   }
12777 
12778   // Visit all inputs, collect all binary operations (and, or, xor and
12779   // select) that are all fed by extensions.
12780   while (!BinOps.empty()) {
12781     SDValue BinOp = BinOps.back();
12782     BinOps.pop_back();
12783 
12784     if (!Visited.insert(BinOp.getNode()).second)
12785       continue;
12786 
12787     PromOps.push_back(BinOp);
12788 
12789     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12790       // The condition of the select is not promoted.
12791       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12792         continue;
12793       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12794         continue;
12795 
12796       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12797             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12798             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12799            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12800           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12801         Inputs.push_back(BinOp.getOperand(i));
12802       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12803                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12804                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12805                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12806                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12807                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12808                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12809                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12810                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12811         BinOps.push_back(BinOp.getOperand(i));
12812       } else {
12813         // We have an input that is not an extension or another binary
12814         // operation; we'll abort this transformation.
12815         return SDValue();
12816       }
12817     }
12818   }
12819 
12820   // Make sure that this is a self-contained cluster of operations (which
12821   // is not quite the same thing as saying that everything has only one
12822   // use).
12823   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12824     if (isa<ConstantSDNode>(Inputs[i]))
12825       continue;
12826 
12827     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12828                               UE = Inputs[i].getNode()->use_end();
12829          UI != UE; ++UI) {
12830       SDNode *User = *UI;
12831       if (User != N && !Visited.count(User))
12832         return SDValue();
12833 
12834       // Make sure that we're not going to promote the non-output-value
12835       // operand(s) or SELECT or SELECT_CC.
12836       // FIXME: Although we could sometimes handle this, and it does occur in
12837       // practice that one of the condition inputs to the select is also one of
12838       // the outputs, we currently can't deal with this.
12839       if (User->getOpcode() == ISD::SELECT) {
12840         if (User->getOperand(0) == Inputs[i])
12841           return SDValue();
12842       } else if (User->getOpcode() == ISD::SELECT_CC) {
12843         if (User->getOperand(0) == Inputs[i] ||
12844             User->getOperand(1) == Inputs[i])
12845           return SDValue();
12846       }
12847     }
12848   }
12849 
12850   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12851     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12852                               UE = PromOps[i].getNode()->use_end();
12853          UI != UE; ++UI) {
12854       SDNode *User = *UI;
12855       if (User != N && !Visited.count(User))
12856         return SDValue();
12857 
12858       // Make sure that we're not going to promote the non-output-value
12859       // operand(s) or SELECT or SELECT_CC.
12860       // FIXME: Although we could sometimes handle this, and it does occur in
12861       // practice that one of the condition inputs to the select is also one of
12862       // the outputs, we currently can't deal with this.
12863       if (User->getOpcode() == ISD::SELECT) {
12864         if (User->getOperand(0) == PromOps[i])
12865           return SDValue();
12866       } else if (User->getOpcode() == ISD::SELECT_CC) {
12867         if (User->getOperand(0) == PromOps[i] ||
12868             User->getOperand(1) == PromOps[i])
12869           return SDValue();
12870       }
12871     }
12872   }
12873 
12874   // Replace all inputs with the extension operand.
12875   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12876     // Constants may have users outside the cluster of to-be-promoted nodes,
12877     // and so we need to replace those as we do the promotions.
12878     if (isa<ConstantSDNode>(Inputs[i]))
12879       continue;
12880     else
12881       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12882   }
12883 
12884   std::list<HandleSDNode> PromOpHandles;
12885   for (auto &PromOp : PromOps)
12886     PromOpHandles.emplace_back(PromOp);
12887 
12888   // Replace all operations (these are all the same, but have a different
12889   // (i1) return type). DAG.getNode will validate that the types of
12890   // a binary operator match, so go through the list in reverse so that
12891   // we've likely promoted both operands first. Any intermediate truncations or
12892   // extensions disappear.
12893   while (!PromOpHandles.empty()) {
12894     SDValue PromOp = PromOpHandles.back().getValue();
12895     PromOpHandles.pop_back();
12896 
12897     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12898         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12899         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12900         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12901       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12902           PromOp.getOperand(0).getValueType() != MVT::i1) {
12903         // The operand is not yet ready (see comment below).
12904         PromOpHandles.emplace_front(PromOp);
12905         continue;
12906       }
12907 
12908       SDValue RepValue = PromOp.getOperand(0);
12909       if (isa<ConstantSDNode>(RepValue))
12910         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12911 
12912       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12913       continue;
12914     }
12915 
12916     unsigned C;
12917     switch (PromOp.getOpcode()) {
12918     default:             C = 0; break;
12919     case ISD::SELECT:    C = 1; break;
12920     case ISD::SELECT_CC: C = 2; break;
12921     }
12922 
12923     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12924          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12925         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12926          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12927       // The to-be-promoted operands of this node have not yet been
12928       // promoted (this should be rare because we're going through the
12929       // list backward, but if one of the operands has several users in
12930       // this cluster of to-be-promoted nodes, it is possible).
12931       PromOpHandles.emplace_front(PromOp);
12932       continue;
12933     }
12934 
12935     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12936                                 PromOp.getNode()->op_end());
12937 
12938     // If there are any constant inputs, make sure they're replaced now.
12939     for (unsigned i = 0; i < 2; ++i)
12940       if (isa<ConstantSDNode>(Ops[C+i]))
12941         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12942 
12943     DAG.ReplaceAllUsesOfValueWith(PromOp,
12944       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12945   }
12946 
12947   // Now we're left with the initial truncation itself.
12948   if (N->getOpcode() == ISD::TRUNCATE)
12949     return N->getOperand(0);
12950 
12951   // Otherwise, this is a comparison. The operands to be compared have just
12952   // changed type (to i1), but everything else is the same.
12953   return SDValue(N, 0);
12954 }
12955 
12956 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12957                                                   DAGCombinerInfo &DCI) const {
12958   SelectionDAG &DAG = DCI.DAG;
12959   SDLoc dl(N);
12960 
12961   // If we're tracking CR bits, we need to be careful that we don't have:
12962   //   zext(binary-ops(trunc(x), trunc(y)))
12963   // or
12964   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12965   // such that we're unnecessarily moving things into CR bits that can more
12966   // efficiently stay in GPRs. Note that if we're not certain that the high
12967   // bits are set as required by the final extension, we still may need to do
12968   // some masking to get the proper behavior.
12969 
12970   // This same functionality is important on PPC64 when dealing with
12971   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12972   // the return values of functions. Because it is so similar, it is handled
12973   // here as well.
12974 
12975   if (N->getValueType(0) != MVT::i32 &&
12976       N->getValueType(0) != MVT::i64)
12977     return SDValue();
12978 
12979   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12980         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12981     return SDValue();
12982 
12983   if (N->getOperand(0).getOpcode() != ISD::AND &&
12984       N->getOperand(0).getOpcode() != ISD::OR  &&
12985       N->getOperand(0).getOpcode() != ISD::XOR &&
12986       N->getOperand(0).getOpcode() != ISD::SELECT &&
12987       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12988     return SDValue();
12989 
12990   SmallVector<SDValue, 4> Inputs;
12991   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12992   SmallPtrSet<SDNode *, 16> Visited;
12993 
12994   // Visit all inputs, collect all binary operations (and, or, xor and
12995   // select) that are all fed by truncations.
12996   while (!BinOps.empty()) {
12997     SDValue BinOp = BinOps.back();
12998     BinOps.pop_back();
12999 
13000     if (!Visited.insert(BinOp.getNode()).second)
13001       continue;
13002 
13003     PromOps.push_back(BinOp);
13004 
13005     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13006       // The condition of the select is not promoted.
13007       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13008         continue;
13009       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13010         continue;
13011 
13012       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13013           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13014         Inputs.push_back(BinOp.getOperand(i));
13015       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13016                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13017                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13018                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13019                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13020         BinOps.push_back(BinOp.getOperand(i));
13021       } else {
13022         // We have an input that is not a truncation or another binary
13023         // operation; we'll abort this transformation.
13024         return SDValue();
13025       }
13026     }
13027   }
13028 
13029   // The operands of a select that must be truncated when the select is
13030   // promoted because the operand is actually part of the to-be-promoted set.
13031   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13032 
13033   // Make sure that this is a self-contained cluster of operations (which
13034   // is not quite the same thing as saying that everything has only one
13035   // use).
13036   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13037     if (isa<ConstantSDNode>(Inputs[i]))
13038       continue;
13039 
13040     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13041                               UE = Inputs[i].getNode()->use_end();
13042          UI != UE; ++UI) {
13043       SDNode *User = *UI;
13044       if (User != N && !Visited.count(User))
13045         return SDValue();
13046 
13047       // If we're going to promote the non-output-value operand(s) or SELECT or
13048       // SELECT_CC, record them for truncation.
13049       if (User->getOpcode() == ISD::SELECT) {
13050         if (User->getOperand(0) == Inputs[i])
13051           SelectTruncOp[0].insert(std::make_pair(User,
13052                                     User->getOperand(0).getValueType()));
13053       } else if (User->getOpcode() == ISD::SELECT_CC) {
13054         if (User->getOperand(0) == Inputs[i])
13055           SelectTruncOp[0].insert(std::make_pair(User,
13056                                     User->getOperand(0).getValueType()));
13057         if (User->getOperand(1) == Inputs[i])
13058           SelectTruncOp[1].insert(std::make_pair(User,
13059                                     User->getOperand(1).getValueType()));
13060       }
13061     }
13062   }
13063 
13064   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13065     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13066                               UE = PromOps[i].getNode()->use_end();
13067          UI != UE; ++UI) {
13068       SDNode *User = *UI;
13069       if (User != N && !Visited.count(User))
13070         return SDValue();
13071 
13072       // If we're going to promote the non-output-value operand(s) or SELECT or
13073       // SELECT_CC, record them for truncation.
13074       if (User->getOpcode() == ISD::SELECT) {
13075         if (User->getOperand(0) == PromOps[i])
13076           SelectTruncOp[0].insert(std::make_pair(User,
13077                                     User->getOperand(0).getValueType()));
13078       } else if (User->getOpcode() == ISD::SELECT_CC) {
13079         if (User->getOperand(0) == PromOps[i])
13080           SelectTruncOp[0].insert(std::make_pair(User,
13081                                     User->getOperand(0).getValueType()));
13082         if (User->getOperand(1) == PromOps[i])
13083           SelectTruncOp[1].insert(std::make_pair(User,
13084                                     User->getOperand(1).getValueType()));
13085       }
13086     }
13087   }
13088 
13089   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13090   bool ReallyNeedsExt = false;
13091   if (N->getOpcode() != ISD::ANY_EXTEND) {
13092     // If all of the inputs are not already sign/zero extended, then
13093     // we'll still need to do that at the end.
13094     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13095       if (isa<ConstantSDNode>(Inputs[i]))
13096         continue;
13097 
13098       unsigned OpBits =
13099         Inputs[i].getOperand(0).getValueSizeInBits();
13100       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13101 
13102       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13103            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13104                                   APInt::getHighBitsSet(OpBits,
13105                                                         OpBits-PromBits))) ||
13106           (N->getOpcode() == ISD::SIGN_EXTEND &&
13107            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13108              (OpBits-(PromBits-1)))) {
13109         ReallyNeedsExt = true;
13110         break;
13111       }
13112     }
13113   }
13114 
13115   // Replace all inputs, either with the truncation operand, or a
13116   // truncation or extension to the final output type.
13117   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13118     // Constant inputs need to be replaced with the to-be-promoted nodes that
13119     // use them because they might have users outside of the cluster of
13120     // promoted nodes.
13121     if (isa<ConstantSDNode>(Inputs[i]))
13122       continue;
13123 
13124     SDValue InSrc = Inputs[i].getOperand(0);
13125     if (Inputs[i].getValueType() == N->getValueType(0))
13126       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13127     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13128       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13129         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13130     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13131       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13132         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13133     else
13134       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13135         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13136   }
13137 
13138   std::list<HandleSDNode> PromOpHandles;
13139   for (auto &PromOp : PromOps)
13140     PromOpHandles.emplace_back(PromOp);
13141 
13142   // Replace all operations (these are all the same, but have a different
13143   // (promoted) return type). DAG.getNode will validate that the types of
13144   // a binary operator match, so go through the list in reverse so that
13145   // we've likely promoted both operands first.
13146   while (!PromOpHandles.empty()) {
13147     SDValue PromOp = PromOpHandles.back().getValue();
13148     PromOpHandles.pop_back();
13149 
13150     unsigned C;
13151     switch (PromOp.getOpcode()) {
13152     default:             C = 0; break;
13153     case ISD::SELECT:    C = 1; break;
13154     case ISD::SELECT_CC: C = 2; break;
13155     }
13156 
13157     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13158          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13159         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13160          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13161       // The to-be-promoted operands of this node have not yet been
13162       // promoted (this should be rare because we're going through the
13163       // list backward, but if one of the operands has several users in
13164       // this cluster of to-be-promoted nodes, it is possible).
13165       PromOpHandles.emplace_front(PromOp);
13166       continue;
13167     }
13168 
13169     // For SELECT and SELECT_CC nodes, we do a similar check for any
13170     // to-be-promoted comparison inputs.
13171     if (PromOp.getOpcode() == ISD::SELECT ||
13172         PromOp.getOpcode() == ISD::SELECT_CC) {
13173       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13174            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13175           (SelectTruncOp[1].count(PromOp.getNode()) &&
13176            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13177         PromOpHandles.emplace_front(PromOp);
13178         continue;
13179       }
13180     }
13181 
13182     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13183                                 PromOp.getNode()->op_end());
13184 
13185     // If this node has constant inputs, then they'll need to be promoted here.
13186     for (unsigned i = 0; i < 2; ++i) {
13187       if (!isa<ConstantSDNode>(Ops[C+i]))
13188         continue;
13189       if (Ops[C+i].getValueType() == N->getValueType(0))
13190         continue;
13191 
13192       if (N->getOpcode() == ISD::SIGN_EXTEND)
13193         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13194       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13195         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13196       else
13197         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13198     }
13199 
13200     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13201     // truncate them again to the original value type.
13202     if (PromOp.getOpcode() == ISD::SELECT ||
13203         PromOp.getOpcode() == ISD::SELECT_CC) {
13204       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13205       if (SI0 != SelectTruncOp[0].end())
13206         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13207       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13208       if (SI1 != SelectTruncOp[1].end())
13209         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13210     }
13211 
13212     DAG.ReplaceAllUsesOfValueWith(PromOp,
13213       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13214   }
13215 
13216   // Now we're left with the initial extension itself.
13217   if (!ReallyNeedsExt)
13218     return N->getOperand(0);
13219 
13220   // To zero extend, just mask off everything except for the first bit (in the
13221   // i1 case).
13222   if (N->getOpcode() == ISD::ZERO_EXTEND)
13223     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13224                        DAG.getConstant(APInt::getLowBitsSet(
13225                                          N->getValueSizeInBits(0), PromBits),
13226                                        dl, N->getValueType(0)));
13227 
13228   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13229          "Invalid extension type");
13230   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13231   SDValue ShiftCst =
13232       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13233   return DAG.getNode(
13234       ISD::SRA, dl, N->getValueType(0),
13235       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13236       ShiftCst);
13237 }
13238 
13239 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13240                                         DAGCombinerInfo &DCI) const {
13241   assert(N->getOpcode() == ISD::SETCC &&
13242          "Should be called with a SETCC node");
13243 
13244   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13245   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13246     SDValue LHS = N->getOperand(0);
13247     SDValue RHS = N->getOperand(1);
13248 
13249     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13250     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13251         LHS.hasOneUse())
13252       std::swap(LHS, RHS);
13253 
13254     // x == 0-y --> x+y == 0
13255     // x != 0-y --> x+y != 0
13256     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13257         RHS.hasOneUse()) {
13258       SDLoc DL(N);
13259       SelectionDAG &DAG = DCI.DAG;
13260       EVT VT = N->getValueType(0);
13261       EVT OpVT = LHS.getValueType();
13262       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13263       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13264     }
13265   }
13266 
13267   return DAGCombineTruncBoolExt(N, DCI);
13268 }
13269 
13270 // Is this an extending load from an f32 to an f64?
13271 static bool isFPExtLoad(SDValue Op) {
13272   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13273     return LD->getExtensionType() == ISD::EXTLOAD &&
13274       Op.getValueType() == MVT::f64;
13275   return false;
13276 }
13277 
13278 /// Reduces the number of fp-to-int conversion when building a vector.
13279 ///
13280 /// If this vector is built out of floating to integer conversions,
13281 /// transform it to a vector built out of floating point values followed by a
13282 /// single floating to integer conversion of the vector.
13283 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13284 /// becomes (fptosi (build_vector ($A, $B, ...)))
13285 SDValue PPCTargetLowering::
13286 combineElementTruncationToVectorTruncation(SDNode *N,
13287                                            DAGCombinerInfo &DCI) const {
13288   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13289          "Should be called with a BUILD_VECTOR node");
13290 
13291   SelectionDAG &DAG = DCI.DAG;
13292   SDLoc dl(N);
13293 
13294   SDValue FirstInput = N->getOperand(0);
13295   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13296          "The input operand must be an fp-to-int conversion.");
13297 
13298   // This combine happens after legalization so the fp_to_[su]i nodes are
13299   // already converted to PPCSISD nodes.
13300   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13301   if (FirstConversion == PPCISD::FCTIDZ ||
13302       FirstConversion == PPCISD::FCTIDUZ ||
13303       FirstConversion == PPCISD::FCTIWZ ||
13304       FirstConversion == PPCISD::FCTIWUZ) {
13305     bool IsSplat = true;
13306     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13307       FirstConversion == PPCISD::FCTIWUZ;
13308     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13309     SmallVector<SDValue, 4> Ops;
13310     EVT TargetVT = N->getValueType(0);
13311     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13312       SDValue NextOp = N->getOperand(i);
13313       if (NextOp.getOpcode() != PPCISD::MFVSR)
13314         return SDValue();
13315       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13316       if (NextConversion != FirstConversion)
13317         return SDValue();
13318       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13319       // This is not valid if the input was originally double precision. It is
13320       // also not profitable to do unless this is an extending load in which
13321       // case doing this combine will allow us to combine consecutive loads.
13322       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13323         return SDValue();
13324       if (N->getOperand(i) != FirstInput)
13325         IsSplat = false;
13326     }
13327 
13328     // If this is a splat, we leave it as-is since there will be only a single
13329     // fp-to-int conversion followed by a splat of the integer. This is better
13330     // for 32-bit and smaller ints and neutral for 64-bit ints.
13331     if (IsSplat)
13332       return SDValue();
13333 
13334     // Now that we know we have the right type of node, get its operands
13335     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13336       SDValue In = N->getOperand(i).getOperand(0);
13337       if (Is32Bit) {
13338         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13339         // here, we know that all inputs are extending loads so this is safe).
13340         if (In.isUndef())
13341           Ops.push_back(DAG.getUNDEF(SrcVT));
13342         else {
13343           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13344                                       MVT::f32, In.getOperand(0),
13345                                       DAG.getIntPtrConstant(1, dl));
13346           Ops.push_back(Trunc);
13347         }
13348       } else
13349         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13350     }
13351 
13352     unsigned Opcode;
13353     if (FirstConversion == PPCISD::FCTIDZ ||
13354         FirstConversion == PPCISD::FCTIWZ)
13355       Opcode = ISD::FP_TO_SINT;
13356     else
13357       Opcode = ISD::FP_TO_UINT;
13358 
13359     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13360     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13361     return DAG.getNode(Opcode, dl, TargetVT, BV);
13362   }
13363   return SDValue();
13364 }
13365 
13366 /// Reduce the number of loads when building a vector.
13367 ///
13368 /// Building a vector out of multiple loads can be converted to a load
13369 /// of the vector type if the loads are consecutive. If the loads are
13370 /// consecutive but in descending order, a shuffle is added at the end
13371 /// to reorder the vector.
13372 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13373   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13374          "Should be called with a BUILD_VECTOR node");
13375 
13376   SDLoc dl(N);
13377 
13378   // Return early for non byte-sized type, as they can't be consecutive.
13379   if (!N->getValueType(0).getVectorElementType().isByteSized())
13380     return SDValue();
13381 
13382   bool InputsAreConsecutiveLoads = true;
13383   bool InputsAreReverseConsecutive = true;
13384   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13385   SDValue FirstInput = N->getOperand(0);
13386   bool IsRoundOfExtLoad = false;
13387 
13388   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13389       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13390     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13391     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13392   }
13393   // Not a build vector of (possibly fp_rounded) loads.
13394   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13395       N->getNumOperands() == 1)
13396     return SDValue();
13397 
13398   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13399     // If any inputs are fp_round(extload), they all must be.
13400     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13401       return SDValue();
13402 
13403     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13404       N->getOperand(i);
13405     if (NextInput.getOpcode() != ISD::LOAD)
13406       return SDValue();
13407 
13408     SDValue PreviousInput =
13409       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13410     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13411     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13412 
13413     // If any inputs are fp_round(extload), they all must be.
13414     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13415       return SDValue();
13416 
13417     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13418       InputsAreConsecutiveLoads = false;
13419     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13420       InputsAreReverseConsecutive = false;
13421 
13422     // Exit early if the loads are neither consecutive nor reverse consecutive.
13423     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13424       return SDValue();
13425   }
13426 
13427   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13428          "The loads cannot be both consecutive and reverse consecutive.");
13429 
13430   SDValue FirstLoadOp =
13431     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13432   SDValue LastLoadOp =
13433     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13434                        N->getOperand(N->getNumOperands()-1);
13435 
13436   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13437   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13438   if (InputsAreConsecutiveLoads) {
13439     assert(LD1 && "Input needs to be a LoadSDNode.");
13440     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13441                        LD1->getBasePtr(), LD1->getPointerInfo(),
13442                        LD1->getAlignment());
13443   }
13444   if (InputsAreReverseConsecutive) {
13445     assert(LDL && "Input needs to be a LoadSDNode.");
13446     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13447                                LDL->getBasePtr(), LDL->getPointerInfo(),
13448                                LDL->getAlignment());
13449     SmallVector<int, 16> Ops;
13450     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13451       Ops.push_back(i);
13452 
13453     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13454                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13455   }
13456   return SDValue();
13457 }
13458 
13459 // This function adds the required vector_shuffle needed to get
13460 // the elements of the vector extract in the correct position
13461 // as specified by the CorrectElems encoding.
13462 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13463                                       SDValue Input, uint64_t Elems,
13464                                       uint64_t CorrectElems) {
13465   SDLoc dl(N);
13466 
13467   unsigned NumElems = Input.getValueType().getVectorNumElements();
13468   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13469 
13470   // Knowing the element indices being extracted from the original
13471   // vector and the order in which they're being inserted, just put
13472   // them at element indices required for the instruction.
13473   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13474     if (DAG.getDataLayout().isLittleEndian())
13475       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13476     else
13477       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13478     CorrectElems = CorrectElems >> 8;
13479     Elems = Elems >> 8;
13480   }
13481 
13482   SDValue Shuffle =
13483       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13484                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13485 
13486   EVT VT = N->getValueType(0);
13487   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13488 
13489   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13490                                Input.getValueType().getVectorElementType(),
13491                                VT.getVectorNumElements());
13492   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13493                      DAG.getValueType(ExtVT));
13494 }
13495 
13496 // Look for build vector patterns where input operands come from sign
13497 // extended vector_extract elements of specific indices. If the correct indices
13498 // aren't used, add a vector shuffle to fix up the indices and create
13499 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13500 // during instruction selection.
13501 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13502   // This array encodes the indices that the vector sign extend instructions
13503   // extract from when extending from one type to another for both BE and LE.
13504   // The right nibble of each byte corresponds to the LE incides.
13505   // and the left nibble of each byte corresponds to the BE incides.
13506   // For example: 0x3074B8FC  byte->word
13507   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13508   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13509   // For example: 0x000070F8  byte->double word
13510   // For LE: the allowed indices are: 0x0,0x8
13511   // For BE: the allowed indices are: 0x7,0xF
13512   uint64_t TargetElems[] = {
13513       0x3074B8FC, // b->w
13514       0x000070F8, // b->d
13515       0x10325476, // h->w
13516       0x00003074, // h->d
13517       0x00001032, // w->d
13518   };
13519 
13520   uint64_t Elems = 0;
13521   int Index;
13522   SDValue Input;
13523 
13524   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13525     if (!Op)
13526       return false;
13527     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13528         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13529       return false;
13530 
13531     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13532     // of the right width.
13533     SDValue Extract = Op.getOperand(0);
13534     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13535       Extract = Extract.getOperand(0);
13536     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13537       return false;
13538 
13539     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13540     if (!ExtOp)
13541       return false;
13542 
13543     Index = ExtOp->getZExtValue();
13544     if (Input && Input != Extract.getOperand(0))
13545       return false;
13546 
13547     if (!Input)
13548       Input = Extract.getOperand(0);
13549 
13550     Elems = Elems << 8;
13551     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13552     Elems |= Index;
13553 
13554     return true;
13555   };
13556 
13557   // If the build vector operands aren't sign extended vector extracts,
13558   // of the same input vector, then return.
13559   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13560     if (!isSExtOfVecExtract(N->getOperand(i))) {
13561       return SDValue();
13562     }
13563   }
13564 
13565   // If the vector extract indicies are not correct, add the appropriate
13566   // vector_shuffle.
13567   int TgtElemArrayIdx;
13568   int InputSize = Input.getValueType().getScalarSizeInBits();
13569   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13570   if (InputSize + OutputSize == 40)
13571     TgtElemArrayIdx = 0;
13572   else if (InputSize + OutputSize == 72)
13573     TgtElemArrayIdx = 1;
13574   else if (InputSize + OutputSize == 48)
13575     TgtElemArrayIdx = 2;
13576   else if (InputSize + OutputSize == 80)
13577     TgtElemArrayIdx = 3;
13578   else if (InputSize + OutputSize == 96)
13579     TgtElemArrayIdx = 4;
13580   else
13581     return SDValue();
13582 
13583   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13584   CorrectElems = DAG.getDataLayout().isLittleEndian()
13585                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13586                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13587   if (Elems != CorrectElems) {
13588     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13589   }
13590 
13591   // Regular lowering will catch cases where a shuffle is not needed.
13592   return SDValue();
13593 }
13594 
13595 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13596                                                  DAGCombinerInfo &DCI) const {
13597   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13598          "Should be called with a BUILD_VECTOR node");
13599 
13600   SelectionDAG &DAG = DCI.DAG;
13601   SDLoc dl(N);
13602 
13603   if (!Subtarget.hasVSX())
13604     return SDValue();
13605 
13606   // The target independent DAG combiner will leave a build_vector of
13607   // float-to-int conversions intact. We can generate MUCH better code for
13608   // a float-to-int conversion of a vector of floats.
13609   SDValue FirstInput = N->getOperand(0);
13610   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13611     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13612     if (Reduced)
13613       return Reduced;
13614   }
13615 
13616   // If we're building a vector out of consecutive loads, just load that
13617   // vector type.
13618   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13619   if (Reduced)
13620     return Reduced;
13621 
13622   // If we're building a vector out of extended elements from another vector
13623   // we have P9 vector integer extend instructions. The code assumes legal
13624   // input types (i.e. it can't handle things like v4i16) so do not run before
13625   // legalization.
13626   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13627     Reduced = combineBVOfVecSExt(N, DAG);
13628     if (Reduced)
13629       return Reduced;
13630   }
13631 
13632 
13633   if (N->getValueType(0) != MVT::v2f64)
13634     return SDValue();
13635 
13636   // Looking for:
13637   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13638   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13639       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13640     return SDValue();
13641   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13642       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13643     return SDValue();
13644   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13645     return SDValue();
13646 
13647   SDValue Ext1 = FirstInput.getOperand(0);
13648   SDValue Ext2 = N->getOperand(1).getOperand(0);
13649   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13650      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13651     return SDValue();
13652 
13653   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13654   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13655   if (!Ext1Op || !Ext2Op)
13656     return SDValue();
13657   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13658       Ext1.getOperand(0) != Ext2.getOperand(0))
13659     return SDValue();
13660 
13661   int FirstElem = Ext1Op->getZExtValue();
13662   int SecondElem = Ext2Op->getZExtValue();
13663   int SubvecIdx;
13664   if (FirstElem == 0 && SecondElem == 1)
13665     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13666   else if (FirstElem == 2 && SecondElem == 3)
13667     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13668   else
13669     return SDValue();
13670 
13671   SDValue SrcVec = Ext1.getOperand(0);
13672   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13673     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13674   return DAG.getNode(NodeType, dl, MVT::v2f64,
13675                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13676 }
13677 
13678 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13679                                               DAGCombinerInfo &DCI) const {
13680   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13681           N->getOpcode() == ISD::UINT_TO_FP) &&
13682          "Need an int -> FP conversion node here");
13683 
13684   if (useSoftFloat() || !Subtarget.has64BitSupport())
13685     return SDValue();
13686 
13687   SelectionDAG &DAG = DCI.DAG;
13688   SDLoc dl(N);
13689   SDValue Op(N, 0);
13690 
13691   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13692   // from the hardware.
13693   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13694     return SDValue();
13695   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13696       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13697     return SDValue();
13698 
13699   SDValue FirstOperand(Op.getOperand(0));
13700   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13701     (FirstOperand.getValueType() == MVT::i8 ||
13702      FirstOperand.getValueType() == MVT::i16);
13703   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13704     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13705     bool DstDouble = Op.getValueType() == MVT::f64;
13706     unsigned ConvOp = Signed ?
13707       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13708       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13709     SDValue WidthConst =
13710       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13711                             dl, false);
13712     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13713     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13714     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13715                                          DAG.getVTList(MVT::f64, MVT::Other),
13716                                          Ops, MVT::i8, LDN->getMemOperand());
13717 
13718     // For signed conversion, we need to sign-extend the value in the VSR
13719     if (Signed) {
13720       SDValue ExtOps[] = { Ld, WidthConst };
13721       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13722       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13723     } else
13724       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13725   }
13726 
13727 
13728   // For i32 intermediate values, unfortunately, the conversion functions
13729   // leave the upper 32 bits of the value are undefined. Within the set of
13730   // scalar instructions, we have no method for zero- or sign-extending the
13731   // value. Thus, we cannot handle i32 intermediate values here.
13732   if (Op.getOperand(0).getValueType() == MVT::i32)
13733     return SDValue();
13734 
13735   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13736          "UINT_TO_FP is supported only with FPCVT");
13737 
13738   // If we have FCFIDS, then use it when converting to single-precision.
13739   // Otherwise, convert to double-precision and then round.
13740   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13741                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13742                                                             : PPCISD::FCFIDS)
13743                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13744                                                             : PPCISD::FCFID);
13745   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13746                   ? MVT::f32
13747                   : MVT::f64;
13748 
13749   // If we're converting from a float, to an int, and back to a float again,
13750   // then we don't need the store/load pair at all.
13751   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13752        Subtarget.hasFPCVT()) ||
13753       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13754     SDValue Src = Op.getOperand(0).getOperand(0);
13755     if (Src.getValueType() == MVT::f32) {
13756       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13757       DCI.AddToWorklist(Src.getNode());
13758     } else if (Src.getValueType() != MVT::f64) {
13759       // Make sure that we don't pick up a ppc_fp128 source value.
13760       return SDValue();
13761     }
13762 
13763     unsigned FCTOp =
13764       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13765                                                         PPCISD::FCTIDUZ;
13766 
13767     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13768     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13769 
13770     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13771       FP = DAG.getNode(ISD::FP_ROUND, dl,
13772                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13773       DCI.AddToWorklist(FP.getNode());
13774     }
13775 
13776     return FP;
13777   }
13778 
13779   return SDValue();
13780 }
13781 
13782 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13783 // builtins) into loads with swaps.
13784 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13785                                               DAGCombinerInfo &DCI) const {
13786   SelectionDAG &DAG = DCI.DAG;
13787   SDLoc dl(N);
13788   SDValue Chain;
13789   SDValue Base;
13790   MachineMemOperand *MMO;
13791 
13792   switch (N->getOpcode()) {
13793   default:
13794     llvm_unreachable("Unexpected opcode for little endian VSX load");
13795   case ISD::LOAD: {
13796     LoadSDNode *LD = cast<LoadSDNode>(N);
13797     Chain = LD->getChain();
13798     Base = LD->getBasePtr();
13799     MMO = LD->getMemOperand();
13800     // If the MMO suggests this isn't a load of a full vector, leave
13801     // things alone.  For a built-in, we have to make the change for
13802     // correctness, so if there is a size problem that will be a bug.
13803     if (MMO->getSize() < 16)
13804       return SDValue();
13805     break;
13806   }
13807   case ISD::INTRINSIC_W_CHAIN: {
13808     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13809     Chain = Intrin->getChain();
13810     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13811     // us what we want. Get operand 2 instead.
13812     Base = Intrin->getOperand(2);
13813     MMO = Intrin->getMemOperand();
13814     break;
13815   }
13816   }
13817 
13818   MVT VecTy = N->getValueType(0).getSimpleVT();
13819 
13820   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13821   // aligned and the type is a vector with elements up to 4 bytes
13822   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13823       VecTy.getScalarSizeInBits() <= 32) {
13824     return SDValue();
13825   }
13826 
13827   SDValue LoadOps[] = { Chain, Base };
13828   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13829                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13830                                          LoadOps, MVT::v2f64, MMO);
13831 
13832   DCI.AddToWorklist(Load.getNode());
13833   Chain = Load.getValue(1);
13834   SDValue Swap = DAG.getNode(
13835       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13836   DCI.AddToWorklist(Swap.getNode());
13837 
13838   // Add a bitcast if the resulting load type doesn't match v2f64.
13839   if (VecTy != MVT::v2f64) {
13840     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13841     DCI.AddToWorklist(N.getNode());
13842     // Package {bitcast value, swap's chain} to match Load's shape.
13843     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13844                        N, Swap.getValue(1));
13845   }
13846 
13847   return Swap;
13848 }
13849 
13850 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13851 // builtins) into stores with swaps.
13852 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13853                                                DAGCombinerInfo &DCI) const {
13854   SelectionDAG &DAG = DCI.DAG;
13855   SDLoc dl(N);
13856   SDValue Chain;
13857   SDValue Base;
13858   unsigned SrcOpnd;
13859   MachineMemOperand *MMO;
13860 
13861   switch (N->getOpcode()) {
13862   default:
13863     llvm_unreachable("Unexpected opcode for little endian VSX store");
13864   case ISD::STORE: {
13865     StoreSDNode *ST = cast<StoreSDNode>(N);
13866     Chain = ST->getChain();
13867     Base = ST->getBasePtr();
13868     MMO = ST->getMemOperand();
13869     SrcOpnd = 1;
13870     // If the MMO suggests this isn't a store of a full vector, leave
13871     // things alone.  For a built-in, we have to make the change for
13872     // correctness, so if there is a size problem that will be a bug.
13873     if (MMO->getSize() < 16)
13874       return SDValue();
13875     break;
13876   }
13877   case ISD::INTRINSIC_VOID: {
13878     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13879     Chain = Intrin->getChain();
13880     // Intrin->getBasePtr() oddly does not get what we want.
13881     Base = Intrin->getOperand(3);
13882     MMO = Intrin->getMemOperand();
13883     SrcOpnd = 2;
13884     break;
13885   }
13886   }
13887 
13888   SDValue Src = N->getOperand(SrcOpnd);
13889   MVT VecTy = Src.getValueType().getSimpleVT();
13890 
13891   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13892   // aligned and the type is a vector with elements up to 4 bytes
13893   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13894       VecTy.getScalarSizeInBits() <= 32) {
13895     return SDValue();
13896   }
13897 
13898   // All stores are done as v2f64 and possible bit cast.
13899   if (VecTy != MVT::v2f64) {
13900     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13901     DCI.AddToWorklist(Src.getNode());
13902   }
13903 
13904   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13905                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13906   DCI.AddToWorklist(Swap.getNode());
13907   Chain = Swap.getValue(1);
13908   SDValue StoreOps[] = { Chain, Swap, Base };
13909   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13910                                           DAG.getVTList(MVT::Other),
13911                                           StoreOps, VecTy, MMO);
13912   DCI.AddToWorklist(Store.getNode());
13913   return Store;
13914 }
13915 
13916 // Handle DAG combine for STORE (FP_TO_INT F).
13917 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13918                                                DAGCombinerInfo &DCI) const {
13919 
13920   SelectionDAG &DAG = DCI.DAG;
13921   SDLoc dl(N);
13922   unsigned Opcode = N->getOperand(1).getOpcode();
13923 
13924   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13925          && "Not a FP_TO_INT Instruction!");
13926 
13927   SDValue Val = N->getOperand(1).getOperand(0);
13928   EVT Op1VT = N->getOperand(1).getValueType();
13929   EVT ResVT = Val.getValueType();
13930 
13931   // Floating point types smaller than 32 bits are not legal on Power.
13932   if (ResVT.getScalarSizeInBits() < 32)
13933     return SDValue();
13934 
13935   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13936   bool ValidTypeForStoreFltAsInt =
13937         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13938          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13939 
13940   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13941       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13942     return SDValue();
13943 
13944   // Extend f32 values to f64
13945   if (ResVT.getScalarSizeInBits() == 32) {
13946     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13947     DCI.AddToWorklist(Val.getNode());
13948   }
13949 
13950   // Set signed or unsigned conversion opcode.
13951   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13952                           PPCISD::FP_TO_SINT_IN_VSR :
13953                           PPCISD::FP_TO_UINT_IN_VSR;
13954 
13955   Val = DAG.getNode(ConvOpcode,
13956                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13957   DCI.AddToWorklist(Val.getNode());
13958 
13959   // Set number of bytes being converted.
13960   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13961   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13962                     DAG.getIntPtrConstant(ByteSize, dl, false),
13963                     DAG.getValueType(Op1VT) };
13964 
13965   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13966           DAG.getVTList(MVT::Other), Ops,
13967           cast<StoreSDNode>(N)->getMemoryVT(),
13968           cast<StoreSDNode>(N)->getMemOperand());
13969 
13970   DCI.AddToWorklist(Val.getNode());
13971   return Val;
13972 }
13973 
13974 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13975                                                 LSBaseSDNode *LSBase,
13976                                                 DAGCombinerInfo &DCI) const {
13977   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13978         "Not a reverse memop pattern!");
13979 
13980   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13981     auto Mask = SVN->getMask();
13982     int i = 0;
13983     auto I = Mask.rbegin();
13984     auto E = Mask.rend();
13985 
13986     for (; I != E; ++I) {
13987       if (*I != i)
13988         return false;
13989       i++;
13990     }
13991     return true;
13992   };
13993 
13994   SelectionDAG &DAG = DCI.DAG;
13995   EVT VT = SVN->getValueType(0);
13996 
13997   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13998     return SDValue();
13999 
14000   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14001   // See comment in PPCVSXSwapRemoval.cpp.
14002   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14003   if (!Subtarget.hasP9Vector())
14004     return SDValue();
14005 
14006   if(!IsElementReverse(SVN))
14007     return SDValue();
14008 
14009   if (LSBase->getOpcode() == ISD::LOAD) {
14010     SDLoc dl(SVN);
14011     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14012     return DAG.getMemIntrinsicNode(
14013         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14014         LSBase->getMemoryVT(), LSBase->getMemOperand());
14015   }
14016 
14017   if (LSBase->getOpcode() == ISD::STORE) {
14018     SDLoc dl(LSBase);
14019     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14020                           LSBase->getBasePtr()};
14021     return DAG.getMemIntrinsicNode(
14022         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14023         LSBase->getMemoryVT(), LSBase->getMemOperand());
14024   }
14025 
14026   llvm_unreachable("Expected a load or store node here");
14027 }
14028 
14029 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14030                                              DAGCombinerInfo &DCI) const {
14031   SelectionDAG &DAG = DCI.DAG;
14032   SDLoc dl(N);
14033   switch (N->getOpcode()) {
14034   default: break;
14035   case ISD::ADD:
14036     return combineADD(N, DCI);
14037   case ISD::SHL:
14038     return combineSHL(N, DCI);
14039   case ISD::SRA:
14040     return combineSRA(N, DCI);
14041   case ISD::SRL:
14042     return combineSRL(N, DCI);
14043   case ISD::MUL:
14044     return combineMUL(N, DCI);
14045   case PPCISD::SHL:
14046     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14047         return N->getOperand(0);
14048     break;
14049   case PPCISD::SRL:
14050     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14051         return N->getOperand(0);
14052     break;
14053   case PPCISD::SRA:
14054     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14055       if (C->isNullValue() ||   //  0 >>s V -> 0.
14056           C->isAllOnesValue())    // -1 >>s V -> -1.
14057         return N->getOperand(0);
14058     }
14059     break;
14060   case ISD::SIGN_EXTEND:
14061   case ISD::ZERO_EXTEND:
14062   case ISD::ANY_EXTEND:
14063     return DAGCombineExtBoolTrunc(N, DCI);
14064   case ISD::TRUNCATE:
14065     return combineTRUNCATE(N, DCI);
14066   case ISD::SETCC:
14067     if (SDValue CSCC = combineSetCC(N, DCI))
14068       return CSCC;
14069     LLVM_FALLTHROUGH;
14070   case ISD::SELECT_CC:
14071     return DAGCombineTruncBoolExt(N, DCI);
14072   case ISD::SINT_TO_FP:
14073   case ISD::UINT_TO_FP:
14074     return combineFPToIntToFP(N, DCI);
14075   case ISD::VECTOR_SHUFFLE:
14076     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14077       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14078       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14079     }
14080     break;
14081   case ISD::STORE: {
14082 
14083     EVT Op1VT = N->getOperand(1).getValueType();
14084     unsigned Opcode = N->getOperand(1).getOpcode();
14085 
14086     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14087       SDValue Val= combineStoreFPToInt(N, DCI);
14088       if (Val)
14089         return Val;
14090     }
14091 
14092     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14093       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14094       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14095       if (Val)
14096         return Val;
14097     }
14098 
14099     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14100     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14101         N->getOperand(1).getNode()->hasOneUse() &&
14102         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14103          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14104 
14105       // STBRX can only handle simple types and it makes no sense to store less
14106       // two bytes in byte-reversed order.
14107       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14108       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14109         break;
14110 
14111       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14112       // Do an any-extend to 32-bits if this is a half-word input.
14113       if (BSwapOp.getValueType() == MVT::i16)
14114         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14115 
14116       // If the type of BSWAP operand is wider than stored memory width
14117       // it need to be shifted to the right side before STBRX.
14118       if (Op1VT.bitsGT(mVT)) {
14119         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14120         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14121                               DAG.getConstant(Shift, dl, MVT::i32));
14122         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14123         if (Op1VT == MVT::i64)
14124           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14125       }
14126 
14127       SDValue Ops[] = {
14128         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14129       };
14130       return
14131         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14132                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14133                                 cast<StoreSDNode>(N)->getMemOperand());
14134     }
14135 
14136     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14137     // So it can increase the chance of CSE constant construction.
14138     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14139         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14140       // Need to sign-extended to 64-bits to handle negative values.
14141       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14142       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14143                                     MemVT.getSizeInBits());
14144       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14145 
14146       // DAG.getTruncStore() can't be used here because it doesn't accept
14147       // the general (base + offset) addressing mode.
14148       // So we use UpdateNodeOperands and setTruncatingStore instead.
14149       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14150                              N->getOperand(3));
14151       cast<StoreSDNode>(N)->setTruncatingStore(true);
14152       return SDValue(N, 0);
14153     }
14154 
14155     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14156     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14157     if (Op1VT.isSimple()) {
14158       MVT StoreVT = Op1VT.getSimpleVT();
14159       if (Subtarget.needsSwapsForVSXMemOps() &&
14160           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14161            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14162         return expandVSXStoreForLE(N, DCI);
14163     }
14164     break;
14165   }
14166   case ISD::LOAD: {
14167     LoadSDNode *LD = cast<LoadSDNode>(N);
14168     EVT VT = LD->getValueType(0);
14169 
14170     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14171     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14172     if (VT.isSimple()) {
14173       MVT LoadVT = VT.getSimpleVT();
14174       if (Subtarget.needsSwapsForVSXMemOps() &&
14175           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14176            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14177         return expandVSXLoadForLE(N, DCI);
14178     }
14179 
14180     // We sometimes end up with a 64-bit integer load, from which we extract
14181     // two single-precision floating-point numbers. This happens with
14182     // std::complex<float>, and other similar structures, because of the way we
14183     // canonicalize structure copies. However, if we lack direct moves,
14184     // then the final bitcasts from the extracted integer values to the
14185     // floating-point numbers turn into store/load pairs. Even with direct moves,
14186     // just loading the two floating-point numbers is likely better.
14187     auto ReplaceTwoFloatLoad = [&]() {
14188       if (VT != MVT::i64)
14189         return false;
14190 
14191       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14192           LD->isVolatile())
14193         return false;
14194 
14195       //  We're looking for a sequence like this:
14196       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14197       //      t16: i64 = srl t13, Constant:i32<32>
14198       //    t17: i32 = truncate t16
14199       //  t18: f32 = bitcast t17
14200       //    t19: i32 = truncate t13
14201       //  t20: f32 = bitcast t19
14202 
14203       if (!LD->hasNUsesOfValue(2, 0))
14204         return false;
14205 
14206       auto UI = LD->use_begin();
14207       while (UI.getUse().getResNo() != 0) ++UI;
14208       SDNode *Trunc = *UI++;
14209       while (UI.getUse().getResNo() != 0) ++UI;
14210       SDNode *RightShift = *UI;
14211       if (Trunc->getOpcode() != ISD::TRUNCATE)
14212         std::swap(Trunc, RightShift);
14213 
14214       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14215           Trunc->getValueType(0) != MVT::i32 ||
14216           !Trunc->hasOneUse())
14217         return false;
14218       if (RightShift->getOpcode() != ISD::SRL ||
14219           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14220           RightShift->getConstantOperandVal(1) != 32 ||
14221           !RightShift->hasOneUse())
14222         return false;
14223 
14224       SDNode *Trunc2 = *RightShift->use_begin();
14225       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14226           Trunc2->getValueType(0) != MVT::i32 ||
14227           !Trunc2->hasOneUse())
14228         return false;
14229 
14230       SDNode *Bitcast = *Trunc->use_begin();
14231       SDNode *Bitcast2 = *Trunc2->use_begin();
14232 
14233       if (Bitcast->getOpcode() != ISD::BITCAST ||
14234           Bitcast->getValueType(0) != MVT::f32)
14235         return false;
14236       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14237           Bitcast2->getValueType(0) != MVT::f32)
14238         return false;
14239 
14240       if (Subtarget.isLittleEndian())
14241         std::swap(Bitcast, Bitcast2);
14242 
14243       // Bitcast has the second float (in memory-layout order) and Bitcast2
14244       // has the first one.
14245 
14246       SDValue BasePtr = LD->getBasePtr();
14247       if (LD->isIndexed()) {
14248         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14249                "Non-pre-inc AM on PPC?");
14250         BasePtr =
14251           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14252                       LD->getOffset());
14253       }
14254 
14255       auto MMOFlags =
14256           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14257       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14258                                       LD->getPointerInfo(), LD->getAlignment(),
14259                                       MMOFlags, LD->getAAInfo());
14260       SDValue AddPtr =
14261         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14262                     BasePtr, DAG.getIntPtrConstant(4, dl));
14263       SDValue FloatLoad2 = DAG.getLoad(
14264           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14265           LD->getPointerInfo().getWithOffset(4),
14266           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14267 
14268       if (LD->isIndexed()) {
14269         // Note that DAGCombine should re-form any pre-increment load(s) from
14270         // what is produced here if that makes sense.
14271         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14272       }
14273 
14274       DCI.CombineTo(Bitcast2, FloatLoad);
14275       DCI.CombineTo(Bitcast, FloatLoad2);
14276 
14277       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14278                                     SDValue(FloatLoad2.getNode(), 1));
14279       return true;
14280     };
14281 
14282     if (ReplaceTwoFloatLoad())
14283       return SDValue(N, 0);
14284 
14285     EVT MemVT = LD->getMemoryVT();
14286     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14287     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14288     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14289     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14290     if (LD->isUnindexed() && VT.isVector() &&
14291         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14292           // P8 and later hardware should just use LOAD.
14293           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14294                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14295          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14296           LD->getAlignment() >= ScalarABIAlignment)) &&
14297         LD->getAlignment() < ABIAlignment) {
14298       // This is a type-legal unaligned Altivec or QPX load.
14299       SDValue Chain = LD->getChain();
14300       SDValue Ptr = LD->getBasePtr();
14301       bool isLittleEndian = Subtarget.isLittleEndian();
14302 
14303       // This implements the loading of unaligned vectors as described in
14304       // the venerable Apple Velocity Engine overview. Specifically:
14305       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14306       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14307       //
14308       // The general idea is to expand a sequence of one or more unaligned
14309       // loads into an alignment-based permutation-control instruction (lvsl
14310       // or lvsr), a series of regular vector loads (which always truncate
14311       // their input address to an aligned address), and a series of
14312       // permutations.  The results of these permutations are the requested
14313       // loaded values.  The trick is that the last "extra" load is not taken
14314       // from the address you might suspect (sizeof(vector) bytes after the
14315       // last requested load), but rather sizeof(vector) - 1 bytes after the
14316       // last requested vector. The point of this is to avoid a page fault if
14317       // the base address happened to be aligned. This works because if the
14318       // base address is aligned, then adding less than a full vector length
14319       // will cause the last vector in the sequence to be (re)loaded.
14320       // Otherwise, the next vector will be fetched as you might suspect was
14321       // necessary.
14322 
14323       // We might be able to reuse the permutation generation from
14324       // a different base address offset from this one by an aligned amount.
14325       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14326       // optimization later.
14327       Intrinsic::ID Intr, IntrLD, IntrPerm;
14328       MVT PermCntlTy, PermTy, LDTy;
14329       if (Subtarget.hasAltivec()) {
14330         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14331                                  Intrinsic::ppc_altivec_lvsl;
14332         IntrLD = Intrinsic::ppc_altivec_lvx;
14333         IntrPerm = Intrinsic::ppc_altivec_vperm;
14334         PermCntlTy = MVT::v16i8;
14335         PermTy = MVT::v4i32;
14336         LDTy = MVT::v4i32;
14337       } else {
14338         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14339                                        Intrinsic::ppc_qpx_qvlpcls;
14340         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14341                                        Intrinsic::ppc_qpx_qvlfs;
14342         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14343         PermCntlTy = MVT::v4f64;
14344         PermTy = MVT::v4f64;
14345         LDTy = MemVT.getSimpleVT();
14346       }
14347 
14348       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14349 
14350       // Create the new MMO for the new base load. It is like the original MMO,
14351       // but represents an area in memory almost twice the vector size centered
14352       // on the original address. If the address is unaligned, we might start
14353       // reading up to (sizeof(vector)-1) bytes below the address of the
14354       // original unaligned load.
14355       MachineFunction &MF = DAG.getMachineFunction();
14356       MachineMemOperand *BaseMMO =
14357         MF.getMachineMemOperand(LD->getMemOperand(),
14358                                 -(long)MemVT.getStoreSize()+1,
14359                                 2*MemVT.getStoreSize()-1);
14360 
14361       // Create the new base load.
14362       SDValue LDXIntID =
14363           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14364       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14365       SDValue BaseLoad =
14366         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14367                                 DAG.getVTList(PermTy, MVT::Other),
14368                                 BaseLoadOps, LDTy, BaseMMO);
14369 
14370       // Note that the value of IncOffset (which is provided to the next
14371       // load's pointer info offset value, and thus used to calculate the
14372       // alignment), and the value of IncValue (which is actually used to
14373       // increment the pointer value) are different! This is because we
14374       // require the next load to appear to be aligned, even though it
14375       // is actually offset from the base pointer by a lesser amount.
14376       int IncOffset = VT.getSizeInBits() / 8;
14377       int IncValue = IncOffset;
14378 
14379       // Walk (both up and down) the chain looking for another load at the real
14380       // (aligned) offset (the alignment of the other load does not matter in
14381       // this case). If found, then do not use the offset reduction trick, as
14382       // that will prevent the loads from being later combined (as they would
14383       // otherwise be duplicates).
14384       if (!findConsecutiveLoad(LD, DAG))
14385         --IncValue;
14386 
14387       SDValue Increment =
14388           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14389       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14390 
14391       MachineMemOperand *ExtraMMO =
14392         MF.getMachineMemOperand(LD->getMemOperand(),
14393                                 1, 2*MemVT.getStoreSize()-1);
14394       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14395       SDValue ExtraLoad =
14396         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14397                                 DAG.getVTList(PermTy, MVT::Other),
14398                                 ExtraLoadOps, LDTy, ExtraMMO);
14399 
14400       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14401         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14402 
14403       // Because vperm has a big-endian bias, we must reverse the order
14404       // of the input vectors and complement the permute control vector
14405       // when generating little endian code.  We have already handled the
14406       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14407       // and ExtraLoad here.
14408       SDValue Perm;
14409       if (isLittleEndian)
14410         Perm = BuildIntrinsicOp(IntrPerm,
14411                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14412       else
14413         Perm = BuildIntrinsicOp(IntrPerm,
14414                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14415 
14416       if (VT != PermTy)
14417         Perm = Subtarget.hasAltivec() ?
14418                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14419                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14420                                DAG.getTargetConstant(1, dl, MVT::i64));
14421                                // second argument is 1 because this rounding
14422                                // is always exact.
14423 
14424       // The output of the permutation is our loaded result, the TokenFactor is
14425       // our new chain.
14426       DCI.CombineTo(N, Perm, TF);
14427       return SDValue(N, 0);
14428     }
14429     }
14430     break;
14431     case ISD::INTRINSIC_WO_CHAIN: {
14432       bool isLittleEndian = Subtarget.isLittleEndian();
14433       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14434       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14435                                            : Intrinsic::ppc_altivec_lvsl);
14436       if ((IID == Intr ||
14437            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14438            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14439         N->getOperand(1)->getOpcode() == ISD::ADD) {
14440         SDValue Add = N->getOperand(1);
14441 
14442         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14443                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14444 
14445         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14446                                   APInt::getAllOnesValue(Bits /* alignment */)
14447                                       .zext(Add.getScalarValueSizeInBits()))) {
14448           SDNode *BasePtr = Add->getOperand(0).getNode();
14449           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14450                                     UE = BasePtr->use_end();
14451                UI != UE; ++UI) {
14452             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14453                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14454               // We've found another LVSL/LVSR, and this address is an aligned
14455               // multiple of that one. The results will be the same, so use the
14456               // one we've just found instead.
14457 
14458               return SDValue(*UI, 0);
14459             }
14460           }
14461         }
14462 
14463         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14464           SDNode *BasePtr = Add->getOperand(0).getNode();
14465           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14466                UE = BasePtr->use_end(); UI != UE; ++UI) {
14467             if (UI->getOpcode() == ISD::ADD &&
14468                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14469                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14470                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14471                 (1ULL << Bits) == 0) {
14472               SDNode *OtherAdd = *UI;
14473               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14474                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14475                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14476                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14477                   return SDValue(*VI, 0);
14478                 }
14479               }
14480             }
14481           }
14482         }
14483       }
14484 
14485       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14486       // Expose the vabsduw/h/b opportunity for down stream
14487       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14488           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14489            IID == Intrinsic::ppc_altivec_vmaxsh ||
14490            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14491         SDValue V1 = N->getOperand(1);
14492         SDValue V2 = N->getOperand(2);
14493         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14494              V1.getSimpleValueType() == MVT::v8i16 ||
14495              V1.getSimpleValueType() == MVT::v16i8) &&
14496             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14497           // (0-a, a)
14498           if (V1.getOpcode() == ISD::SUB &&
14499               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14500               V1.getOperand(1) == V2) {
14501             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14502           }
14503           // (a, 0-a)
14504           if (V2.getOpcode() == ISD::SUB &&
14505               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14506               V2.getOperand(1) == V1) {
14507             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14508           }
14509           // (x-y, y-x)
14510           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14511               V1.getOperand(0) == V2.getOperand(1) &&
14512               V1.getOperand(1) == V2.getOperand(0)) {
14513             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14514           }
14515         }
14516       }
14517     }
14518 
14519     break;
14520   case ISD::INTRINSIC_W_CHAIN:
14521     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14522     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14523     if (Subtarget.needsSwapsForVSXMemOps()) {
14524       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14525       default:
14526         break;
14527       case Intrinsic::ppc_vsx_lxvw4x:
14528       case Intrinsic::ppc_vsx_lxvd2x:
14529         return expandVSXLoadForLE(N, DCI);
14530       }
14531     }
14532     break;
14533   case ISD::INTRINSIC_VOID:
14534     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14535     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14536     if (Subtarget.needsSwapsForVSXMemOps()) {
14537       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14538       default:
14539         break;
14540       case Intrinsic::ppc_vsx_stxvw4x:
14541       case Intrinsic::ppc_vsx_stxvd2x:
14542         return expandVSXStoreForLE(N, DCI);
14543       }
14544     }
14545     break;
14546   case ISD::BSWAP:
14547     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14548     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14549         N->getOperand(0).hasOneUse() &&
14550         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14551          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14552           N->getValueType(0) == MVT::i64))) {
14553       SDValue Load = N->getOperand(0);
14554       LoadSDNode *LD = cast<LoadSDNode>(Load);
14555       // Create the byte-swapping load.
14556       SDValue Ops[] = {
14557         LD->getChain(),    // Chain
14558         LD->getBasePtr(),  // Ptr
14559         DAG.getValueType(N->getValueType(0)) // VT
14560       };
14561       SDValue BSLoad =
14562         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14563                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14564                                               MVT::i64 : MVT::i32, MVT::Other),
14565                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14566 
14567       // If this is an i16 load, insert the truncate.
14568       SDValue ResVal = BSLoad;
14569       if (N->getValueType(0) == MVT::i16)
14570         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14571 
14572       // First, combine the bswap away.  This makes the value produced by the
14573       // load dead.
14574       DCI.CombineTo(N, ResVal);
14575 
14576       // Next, combine the load away, we give it a bogus result value but a real
14577       // chain result.  The result value is dead because the bswap is dead.
14578       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14579 
14580       // Return N so it doesn't get rechecked!
14581       return SDValue(N, 0);
14582     }
14583     break;
14584   case PPCISD::VCMP:
14585     // If a VCMPo node already exists with exactly the same operands as this
14586     // node, use its result instead of this node (VCMPo computes both a CR6 and
14587     // a normal output).
14588     //
14589     if (!N->getOperand(0).hasOneUse() &&
14590         !N->getOperand(1).hasOneUse() &&
14591         !N->getOperand(2).hasOneUse()) {
14592 
14593       // Scan all of the users of the LHS, looking for VCMPo's that match.
14594       SDNode *VCMPoNode = nullptr;
14595 
14596       SDNode *LHSN = N->getOperand(0).getNode();
14597       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14598            UI != E; ++UI)
14599         if (UI->getOpcode() == PPCISD::VCMPo &&
14600             UI->getOperand(1) == N->getOperand(1) &&
14601             UI->getOperand(2) == N->getOperand(2) &&
14602             UI->getOperand(0) == N->getOperand(0)) {
14603           VCMPoNode = *UI;
14604           break;
14605         }
14606 
14607       // If there is no VCMPo node, or if the flag value has a single use, don't
14608       // transform this.
14609       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14610         break;
14611 
14612       // Look at the (necessarily single) use of the flag value.  If it has a
14613       // chain, this transformation is more complex.  Note that multiple things
14614       // could use the value result, which we should ignore.
14615       SDNode *FlagUser = nullptr;
14616       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14617            FlagUser == nullptr; ++UI) {
14618         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14619         SDNode *User = *UI;
14620         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14621           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14622             FlagUser = User;
14623             break;
14624           }
14625         }
14626       }
14627 
14628       // If the user is a MFOCRF instruction, we know this is safe.
14629       // Otherwise we give up for right now.
14630       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14631         return SDValue(VCMPoNode, 0);
14632     }
14633     break;
14634   case ISD::BRCOND: {
14635     SDValue Cond = N->getOperand(1);
14636     SDValue Target = N->getOperand(2);
14637 
14638     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14639         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14640           Intrinsic::loop_decrement) {
14641 
14642       // We now need to make the intrinsic dead (it cannot be instruction
14643       // selected).
14644       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14645       assert(Cond.getNode()->hasOneUse() &&
14646              "Counter decrement has more than one use");
14647 
14648       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14649                          N->getOperand(0), Target);
14650     }
14651   }
14652   break;
14653   case ISD::BR_CC: {
14654     // If this is a branch on an altivec predicate comparison, lower this so
14655     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14656     // lowering is done pre-legalize, because the legalizer lowers the predicate
14657     // compare down to code that is difficult to reassemble.
14658     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14659     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14660 
14661     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14662     // value. If so, pass-through the AND to get to the intrinsic.
14663     if (LHS.getOpcode() == ISD::AND &&
14664         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14665         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14666           Intrinsic::loop_decrement &&
14667         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14668         !isNullConstant(LHS.getOperand(1)))
14669       LHS = LHS.getOperand(0);
14670 
14671     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14672         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14673           Intrinsic::loop_decrement &&
14674         isa<ConstantSDNode>(RHS)) {
14675       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14676              "Counter decrement comparison is not EQ or NE");
14677 
14678       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14679       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14680                     (CC == ISD::SETNE && !Val);
14681 
14682       // We now need to make the intrinsic dead (it cannot be instruction
14683       // selected).
14684       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14685       assert(LHS.getNode()->hasOneUse() &&
14686              "Counter decrement has more than one use");
14687 
14688       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14689                          N->getOperand(0), N->getOperand(4));
14690     }
14691 
14692     int CompareOpc;
14693     bool isDot;
14694 
14695     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14696         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14697         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14698       assert(isDot && "Can't compare against a vector result!");
14699 
14700       // If this is a comparison against something other than 0/1, then we know
14701       // that the condition is never/always true.
14702       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14703       if (Val != 0 && Val != 1) {
14704         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14705           return N->getOperand(0);
14706         // Always !=, turn it into an unconditional branch.
14707         return DAG.getNode(ISD::BR, dl, MVT::Other,
14708                            N->getOperand(0), N->getOperand(4));
14709       }
14710 
14711       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14712 
14713       // Create the PPCISD altivec 'dot' comparison node.
14714       SDValue Ops[] = {
14715         LHS.getOperand(2),  // LHS of compare
14716         LHS.getOperand(3),  // RHS of compare
14717         DAG.getConstant(CompareOpc, dl, MVT::i32)
14718       };
14719       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14720       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14721 
14722       // Unpack the result based on how the target uses it.
14723       PPC::Predicate CompOpc;
14724       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14725       default:  // Can't happen, don't crash on invalid number though.
14726       case 0:   // Branch on the value of the EQ bit of CR6.
14727         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14728         break;
14729       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14730         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14731         break;
14732       case 2:   // Branch on the value of the LT bit of CR6.
14733         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14734         break;
14735       case 3:   // Branch on the inverted value of the LT bit of CR6.
14736         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14737         break;
14738       }
14739 
14740       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14741                          DAG.getConstant(CompOpc, dl, MVT::i32),
14742                          DAG.getRegister(PPC::CR6, MVT::i32),
14743                          N->getOperand(4), CompNode.getValue(1));
14744     }
14745     break;
14746   }
14747   case ISD::BUILD_VECTOR:
14748     return DAGCombineBuildVector(N, DCI);
14749   case ISD::ABS:
14750     return combineABS(N, DCI);
14751   case ISD::VSELECT:
14752     return combineVSelect(N, DCI);
14753   }
14754 
14755   return SDValue();
14756 }
14757 
14758 SDValue
14759 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14760                                  SelectionDAG &DAG,
14761                                  SmallVectorImpl<SDNode *> &Created) const {
14762   // fold (sdiv X, pow2)
14763   EVT VT = N->getValueType(0);
14764   if (VT == MVT::i64 && !Subtarget.isPPC64())
14765     return SDValue();
14766   if ((VT != MVT::i32 && VT != MVT::i64) ||
14767       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14768     return SDValue();
14769 
14770   SDLoc DL(N);
14771   SDValue N0 = N->getOperand(0);
14772 
14773   bool IsNegPow2 = (-Divisor).isPowerOf2();
14774   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14775   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14776 
14777   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14778   Created.push_back(Op.getNode());
14779 
14780   if (IsNegPow2) {
14781     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14782     Created.push_back(Op.getNode());
14783   }
14784 
14785   return Op;
14786 }
14787 
14788 //===----------------------------------------------------------------------===//
14789 // Inline Assembly Support
14790 //===----------------------------------------------------------------------===//
14791 
14792 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14793                                                       KnownBits &Known,
14794                                                       const APInt &DemandedElts,
14795                                                       const SelectionDAG &DAG,
14796                                                       unsigned Depth) const {
14797   Known.resetAll();
14798   switch (Op.getOpcode()) {
14799   default: break;
14800   case PPCISD::LBRX: {
14801     // lhbrx is known to have the top bits cleared out.
14802     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14803       Known.Zero = 0xFFFF0000;
14804     break;
14805   }
14806   case ISD::INTRINSIC_WO_CHAIN: {
14807     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14808     default: break;
14809     case Intrinsic::ppc_altivec_vcmpbfp_p:
14810     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14811     case Intrinsic::ppc_altivec_vcmpequb_p:
14812     case Intrinsic::ppc_altivec_vcmpequh_p:
14813     case Intrinsic::ppc_altivec_vcmpequw_p:
14814     case Intrinsic::ppc_altivec_vcmpequd_p:
14815     case Intrinsic::ppc_altivec_vcmpgefp_p:
14816     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14817     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14818     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14819     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14820     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14821     case Intrinsic::ppc_altivec_vcmpgtub_p:
14822     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14823     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14824     case Intrinsic::ppc_altivec_vcmpgtud_p:
14825       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14826       break;
14827     }
14828   }
14829   }
14830 }
14831 
14832 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14833   switch (Subtarget.getCPUDirective()) {
14834   default: break;
14835   case PPC::DIR_970:
14836   case PPC::DIR_PWR4:
14837   case PPC::DIR_PWR5:
14838   case PPC::DIR_PWR5X:
14839   case PPC::DIR_PWR6:
14840   case PPC::DIR_PWR6X:
14841   case PPC::DIR_PWR7:
14842   case PPC::DIR_PWR8:
14843   case PPC::DIR_PWR9:
14844   case PPC::DIR_PWR_FUTURE: {
14845     if (!ML)
14846       break;
14847 
14848     if (!DisableInnermostLoopAlign32) {
14849       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14850       // so that we can decrease cache misses and branch-prediction misses.
14851       // Actual alignment of the loop will depend on the hotness check and other
14852       // logic in alignBlocks.
14853       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14854         return Align(32);
14855     }
14856 
14857     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14858 
14859     // For small loops (between 5 and 8 instructions), align to a 32-byte
14860     // boundary so that the entire loop fits in one instruction-cache line.
14861     uint64_t LoopSize = 0;
14862     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14863       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14864         LoopSize += TII->getInstSizeInBytes(*J);
14865         if (LoopSize > 32)
14866           break;
14867       }
14868 
14869     if (LoopSize > 16 && LoopSize <= 32)
14870       return Align(32);
14871 
14872     break;
14873   }
14874   }
14875 
14876   return TargetLowering::getPrefLoopAlignment(ML);
14877 }
14878 
14879 /// getConstraintType - Given a constraint, return the type of
14880 /// constraint it is for this target.
14881 PPCTargetLowering::ConstraintType
14882 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14883   if (Constraint.size() == 1) {
14884     switch (Constraint[0]) {
14885     default: break;
14886     case 'b':
14887     case 'r':
14888     case 'f':
14889     case 'd':
14890     case 'v':
14891     case 'y':
14892       return C_RegisterClass;
14893     case 'Z':
14894       // FIXME: While Z does indicate a memory constraint, it specifically
14895       // indicates an r+r address (used in conjunction with the 'y' modifier
14896       // in the replacement string). Currently, we're forcing the base
14897       // register to be r0 in the asm printer (which is interpreted as zero)
14898       // and forming the complete address in the second register. This is
14899       // suboptimal.
14900       return C_Memory;
14901     }
14902   } else if (Constraint == "wc") { // individual CR bits.
14903     return C_RegisterClass;
14904   } else if (Constraint == "wa" || Constraint == "wd" ||
14905              Constraint == "wf" || Constraint == "ws" ||
14906              Constraint == "wi" || Constraint == "ww") {
14907     return C_RegisterClass; // VSX registers.
14908   }
14909   return TargetLowering::getConstraintType(Constraint);
14910 }
14911 
14912 /// Examine constraint type and operand type and determine a weight value.
14913 /// This object must already have been set up with the operand type
14914 /// and the current alternative constraint selected.
14915 TargetLowering::ConstraintWeight
14916 PPCTargetLowering::getSingleConstraintMatchWeight(
14917     AsmOperandInfo &info, const char *constraint) const {
14918   ConstraintWeight weight = CW_Invalid;
14919   Value *CallOperandVal = info.CallOperandVal;
14920     // If we don't have a value, we can't do a match,
14921     // but allow it at the lowest weight.
14922   if (!CallOperandVal)
14923     return CW_Default;
14924   Type *type = CallOperandVal->getType();
14925 
14926   // Look at the constraint type.
14927   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14928     return CW_Register; // an individual CR bit.
14929   else if ((StringRef(constraint) == "wa" ||
14930             StringRef(constraint) == "wd" ||
14931             StringRef(constraint) == "wf") &&
14932            type->isVectorTy())
14933     return CW_Register;
14934   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14935     return CW_Register; // just hold 64-bit integers data.
14936   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14937     return CW_Register;
14938   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14939     return CW_Register;
14940 
14941   switch (*constraint) {
14942   default:
14943     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14944     break;
14945   case 'b':
14946     if (type->isIntegerTy())
14947       weight = CW_Register;
14948     break;
14949   case 'f':
14950     if (type->isFloatTy())
14951       weight = CW_Register;
14952     break;
14953   case 'd':
14954     if (type->isDoubleTy())
14955       weight = CW_Register;
14956     break;
14957   case 'v':
14958     if (type->isVectorTy())
14959       weight = CW_Register;
14960     break;
14961   case 'y':
14962     weight = CW_Register;
14963     break;
14964   case 'Z':
14965     weight = CW_Memory;
14966     break;
14967   }
14968   return weight;
14969 }
14970 
14971 std::pair<unsigned, const TargetRegisterClass *>
14972 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14973                                                 StringRef Constraint,
14974                                                 MVT VT) const {
14975   if (Constraint.size() == 1) {
14976     // GCC RS6000 Constraint Letters
14977     switch (Constraint[0]) {
14978     case 'b':   // R1-R31
14979       if (VT == MVT::i64 && Subtarget.isPPC64())
14980         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14981       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14982     case 'r':   // R0-R31
14983       if (VT == MVT::i64 && Subtarget.isPPC64())
14984         return std::make_pair(0U, &PPC::G8RCRegClass);
14985       return std::make_pair(0U, &PPC::GPRCRegClass);
14986     // 'd' and 'f' constraints are both defined to be "the floating point
14987     // registers", where one is for 32-bit and the other for 64-bit. We don't
14988     // really care overly much here so just give them all the same reg classes.
14989     case 'd':
14990     case 'f':
14991       if (Subtarget.hasSPE()) {
14992         if (VT == MVT::f32 || VT == MVT::i32)
14993           return std::make_pair(0U, &PPC::GPRCRegClass);
14994         if (VT == MVT::f64 || VT == MVT::i64)
14995           return std::make_pair(0U, &PPC::SPERCRegClass);
14996       } else {
14997         if (VT == MVT::f32 || VT == MVT::i32)
14998           return std::make_pair(0U, &PPC::F4RCRegClass);
14999         if (VT == MVT::f64 || VT == MVT::i64)
15000           return std::make_pair(0U, &PPC::F8RCRegClass);
15001         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15002           return std::make_pair(0U, &PPC::QFRCRegClass);
15003         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15004           return std::make_pair(0U, &PPC::QSRCRegClass);
15005       }
15006       break;
15007     case 'v':
15008       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15009         return std::make_pair(0U, &PPC::QFRCRegClass);
15010       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15011         return std::make_pair(0U, &PPC::QSRCRegClass);
15012       if (Subtarget.hasAltivec())
15013         return std::make_pair(0U, &PPC::VRRCRegClass);
15014       break;
15015     case 'y':   // crrc
15016       return std::make_pair(0U, &PPC::CRRCRegClass);
15017     }
15018   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15019     // An individual CR bit.
15020     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15021   } else if ((Constraint == "wa" || Constraint == "wd" ||
15022              Constraint == "wf" || Constraint == "wi") &&
15023              Subtarget.hasVSX()) {
15024     return std::make_pair(0U, &PPC::VSRCRegClass);
15025   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15026     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15027       return std::make_pair(0U, &PPC::VSSRCRegClass);
15028     else
15029       return std::make_pair(0U, &PPC::VSFRCRegClass);
15030   }
15031 
15032   // If we name a VSX register, we can't defer to the base class because it
15033   // will not recognize the correct register (their names will be VSL{0-31}
15034   // and V{0-31} so they won't match). So we match them here.
15035   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15036     int VSNum = atoi(Constraint.data() + 3);
15037     assert(VSNum >= 0 && VSNum <= 63 &&
15038            "Attempted to access a vsr out of range");
15039     if (VSNum < 32)
15040       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15041     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15042   }
15043   std::pair<unsigned, const TargetRegisterClass *> R =
15044       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15045 
15046   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15047   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15048   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15049   // register.
15050   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15051   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15052   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15053       PPC::GPRCRegClass.contains(R.first))
15054     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15055                             PPC::sub_32, &PPC::G8RCRegClass),
15056                           &PPC::G8RCRegClass);
15057 
15058   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15059   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15060     R.first = PPC::CR0;
15061     R.second = &PPC::CRRCRegClass;
15062   }
15063 
15064   return R;
15065 }
15066 
15067 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15068 /// vector.  If it is invalid, don't add anything to Ops.
15069 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15070                                                      std::string &Constraint,
15071                                                      std::vector<SDValue>&Ops,
15072                                                      SelectionDAG &DAG) const {
15073   SDValue Result;
15074 
15075   // Only support length 1 constraints.
15076   if (Constraint.length() > 1) return;
15077 
15078   char Letter = Constraint[0];
15079   switch (Letter) {
15080   default: break;
15081   case 'I':
15082   case 'J':
15083   case 'K':
15084   case 'L':
15085   case 'M':
15086   case 'N':
15087   case 'O':
15088   case 'P': {
15089     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15090     if (!CST) return; // Must be an immediate to match.
15091     SDLoc dl(Op);
15092     int64_t Value = CST->getSExtValue();
15093     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15094                          // numbers are printed as such.
15095     switch (Letter) {
15096     default: llvm_unreachable("Unknown constraint letter!");
15097     case 'I':  // "I" is a signed 16-bit constant.
15098       if (isInt<16>(Value))
15099         Result = DAG.getTargetConstant(Value, dl, TCVT);
15100       break;
15101     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15102       if (isShiftedUInt<16, 16>(Value))
15103         Result = DAG.getTargetConstant(Value, dl, TCVT);
15104       break;
15105     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15106       if (isShiftedInt<16, 16>(Value))
15107         Result = DAG.getTargetConstant(Value, dl, TCVT);
15108       break;
15109     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15110       if (isUInt<16>(Value))
15111         Result = DAG.getTargetConstant(Value, dl, TCVT);
15112       break;
15113     case 'M':  // "M" is a constant that is greater than 31.
15114       if (Value > 31)
15115         Result = DAG.getTargetConstant(Value, dl, TCVT);
15116       break;
15117     case 'N':  // "N" is a positive constant that is an exact power of two.
15118       if (Value > 0 && isPowerOf2_64(Value))
15119         Result = DAG.getTargetConstant(Value, dl, TCVT);
15120       break;
15121     case 'O':  // "O" is the constant zero.
15122       if (Value == 0)
15123         Result = DAG.getTargetConstant(Value, dl, TCVT);
15124       break;
15125     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15126       if (isInt<16>(-Value))
15127         Result = DAG.getTargetConstant(Value, dl, TCVT);
15128       break;
15129     }
15130     break;
15131   }
15132   }
15133 
15134   if (Result.getNode()) {
15135     Ops.push_back(Result);
15136     return;
15137   }
15138 
15139   // Handle standard constraint letters.
15140   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15141 }
15142 
15143 // isLegalAddressingMode - Return true if the addressing mode represented
15144 // by AM is legal for this target, for a load/store of the specified type.
15145 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15146                                               const AddrMode &AM, Type *Ty,
15147                                               unsigned AS, Instruction *I) const {
15148   // PPC does not allow r+i addressing modes for vectors!
15149   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15150     return false;
15151 
15152   // PPC allows a sign-extended 16-bit immediate field.
15153   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15154     return false;
15155 
15156   // No global is ever allowed as a base.
15157   if (AM.BaseGV)
15158     return false;
15159 
15160   // PPC only support r+r,
15161   switch (AM.Scale) {
15162   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15163     break;
15164   case 1:
15165     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15166       return false;
15167     // Otherwise we have r+r or r+i.
15168     break;
15169   case 2:
15170     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15171       return false;
15172     // Allow 2*r as r+r.
15173     break;
15174   default:
15175     // No other scales are supported.
15176     return false;
15177   }
15178 
15179   return true;
15180 }
15181 
15182 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15183                                            SelectionDAG &DAG) const {
15184   MachineFunction &MF = DAG.getMachineFunction();
15185   MachineFrameInfo &MFI = MF.getFrameInfo();
15186   MFI.setReturnAddressIsTaken(true);
15187 
15188   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15189     return SDValue();
15190 
15191   SDLoc dl(Op);
15192   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15193 
15194   // Make sure the function does not optimize away the store of the RA to
15195   // the stack.
15196   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15197   FuncInfo->setLRStoreRequired();
15198   bool isPPC64 = Subtarget.isPPC64();
15199   auto PtrVT = getPointerTy(MF.getDataLayout());
15200 
15201   if (Depth > 0) {
15202     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15203     SDValue Offset =
15204         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15205                         isPPC64 ? MVT::i64 : MVT::i32);
15206     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15207                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15208                        MachinePointerInfo());
15209   }
15210 
15211   // Just load the return address off the stack.
15212   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15213   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15214                      MachinePointerInfo());
15215 }
15216 
15217 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15218                                           SelectionDAG &DAG) const {
15219   SDLoc dl(Op);
15220   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15221 
15222   MachineFunction &MF = DAG.getMachineFunction();
15223   MachineFrameInfo &MFI = MF.getFrameInfo();
15224   MFI.setFrameAddressIsTaken(true);
15225 
15226   EVT PtrVT = getPointerTy(MF.getDataLayout());
15227   bool isPPC64 = PtrVT == MVT::i64;
15228 
15229   // Naked functions never have a frame pointer, and so we use r1. For all
15230   // other functions, this decision must be delayed until during PEI.
15231   unsigned FrameReg;
15232   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15233     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15234   else
15235     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15236 
15237   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15238                                          PtrVT);
15239   while (Depth--)
15240     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15241                             FrameAddr, MachinePointerInfo());
15242   return FrameAddr;
15243 }
15244 
15245 // FIXME? Maybe this could be a TableGen attribute on some registers and
15246 // this table could be generated automatically from RegInfo.
15247 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15248                                               const MachineFunction &MF) const {
15249   bool isPPC64 = Subtarget.isPPC64();
15250 
15251   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15252   if (!is64Bit && VT != LLT::scalar(32))
15253     report_fatal_error("Invalid register global variable type");
15254 
15255   Register Reg = StringSwitch<Register>(RegName)
15256                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15257                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15258                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15259                      .Default(Register());
15260 
15261   if (Reg)
15262     return Reg;
15263   report_fatal_error("Invalid register name global variable");
15264 }
15265 
15266 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15267   // 32-bit SVR4 ABI access everything as got-indirect.
15268   if (Subtarget.is32BitELFABI())
15269     return true;
15270 
15271   // AIX accesses everything indirectly through the TOC, which is similar to
15272   // the GOT.
15273   if (Subtarget.isAIXABI())
15274     return true;
15275 
15276   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15277   // If it is small or large code model, module locals are accessed
15278   // indirectly by loading their address from .toc/.got.
15279   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15280     return true;
15281 
15282   // JumpTable and BlockAddress are accessed as got-indirect.
15283   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15284     return true;
15285 
15286   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15287     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15288 
15289   return false;
15290 }
15291 
15292 bool
15293 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15294   // The PowerPC target isn't yet aware of offsets.
15295   return false;
15296 }
15297 
15298 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15299                                            const CallInst &I,
15300                                            MachineFunction &MF,
15301                                            unsigned Intrinsic) const {
15302   switch (Intrinsic) {
15303   case Intrinsic::ppc_qpx_qvlfd:
15304   case Intrinsic::ppc_qpx_qvlfs:
15305   case Intrinsic::ppc_qpx_qvlfcd:
15306   case Intrinsic::ppc_qpx_qvlfcs:
15307   case Intrinsic::ppc_qpx_qvlfiwa:
15308   case Intrinsic::ppc_qpx_qvlfiwz:
15309   case Intrinsic::ppc_altivec_lvx:
15310   case Intrinsic::ppc_altivec_lvxl:
15311   case Intrinsic::ppc_altivec_lvebx:
15312   case Intrinsic::ppc_altivec_lvehx:
15313   case Intrinsic::ppc_altivec_lvewx:
15314   case Intrinsic::ppc_vsx_lxvd2x:
15315   case Intrinsic::ppc_vsx_lxvw4x: {
15316     EVT VT;
15317     switch (Intrinsic) {
15318     case Intrinsic::ppc_altivec_lvebx:
15319       VT = MVT::i8;
15320       break;
15321     case Intrinsic::ppc_altivec_lvehx:
15322       VT = MVT::i16;
15323       break;
15324     case Intrinsic::ppc_altivec_lvewx:
15325       VT = MVT::i32;
15326       break;
15327     case Intrinsic::ppc_vsx_lxvd2x:
15328       VT = MVT::v2f64;
15329       break;
15330     case Intrinsic::ppc_qpx_qvlfd:
15331       VT = MVT::v4f64;
15332       break;
15333     case Intrinsic::ppc_qpx_qvlfs:
15334       VT = MVT::v4f32;
15335       break;
15336     case Intrinsic::ppc_qpx_qvlfcd:
15337       VT = MVT::v2f64;
15338       break;
15339     case Intrinsic::ppc_qpx_qvlfcs:
15340       VT = MVT::v2f32;
15341       break;
15342     default:
15343       VT = MVT::v4i32;
15344       break;
15345     }
15346 
15347     Info.opc = ISD::INTRINSIC_W_CHAIN;
15348     Info.memVT = VT;
15349     Info.ptrVal = I.getArgOperand(0);
15350     Info.offset = -VT.getStoreSize()+1;
15351     Info.size = 2*VT.getStoreSize()-1;
15352     Info.align = Align(1);
15353     Info.flags = MachineMemOperand::MOLoad;
15354     return true;
15355   }
15356   case Intrinsic::ppc_qpx_qvlfda:
15357   case Intrinsic::ppc_qpx_qvlfsa:
15358   case Intrinsic::ppc_qpx_qvlfcda:
15359   case Intrinsic::ppc_qpx_qvlfcsa:
15360   case Intrinsic::ppc_qpx_qvlfiwaa:
15361   case Intrinsic::ppc_qpx_qvlfiwza: {
15362     EVT VT;
15363     switch (Intrinsic) {
15364     case Intrinsic::ppc_qpx_qvlfda:
15365       VT = MVT::v4f64;
15366       break;
15367     case Intrinsic::ppc_qpx_qvlfsa:
15368       VT = MVT::v4f32;
15369       break;
15370     case Intrinsic::ppc_qpx_qvlfcda:
15371       VT = MVT::v2f64;
15372       break;
15373     case Intrinsic::ppc_qpx_qvlfcsa:
15374       VT = MVT::v2f32;
15375       break;
15376     default:
15377       VT = MVT::v4i32;
15378       break;
15379     }
15380 
15381     Info.opc = ISD::INTRINSIC_W_CHAIN;
15382     Info.memVT = VT;
15383     Info.ptrVal = I.getArgOperand(0);
15384     Info.offset = 0;
15385     Info.size = VT.getStoreSize();
15386     Info.align = Align(1);
15387     Info.flags = MachineMemOperand::MOLoad;
15388     return true;
15389   }
15390   case Intrinsic::ppc_qpx_qvstfd:
15391   case Intrinsic::ppc_qpx_qvstfs:
15392   case Intrinsic::ppc_qpx_qvstfcd:
15393   case Intrinsic::ppc_qpx_qvstfcs:
15394   case Intrinsic::ppc_qpx_qvstfiw:
15395   case Intrinsic::ppc_altivec_stvx:
15396   case Intrinsic::ppc_altivec_stvxl:
15397   case Intrinsic::ppc_altivec_stvebx:
15398   case Intrinsic::ppc_altivec_stvehx:
15399   case Intrinsic::ppc_altivec_stvewx:
15400   case Intrinsic::ppc_vsx_stxvd2x:
15401   case Intrinsic::ppc_vsx_stxvw4x: {
15402     EVT VT;
15403     switch (Intrinsic) {
15404     case Intrinsic::ppc_altivec_stvebx:
15405       VT = MVT::i8;
15406       break;
15407     case Intrinsic::ppc_altivec_stvehx:
15408       VT = MVT::i16;
15409       break;
15410     case Intrinsic::ppc_altivec_stvewx:
15411       VT = MVT::i32;
15412       break;
15413     case Intrinsic::ppc_vsx_stxvd2x:
15414       VT = MVT::v2f64;
15415       break;
15416     case Intrinsic::ppc_qpx_qvstfd:
15417       VT = MVT::v4f64;
15418       break;
15419     case Intrinsic::ppc_qpx_qvstfs:
15420       VT = MVT::v4f32;
15421       break;
15422     case Intrinsic::ppc_qpx_qvstfcd:
15423       VT = MVT::v2f64;
15424       break;
15425     case Intrinsic::ppc_qpx_qvstfcs:
15426       VT = MVT::v2f32;
15427       break;
15428     default:
15429       VT = MVT::v4i32;
15430       break;
15431     }
15432 
15433     Info.opc = ISD::INTRINSIC_VOID;
15434     Info.memVT = VT;
15435     Info.ptrVal = I.getArgOperand(1);
15436     Info.offset = -VT.getStoreSize()+1;
15437     Info.size = 2*VT.getStoreSize()-1;
15438     Info.align = Align(1);
15439     Info.flags = MachineMemOperand::MOStore;
15440     return true;
15441   }
15442   case Intrinsic::ppc_qpx_qvstfda:
15443   case Intrinsic::ppc_qpx_qvstfsa:
15444   case Intrinsic::ppc_qpx_qvstfcda:
15445   case Intrinsic::ppc_qpx_qvstfcsa:
15446   case Intrinsic::ppc_qpx_qvstfiwa: {
15447     EVT VT;
15448     switch (Intrinsic) {
15449     case Intrinsic::ppc_qpx_qvstfda:
15450       VT = MVT::v4f64;
15451       break;
15452     case Intrinsic::ppc_qpx_qvstfsa:
15453       VT = MVT::v4f32;
15454       break;
15455     case Intrinsic::ppc_qpx_qvstfcda:
15456       VT = MVT::v2f64;
15457       break;
15458     case Intrinsic::ppc_qpx_qvstfcsa:
15459       VT = MVT::v2f32;
15460       break;
15461     default:
15462       VT = MVT::v4i32;
15463       break;
15464     }
15465 
15466     Info.opc = ISD::INTRINSIC_VOID;
15467     Info.memVT = VT;
15468     Info.ptrVal = I.getArgOperand(1);
15469     Info.offset = 0;
15470     Info.size = VT.getStoreSize();
15471     Info.align = Align(1);
15472     Info.flags = MachineMemOperand::MOStore;
15473     return true;
15474   }
15475   default:
15476     break;
15477   }
15478 
15479   return false;
15480 }
15481 
15482 /// It returns EVT::Other if the type should be determined using generic
15483 /// target-independent logic.
15484 EVT PPCTargetLowering::getOptimalMemOpType(
15485     const MemOp &Op, const AttributeList &FuncAttributes) const {
15486   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15487     // When expanding a memset, require at least two QPX instructions to cover
15488     // the cost of loading the value to be stored from the constant pool.
15489     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15490         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15491         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15492       return MVT::v4f64;
15493     }
15494 
15495     // We should use Altivec/VSX loads and stores when available. For unaligned
15496     // addresses, unaligned VSX loads are only fast starting with the P8.
15497     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15498         (Op.isAligned(Align(16)) ||
15499          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15500       return MVT::v4i32;
15501   }
15502 
15503   if (Subtarget.isPPC64()) {
15504     return MVT::i64;
15505   }
15506 
15507   return MVT::i32;
15508 }
15509 
15510 /// Returns true if it is beneficial to convert a load of a constant
15511 /// to just the constant itself.
15512 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15513                                                           Type *Ty) const {
15514   assert(Ty->isIntegerTy());
15515 
15516   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15517   return !(BitSize == 0 || BitSize > 64);
15518 }
15519 
15520 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15521   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15522     return false;
15523   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15524   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15525   return NumBits1 == 64 && NumBits2 == 32;
15526 }
15527 
15528 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15529   if (!VT1.isInteger() || !VT2.isInteger())
15530     return false;
15531   unsigned NumBits1 = VT1.getSizeInBits();
15532   unsigned NumBits2 = VT2.getSizeInBits();
15533   return NumBits1 == 64 && NumBits2 == 32;
15534 }
15535 
15536 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15537   // Generally speaking, zexts are not free, but they are free when they can be
15538   // folded with other operations.
15539   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15540     EVT MemVT = LD->getMemoryVT();
15541     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15542          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15543         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15544          LD->getExtensionType() == ISD::ZEXTLOAD))
15545       return true;
15546   }
15547 
15548   // FIXME: Add other cases...
15549   //  - 32-bit shifts with a zext to i64
15550   //  - zext after ctlz, bswap, etc.
15551   //  - zext after and by a constant mask
15552 
15553   return TargetLowering::isZExtFree(Val, VT2);
15554 }
15555 
15556 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15557   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15558          "invalid fpext types");
15559   // Extending to float128 is not free.
15560   if (DestVT == MVT::f128)
15561     return false;
15562   return true;
15563 }
15564 
15565 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15566   return isInt<16>(Imm) || isUInt<16>(Imm);
15567 }
15568 
15569 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15570   return isInt<16>(Imm) || isUInt<16>(Imm);
15571 }
15572 
15573 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15574                                                        unsigned,
15575                                                        unsigned,
15576                                                        MachineMemOperand::Flags,
15577                                                        bool *Fast) const {
15578   if (DisablePPCUnaligned)
15579     return false;
15580 
15581   // PowerPC supports unaligned memory access for simple non-vector types.
15582   // Although accessing unaligned addresses is not as efficient as accessing
15583   // aligned addresses, it is generally more efficient than manual expansion,
15584   // and generally only traps for software emulation when crossing page
15585   // boundaries.
15586 
15587   if (!VT.isSimple())
15588     return false;
15589 
15590   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15591     return false;
15592 
15593   if (VT.getSimpleVT().isVector()) {
15594     if (Subtarget.hasVSX()) {
15595       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15596           VT != MVT::v4f32 && VT != MVT::v4i32)
15597         return false;
15598     } else {
15599       return false;
15600     }
15601   }
15602 
15603   if (VT == MVT::ppcf128)
15604     return false;
15605 
15606   if (Fast)
15607     *Fast = true;
15608 
15609   return true;
15610 }
15611 
15612 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15613                                                    EVT VT) const {
15614   return isFMAFasterThanFMulAndFAdd(
15615       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15616 }
15617 
15618 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15619                                                    Type *Ty) const {
15620   switch (Ty->getScalarType()->getTypeID()) {
15621   case Type::FloatTyID:
15622   case Type::DoubleTyID:
15623     return true;
15624   case Type::FP128TyID:
15625     return EnableQuadPrecision && Subtarget.hasP9Vector();
15626   default:
15627     return false;
15628   }
15629 }
15630 
15631 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15632 // FIXME: add more patterns which are profitable to hoist.
15633 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15634   if (I->getOpcode() != Instruction::FMul)
15635     return true;
15636 
15637   if (!I->hasOneUse())
15638     return true;
15639 
15640   Instruction *User = I->user_back();
15641   assert(User && "A single use instruction with no uses.");
15642 
15643   if (User->getOpcode() != Instruction::FSub &&
15644       User->getOpcode() != Instruction::FAdd)
15645     return true;
15646 
15647   const TargetOptions &Options = getTargetMachine().Options;
15648   const Function *F = I->getFunction();
15649   const DataLayout &DL = F->getParent()->getDataLayout();
15650   Type *Ty = User->getOperand(0)->getType();
15651 
15652   return !(
15653       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15654       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15655       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15656 }
15657 
15658 const MCPhysReg *
15659 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15660   // LR is a callee-save register, but we must treat it as clobbered by any call
15661   // site. Hence we include LR in the scratch registers, which are in turn added
15662   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15663   // to CTR, which is used by any indirect call.
15664   static const MCPhysReg ScratchRegs[] = {
15665     PPC::X12, PPC::LR8, PPC::CTR8, 0
15666   };
15667 
15668   return ScratchRegs;
15669 }
15670 
15671 Register PPCTargetLowering::getExceptionPointerRegister(
15672     const Constant *PersonalityFn) const {
15673   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15674 }
15675 
15676 Register PPCTargetLowering::getExceptionSelectorRegister(
15677     const Constant *PersonalityFn) const {
15678   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15679 }
15680 
15681 bool
15682 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15683                      EVT VT , unsigned DefinedValues) const {
15684   if (VT == MVT::v2i64)
15685     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15686 
15687   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15688     return true;
15689 
15690   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15691 }
15692 
15693 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15694   if (DisableILPPref || Subtarget.enableMachineScheduler())
15695     return TargetLowering::getSchedulingPreference(N);
15696 
15697   return Sched::ILP;
15698 }
15699 
15700 // Create a fast isel object.
15701 FastISel *
15702 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15703                                   const TargetLibraryInfo *LibInfo) const {
15704   return PPC::createFastISel(FuncInfo, LibInfo);
15705 }
15706 
15707 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15708   if (!Subtarget.isPPC64()) return;
15709 
15710   // Update IsSplitCSR in PPCFunctionInfo
15711   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15712   PFI->setIsSplitCSR(true);
15713 }
15714 
15715 void PPCTargetLowering::insertCopiesSplitCSR(
15716   MachineBasicBlock *Entry,
15717   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15718   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15719   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15720   if (!IStart)
15721     return;
15722 
15723   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15724   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15725   MachineBasicBlock::iterator MBBI = Entry->begin();
15726   for (const MCPhysReg *I = IStart; *I; ++I) {
15727     const TargetRegisterClass *RC = nullptr;
15728     if (PPC::G8RCRegClass.contains(*I))
15729       RC = &PPC::G8RCRegClass;
15730     else if (PPC::F8RCRegClass.contains(*I))
15731       RC = &PPC::F8RCRegClass;
15732     else if (PPC::CRRCRegClass.contains(*I))
15733       RC = &PPC::CRRCRegClass;
15734     else if (PPC::VRRCRegClass.contains(*I))
15735       RC = &PPC::VRRCRegClass;
15736     else
15737       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15738 
15739     Register NewVR = MRI->createVirtualRegister(RC);
15740     // Create copy from CSR to a virtual register.
15741     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15742     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15743     // nounwind. If we want to generalize this later, we may need to emit
15744     // CFI pseudo-instructions.
15745     assert(Entry->getParent()->getFunction().hasFnAttribute(
15746              Attribute::NoUnwind) &&
15747            "Function should be nounwind in insertCopiesSplitCSR!");
15748     Entry->addLiveIn(*I);
15749     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15750       .addReg(*I);
15751 
15752     // Insert the copy-back instructions right before the terminator.
15753     for (auto *Exit : Exits)
15754       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15755               TII->get(TargetOpcode::COPY), *I)
15756         .addReg(NewVR);
15757   }
15758 }
15759 
15760 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15761 bool PPCTargetLowering::useLoadStackGuardNode() const {
15762   if (!Subtarget.isTargetLinux())
15763     return TargetLowering::useLoadStackGuardNode();
15764   return true;
15765 }
15766 
15767 // Override to disable global variable loading on Linux.
15768 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15769   if (!Subtarget.isTargetLinux())
15770     return TargetLowering::insertSSPDeclarations(M);
15771 }
15772 
15773 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15774                                      bool ForCodeSize) const {
15775   if (!VT.isSimple() || !Subtarget.hasVSX())
15776     return false;
15777 
15778   switch(VT.getSimpleVT().SimpleTy) {
15779   default:
15780     // For FP types that are currently not supported by PPC backend, return
15781     // false. Examples: f16, f80.
15782     return false;
15783   case MVT::f32:
15784   case MVT::f64:
15785   case MVT::ppcf128:
15786     return Imm.isPosZero();
15787   }
15788 }
15789 
15790 // For vector shift operation op, fold
15791 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15792 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15793                                   SelectionDAG &DAG) {
15794   SDValue N0 = N->getOperand(0);
15795   SDValue N1 = N->getOperand(1);
15796   EVT VT = N0.getValueType();
15797   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15798   unsigned Opcode = N->getOpcode();
15799   unsigned TargetOpcode;
15800 
15801   switch (Opcode) {
15802   default:
15803     llvm_unreachable("Unexpected shift operation");
15804   case ISD::SHL:
15805     TargetOpcode = PPCISD::SHL;
15806     break;
15807   case ISD::SRL:
15808     TargetOpcode = PPCISD::SRL;
15809     break;
15810   case ISD::SRA:
15811     TargetOpcode = PPCISD::SRA;
15812     break;
15813   }
15814 
15815   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15816       N1->getOpcode() == ISD::AND)
15817     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15818       if (Mask->getZExtValue() == OpSizeInBits - 1)
15819         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15820 
15821   return SDValue();
15822 }
15823 
15824 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15825   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15826     return Value;
15827 
15828   SDValue N0 = N->getOperand(0);
15829   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15830   if (!Subtarget.isISA3_0() ||
15831       N0.getOpcode() != ISD::SIGN_EXTEND ||
15832       N0.getOperand(0).getValueType() != MVT::i32 ||
15833       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15834     return SDValue();
15835 
15836   // We can't save an operation here if the value is already extended, and
15837   // the existing shift is easier to combine.
15838   SDValue ExtsSrc = N0.getOperand(0);
15839   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15840       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15841     return SDValue();
15842 
15843   SDLoc DL(N0);
15844   SDValue ShiftBy = SDValue(CN1, 0);
15845   // We want the shift amount to be i32 on the extswli, but the shift could
15846   // have an i64.
15847   if (ShiftBy.getValueType() == MVT::i64)
15848     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15849 
15850   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15851                          ShiftBy);
15852 }
15853 
15854 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15855   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15856     return Value;
15857 
15858   return SDValue();
15859 }
15860 
15861 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15862   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15863     return Value;
15864 
15865   return SDValue();
15866 }
15867 
15868 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15869 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15870 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15871 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15872 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15873                                  const PPCSubtarget &Subtarget) {
15874   if (!Subtarget.isPPC64())
15875     return SDValue();
15876 
15877   SDValue LHS = N->getOperand(0);
15878   SDValue RHS = N->getOperand(1);
15879 
15880   auto isZextOfCompareWithConstant = [](SDValue Op) {
15881     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15882         Op.getValueType() != MVT::i64)
15883       return false;
15884 
15885     SDValue Cmp = Op.getOperand(0);
15886     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15887         Cmp.getOperand(0).getValueType() != MVT::i64)
15888       return false;
15889 
15890     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15891       int64_t NegConstant = 0 - Constant->getSExtValue();
15892       // Due to the limitations of the addi instruction,
15893       // -C is required to be [-32768, 32767].
15894       return isInt<16>(NegConstant);
15895     }
15896 
15897     return false;
15898   };
15899 
15900   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15901   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15902 
15903   // If there is a pattern, canonicalize a zext operand to the RHS.
15904   if (LHSHasPattern && !RHSHasPattern)
15905     std::swap(LHS, RHS);
15906   else if (!LHSHasPattern && !RHSHasPattern)
15907     return SDValue();
15908 
15909   SDLoc DL(N);
15910   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15911   SDValue Cmp = RHS.getOperand(0);
15912   SDValue Z = Cmp.getOperand(0);
15913   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15914 
15915   assert(Constant && "Constant Should not be a null pointer.");
15916   int64_t NegConstant = 0 - Constant->getSExtValue();
15917 
15918   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15919   default: break;
15920   case ISD::SETNE: {
15921     //                                 when C == 0
15922     //                             --> addze X, (addic Z, -1).carry
15923     //                            /
15924     // add X, (zext(setne Z, C))--
15925     //                            \    when -32768 <= -C <= 32767 && C != 0
15926     //                             --> addze X, (addic (addi Z, -C), -1).carry
15927     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15928                               DAG.getConstant(NegConstant, DL, MVT::i64));
15929     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15930     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15931                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15932     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15933                        SDValue(Addc.getNode(), 1));
15934     }
15935   case ISD::SETEQ: {
15936     //                                 when C == 0
15937     //                             --> addze X, (subfic Z, 0).carry
15938     //                            /
15939     // add X, (zext(sete  Z, C))--
15940     //                            \    when -32768 <= -C <= 32767 && C != 0
15941     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15942     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15943                               DAG.getConstant(NegConstant, DL, MVT::i64));
15944     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15945     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15946                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15947     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15948                        SDValue(Subc.getNode(), 1));
15949     }
15950   }
15951 
15952   return SDValue();
15953 }
15954 
15955 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15956   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15957     return Value;
15958 
15959   return SDValue();
15960 }
15961 
15962 // Detect TRUNCATE operations on bitcasts of float128 values.
15963 // What we are looking for here is the situtation where we extract a subset
15964 // of bits from a 128 bit float.
15965 // This can be of two forms:
15966 // 1) BITCAST of f128 feeding TRUNCATE
15967 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15968 // The reason this is required is because we do not have a legal i128 type
15969 // and so we want to prevent having to store the f128 and then reload part
15970 // of it.
15971 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15972                                            DAGCombinerInfo &DCI) const {
15973   // If we are using CRBits then try that first.
15974   if (Subtarget.useCRBits()) {
15975     // Check if CRBits did anything and return that if it did.
15976     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15977       return CRTruncValue;
15978   }
15979 
15980   SDLoc dl(N);
15981   SDValue Op0 = N->getOperand(0);
15982 
15983   // Looking for a truncate of i128 to i64.
15984   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15985     return SDValue();
15986 
15987   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15988 
15989   // SRL feeding TRUNCATE.
15990   if (Op0.getOpcode() == ISD::SRL) {
15991     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15992     // The right shift has to be by 64 bits.
15993     if (!ConstNode || ConstNode->getZExtValue() != 64)
15994       return SDValue();
15995 
15996     // Switch the element number to extract.
15997     EltToExtract = EltToExtract ? 0 : 1;
15998     // Update Op0 past the SRL.
15999     Op0 = Op0.getOperand(0);
16000   }
16001 
16002   // BITCAST feeding a TRUNCATE possibly via SRL.
16003   if (Op0.getOpcode() == ISD::BITCAST &&
16004       Op0.getValueType() == MVT::i128 &&
16005       Op0.getOperand(0).getValueType() == MVT::f128) {
16006     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16007     return DCI.DAG.getNode(
16008         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16009         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16010   }
16011   return SDValue();
16012 }
16013 
16014 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16015   SelectionDAG &DAG = DCI.DAG;
16016 
16017   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16018   if (!ConstOpOrElement)
16019     return SDValue();
16020 
16021   // An imul is usually smaller than the alternative sequence for legal type.
16022   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16023       isOperationLegal(ISD::MUL, N->getValueType(0)))
16024     return SDValue();
16025 
16026   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16027     switch (this->Subtarget.getCPUDirective()) {
16028     default:
16029       // TODO: enhance the condition for subtarget before pwr8
16030       return false;
16031     case PPC::DIR_PWR8:
16032       //  type        mul     add    shl
16033       // scalar        4       1      1
16034       // vector        7       2      2
16035       return true;
16036     case PPC::DIR_PWR9:
16037     case PPC::DIR_PWR_FUTURE:
16038       //  type        mul     add    shl
16039       // scalar        5       2      2
16040       // vector        7       2      2
16041 
16042       // The cycle RATIO of related operations are showed as a table above.
16043       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16044       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16045       // are 4, it is always profitable; but for 3 instrs patterns
16046       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16047       // So we should only do it for vector type.
16048       return IsAddOne && IsNeg ? VT.isVector() : true;
16049     }
16050   };
16051 
16052   EVT VT = N->getValueType(0);
16053   SDLoc DL(N);
16054 
16055   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16056   bool IsNeg = MulAmt.isNegative();
16057   APInt MulAmtAbs = MulAmt.abs();
16058 
16059   if ((MulAmtAbs - 1).isPowerOf2()) {
16060     // (mul x, 2^N + 1) => (add (shl x, N), x)
16061     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16062 
16063     if (!IsProfitable(IsNeg, true, VT))
16064       return SDValue();
16065 
16066     SDValue Op0 = N->getOperand(0);
16067     SDValue Op1 =
16068         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16069                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16070     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16071 
16072     if (!IsNeg)
16073       return Res;
16074 
16075     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16076   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16077     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16078     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16079 
16080     if (!IsProfitable(IsNeg, false, VT))
16081       return SDValue();
16082 
16083     SDValue Op0 = N->getOperand(0);
16084     SDValue Op1 =
16085         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16086                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16087 
16088     if (!IsNeg)
16089       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16090     else
16091       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16092 
16093   } else {
16094     return SDValue();
16095   }
16096 }
16097 
16098 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16099   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16100   if (!Subtarget.is64BitELFABI())
16101     return false;
16102 
16103   // If not a tail call then no need to proceed.
16104   if (!CI->isTailCall())
16105     return false;
16106 
16107   // If sibling calls have been disabled and tail-calls aren't guaranteed
16108   // there is no reason to duplicate.
16109   auto &TM = getTargetMachine();
16110   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16111     return false;
16112 
16113   // Can't tail call a function called indirectly, or if it has variadic args.
16114   const Function *Callee = CI->getCalledFunction();
16115   if (!Callee || Callee->isVarArg())
16116     return false;
16117 
16118   // Make sure the callee and caller calling conventions are eligible for tco.
16119   const Function *Caller = CI->getParent()->getParent();
16120   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16121                                            CI->getCallingConv()))
16122       return false;
16123 
16124   // If the function is local then we have a good chance at tail-calling it
16125   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16126 }
16127 
16128 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16129   if (!Subtarget.hasVSX())
16130     return false;
16131   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16132     return true;
16133   return VT == MVT::f32 || VT == MVT::f64 ||
16134     VT == MVT::v4f32 || VT == MVT::v2f64;
16135 }
16136 
16137 bool PPCTargetLowering::
16138 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16139   const Value *Mask = AndI.getOperand(1);
16140   // If the mask is suitable for andi. or andis. we should sink the and.
16141   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16142     // Can't handle constants wider than 64-bits.
16143     if (CI->getBitWidth() > 64)
16144       return false;
16145     int64_t ConstVal = CI->getZExtValue();
16146     return isUInt<16>(ConstVal) ||
16147       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16148   }
16149 
16150   // For non-constant masks, we can always use the record-form and.
16151   return true;
16152 }
16153 
16154 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16155 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16156 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16157 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16158 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16159 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16160   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16161   assert(Subtarget.hasP9Altivec() &&
16162          "Only combine this when P9 altivec supported!");
16163   EVT VT = N->getValueType(0);
16164   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16165     return SDValue();
16166 
16167   SelectionDAG &DAG = DCI.DAG;
16168   SDLoc dl(N);
16169   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16170     // Even for signed integers, if it's known to be positive (as signed
16171     // integer) due to zero-extended inputs.
16172     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16173     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16174     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16175          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16176         (SubOpcd1 == ISD::ZERO_EXTEND ||
16177          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16178       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16179                          N->getOperand(0)->getOperand(0),
16180                          N->getOperand(0)->getOperand(1),
16181                          DAG.getTargetConstant(0, dl, MVT::i32));
16182     }
16183 
16184     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16185     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16186         N->getOperand(0).hasOneUse()) {
16187       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16188                          N->getOperand(0)->getOperand(0),
16189                          N->getOperand(0)->getOperand(1),
16190                          DAG.getTargetConstant(1, dl, MVT::i32));
16191     }
16192   }
16193 
16194   return SDValue();
16195 }
16196 
16197 // For type v4i32/v8ii16/v16i8, transform
16198 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16199 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16200 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16201 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16202 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16203                                           DAGCombinerInfo &DCI) const {
16204   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16205   assert(Subtarget.hasP9Altivec() &&
16206          "Only combine this when P9 altivec supported!");
16207 
16208   SelectionDAG &DAG = DCI.DAG;
16209   SDLoc dl(N);
16210   SDValue Cond = N->getOperand(0);
16211   SDValue TrueOpnd = N->getOperand(1);
16212   SDValue FalseOpnd = N->getOperand(2);
16213   EVT VT = N->getOperand(1).getValueType();
16214 
16215   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16216       FalseOpnd.getOpcode() != ISD::SUB)
16217     return SDValue();
16218 
16219   // ABSD only available for type v4i32/v8i16/v16i8
16220   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16221     return SDValue();
16222 
16223   // At least to save one more dependent computation
16224   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16225     return SDValue();
16226 
16227   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16228 
16229   // Can only handle unsigned comparison here
16230   switch (CC) {
16231   default:
16232     return SDValue();
16233   case ISD::SETUGT:
16234   case ISD::SETUGE:
16235     break;
16236   case ISD::SETULT:
16237   case ISD::SETULE:
16238     std::swap(TrueOpnd, FalseOpnd);
16239     break;
16240   }
16241 
16242   SDValue CmpOpnd1 = Cond.getOperand(0);
16243   SDValue CmpOpnd2 = Cond.getOperand(1);
16244 
16245   // SETCC CmpOpnd1 CmpOpnd2 cond
16246   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16247   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16248   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16249       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16250       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16251       FalseOpnd.getOperand(1) == CmpOpnd1) {
16252     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16253                        CmpOpnd1, CmpOpnd2,
16254                        DAG.getTargetConstant(0, dl, MVT::i32));
16255   }
16256 
16257   return SDValue();
16258 }
16259