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/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSymbolXCOFF.h"
78 #include "llvm/Support/AtomicOrdering.h"
79 #include "llvm/Support/BranchProbability.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/CodeGen.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/KnownBits.h"
88 #include "llvm/Support/MachineValueType.h"
89 #include "llvm/Support/MathExtras.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Target/TargetMachine.h"
92 #include "llvm/Target/TargetOptions.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <iterator>
97 #include <list>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 
103 #define DEBUG_TYPE "ppc-lowering"
104 
105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
113 
114 static cl::opt<bool> DisableSCO("disable-ppc-sco",
115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
116 
117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
119 
120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
121 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
122 
123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
124 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
125 
126 STATISTIC(NumTailCalls, "Number of tail calls");
127 STATISTIC(NumSiblingCalls, "Number of sibling calls");
128 
129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
130 
131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
132 
133 // FIXME: Remove this once the bug has been fixed!
134 extern cl::opt<bool> ANDIGlueBug;
135 
136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
137                                      const PPCSubtarget &STI)
138     : TargetLowering(TM), Subtarget(STI) {
139   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
140   // arguments are at least 4/8 bytes aligned.
141   bool isPPC64 = Subtarget.isPPC64();
142   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
143 
144   // Set up the register classes.
145   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
146   if (!useSoftFloat()) {
147     if (hasSPE()) {
148       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
149       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
150     } else {
151       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
152       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
153     }
154   }
155 
156   // Match BITREVERSE to customized fast code sequence in the td file.
157   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
158   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
159 
160   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
161   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
162 
163   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
164   for (MVT VT : MVT::integer_valuetypes()) {
165     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
167   }
168 
169   if (Subtarget.isISA3_0()) {
170     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
171     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
172     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
174   } else {
175     // No extending loads from f16 or HW conversions back and forth.
176     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
177     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
178     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
179     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
180     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
181     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
182     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
183     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
184   }
185 
186   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
187 
188   // PowerPC has pre-inc load and store's.
189   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
194   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
199   if (!Subtarget.hasSPE()) {
200     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
202     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
204   }
205 
206   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
207   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
208   for (MVT VT : ScalarIntVTs) {
209     setOperationAction(ISD::ADDC, VT, Legal);
210     setOperationAction(ISD::ADDE, VT, Legal);
211     setOperationAction(ISD::SUBC, VT, Legal);
212     setOperationAction(ISD::SUBE, VT, Legal);
213   }
214 
215   if (Subtarget.useCRBits()) {
216     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
217 
218     if (isPPC64 || Subtarget.hasFPCVT()) {
219       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
220       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
221                          isPPC64 ? MVT::i64 : MVT::i32);
222       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
223       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
224                         isPPC64 ? MVT::i64 : MVT::i32);
225     } else {
226       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
227       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
228     }
229 
230     // PowerPC does not support direct load/store of condition registers.
231     setOperationAction(ISD::LOAD, MVT::i1, Custom);
232     setOperationAction(ISD::STORE, MVT::i1, Custom);
233 
234     // FIXME: Remove this once the ANDI glue bug is fixed:
235     if (ANDIGlueBug)
236       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
237 
238     for (MVT VT : MVT::integer_valuetypes()) {
239       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
240       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
241       setTruncStoreAction(VT, MVT::i1, Expand);
242     }
243 
244     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
245   }
246 
247   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
248   // PPC (the libcall is not available).
249   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
250   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
251 
252   // We do not currently implement these libm ops for PowerPC.
253   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
254   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
255   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
256   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
257   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
258   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
259 
260   // PowerPC has no SREM/UREM instructions unless we are on P9
261   // On P9 we may use a hardware instruction to compute the remainder.
262   // The instructions are not legalized directly because in the cases where the
263   // result of both the remainder and the division is required it is more
264   // efficient to compute the remainder from the result of the division rather
265   // than use the remainder instruction.
266   if (Subtarget.isISA3_0()) {
267     setOperationAction(ISD::SREM, MVT::i32, Custom);
268     setOperationAction(ISD::UREM, MVT::i32, Custom);
269     setOperationAction(ISD::SREM, MVT::i64, Custom);
270     setOperationAction(ISD::UREM, MVT::i64, Custom);
271   } else {
272     setOperationAction(ISD::SREM, MVT::i32, Expand);
273     setOperationAction(ISD::UREM, MVT::i32, Expand);
274     setOperationAction(ISD::SREM, MVT::i64, Expand);
275     setOperationAction(ISD::UREM, MVT::i64, Expand);
276   }
277 
278   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
279   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
280   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
282   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
284   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
286   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
287 
288   // Handle constrained floating-point operations of scalar.
289   // TODO: Handle SPE specific operation.
290   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
291   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
292   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
293   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FMA, 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   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
301 
302   if (Subtarget.hasFSQRT()) {
303     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
304     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
305   }
306 
307   // We don't support sin/cos/sqrt/fmod/pow
308   setOperationAction(ISD::FSIN , MVT::f64, Expand);
309   setOperationAction(ISD::FCOS , MVT::f64, Expand);
310   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
311   setOperationAction(ISD::FREM , MVT::f64, Expand);
312   setOperationAction(ISD::FPOW , MVT::f64, Expand);
313   setOperationAction(ISD::FSIN , MVT::f32, Expand);
314   setOperationAction(ISD::FCOS , MVT::f32, Expand);
315   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
316   setOperationAction(ISD::FREM , MVT::f32, Expand);
317   setOperationAction(ISD::FPOW , MVT::f32, Expand);
318   if (Subtarget.hasSPE()) {
319     setOperationAction(ISD::FMA  , MVT::f64, Expand);
320     setOperationAction(ISD::FMA  , MVT::f32, Expand);
321   } else {
322     setOperationAction(ISD::FMA  , MVT::f64, Legal);
323     setOperationAction(ISD::FMA  , MVT::f32, Legal);
324   }
325 
326   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
327 
328   // If we're enabling GP optimizations, use hardware square root
329   if (!Subtarget.hasFSQRT() &&
330       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
331         Subtarget.hasFRE()))
332     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
333 
334   if (!Subtarget.hasFSQRT() &&
335       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
336         Subtarget.hasFRES()))
337     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
338 
339   if (Subtarget.hasFCPSGN()) {
340     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
341     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
342   } else {
343     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
344     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
345   }
346 
347   if (Subtarget.hasFPRND()) {
348     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
349     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
350     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
351     setOperationAction(ISD::FROUND, MVT::f64, Legal);
352 
353     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
354     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
355     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
356     setOperationAction(ISD::FROUND, MVT::f32, Legal);
357   }
358 
359   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
360   // to speed up scalar BSWAP64.
361   // CTPOP or CTTZ were introduced in P8/P9 respectively
362   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
363   if (Subtarget.hasP9Vector())
364     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
365   else
366     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
367   if (Subtarget.isISA3_0()) {
368     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
369     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
370   } else {
371     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
372     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
373   }
374 
375   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
376     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
377     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
378   } else {
379     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
380     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
381   }
382 
383   // PowerPC does not have ROTR
384   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
385   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
386 
387   if (!Subtarget.useCRBits()) {
388     // PowerPC does not have Select
389     setOperationAction(ISD::SELECT, MVT::i32, Expand);
390     setOperationAction(ISD::SELECT, MVT::i64, Expand);
391     setOperationAction(ISD::SELECT, MVT::f32, Expand);
392     setOperationAction(ISD::SELECT, MVT::f64, Expand);
393   }
394 
395   // PowerPC wants to turn select_cc of FP into fsel when possible.
396   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
397   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
398 
399   // PowerPC wants to optimize integer setcc a bit
400   if (!Subtarget.useCRBits())
401     setOperationAction(ISD::SETCC, MVT::i32, Custom);
402 
403   // PowerPC does not have BRCOND which requires SetCC
404   if (!Subtarget.useCRBits())
405     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
406 
407   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
408 
409   if (Subtarget.hasSPE()) {
410     // SPE has built-in conversions
411     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
412     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
413     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
414   } else {
415     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
416     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
417 
418     // PowerPC does not have [U|S]INT_TO_FP
419     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
420     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
421   }
422 
423   if (Subtarget.hasDirectMove() && isPPC64) {
424     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
425     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
426     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
427     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
428     if (TM.Options.UnsafeFPMath) {
429       setOperationAction(ISD::LRINT, MVT::f64, Legal);
430       setOperationAction(ISD::LRINT, MVT::f32, Legal);
431       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
432       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
433       setOperationAction(ISD::LROUND, MVT::f64, Legal);
434       setOperationAction(ISD::LROUND, MVT::f32, Legal);
435       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
436       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
437     }
438   } else {
439     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
440     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
441     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
442     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
443   }
444 
445   // We cannot sextinreg(i1).  Expand to shifts.
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
447 
448   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
449   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
450   // support continuation, user-level threading, and etc.. As a result, no
451   // other SjLj exception interfaces are implemented and please don't build
452   // your own exception handling based on them.
453   // LLVM/Clang supports zero-cost DWARF exception handling.
454   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
455   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
456 
457   // We want to legalize GlobalAddress and ConstantPool nodes into the
458   // appropriate instructions to materialize the address.
459   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
460   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
461   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
462   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
463   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
464   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
465   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
467   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
468   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
469 
470   // TRAP is legal.
471   setOperationAction(ISD::TRAP, MVT::Other, Legal);
472 
473   // TRAMPOLINE is custom lowered.
474   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
475   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
476 
477   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
478   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
479 
480   if (Subtarget.is64BitELFABI()) {
481     // VAARG always uses double-word chunks, so promote anything smaller.
482     setOperationAction(ISD::VAARG, MVT::i1, Promote);
483     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
484     setOperationAction(ISD::VAARG, MVT::i8, Promote);
485     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
486     setOperationAction(ISD::VAARG, MVT::i16, Promote);
487     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
488     setOperationAction(ISD::VAARG, MVT::i32, Promote);
489     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
490     setOperationAction(ISD::VAARG, MVT::Other, Expand);
491   } else if (Subtarget.is32BitELFABI()) {
492     // VAARG is custom lowered with the 32-bit SVR4 ABI.
493     setOperationAction(ISD::VAARG, MVT::Other, Custom);
494     setOperationAction(ISD::VAARG, MVT::i64, Custom);
495   } else
496     setOperationAction(ISD::VAARG, MVT::Other, Expand);
497 
498   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
499   if (Subtarget.is32BitELFABI())
500     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
501   else
502     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
503 
504   // Use the default implementation.
505   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
506   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
507   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
509   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
510   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
511   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
512   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
513   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
514 
515   // We want to custom lower some of our intrinsics.
516   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
517 
518   // To handle counter-based loop conditions.
519   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
520 
521   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
522   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
523   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
524   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
525 
526   // Comparisons that require checking two conditions.
527   if (Subtarget.hasSPE()) {
528     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
529     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
530     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
531     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
532   }
533   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
534   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
535   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
536   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
537   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
538   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
539   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
540   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
541   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
542   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
543   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
544   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
545 
546   if (Subtarget.has64BitSupport()) {
547     // They also have instructions for converting between i64 and fp.
548     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
549     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
550     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
551     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
552     // This is just the low 32 bits of a (signed) fp->i64 conversion.
553     // We cannot do this with Promote because i64 is not a legal type.
554     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
555 
556     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
557       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
558   } else {
559     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
560     if (Subtarget.hasSPE())
561       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
562     else
563       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
564   }
565 
566   // With the instructions enabled under FPCVT, we can do everything.
567   if (Subtarget.hasFPCVT()) {
568     if (Subtarget.has64BitSupport()) {
569       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
570       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
571       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
572       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
573     }
574 
575     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
576     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
577     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
578     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
579   }
580 
581   if (Subtarget.use64BitRegs()) {
582     // 64-bit PowerPC implementations can support i64 types directly
583     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
584     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
585     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
586     // 64-bit PowerPC wants to expand i128 shifts itself.
587     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
588     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
589     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
590   } else {
591     // 32-bit PowerPC wants to expand i64 shifts itself.
592     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
593     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
594     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
595   }
596 
597   if (Subtarget.hasVSX()) {
598     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
599     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
600     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
601     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
602   }
603 
604   if (Subtarget.hasAltivec()) {
605     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
606       setOperationAction(ISD::SADDSAT, VT, Legal);
607       setOperationAction(ISD::SSUBSAT, VT, Legal);
608       setOperationAction(ISD::UADDSAT, VT, Legal);
609       setOperationAction(ISD::USUBSAT, VT, Legal);
610     }
611     // First set operation action for all vector types to expand. Then we
612     // will selectively turn on ones that can be effectively codegen'd.
613     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
614       // add/sub are legal for all supported vector VT's.
615       setOperationAction(ISD::ADD, VT, Legal);
616       setOperationAction(ISD::SUB, VT, Legal);
617 
618       // For v2i64, these are only valid with P8Vector. This is corrected after
619       // the loop.
620       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
621         setOperationAction(ISD::SMAX, VT, Legal);
622         setOperationAction(ISD::SMIN, VT, Legal);
623         setOperationAction(ISD::UMAX, VT, Legal);
624         setOperationAction(ISD::UMIN, VT, Legal);
625       }
626       else {
627         setOperationAction(ISD::SMAX, VT, Expand);
628         setOperationAction(ISD::SMIN, VT, Expand);
629         setOperationAction(ISD::UMAX, VT, Expand);
630         setOperationAction(ISD::UMIN, VT, Expand);
631       }
632 
633       if (Subtarget.hasVSX()) {
634         setOperationAction(ISD::FMAXNUM, VT, Legal);
635         setOperationAction(ISD::FMINNUM, VT, Legal);
636       }
637 
638       // Vector instructions introduced in P8
639       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
640         setOperationAction(ISD::CTPOP, VT, Legal);
641         setOperationAction(ISD::CTLZ, VT, Legal);
642       }
643       else {
644         setOperationAction(ISD::CTPOP, VT, Expand);
645         setOperationAction(ISD::CTLZ, VT, Expand);
646       }
647 
648       // Vector instructions introduced in P9
649       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
650         setOperationAction(ISD::CTTZ, VT, Legal);
651       else
652         setOperationAction(ISD::CTTZ, VT, Expand);
653 
654       // We promote all shuffles to v16i8.
655       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
656       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
657 
658       // We promote all non-typed operations to v4i32.
659       setOperationAction(ISD::AND   , VT, Promote);
660       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
661       setOperationAction(ISD::OR    , VT, Promote);
662       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
663       setOperationAction(ISD::XOR   , VT, Promote);
664       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
665       setOperationAction(ISD::LOAD  , VT, Promote);
666       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
667       setOperationAction(ISD::SELECT, VT, Promote);
668       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
669       setOperationAction(ISD::VSELECT, VT, Legal);
670       setOperationAction(ISD::SELECT_CC, VT, Promote);
671       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
672       setOperationAction(ISD::STORE, VT, Promote);
673       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
674 
675       // No other operations are legal.
676       setOperationAction(ISD::MUL , VT, Expand);
677       setOperationAction(ISD::SDIV, VT, Expand);
678       setOperationAction(ISD::SREM, VT, Expand);
679       setOperationAction(ISD::UDIV, VT, Expand);
680       setOperationAction(ISD::UREM, VT, Expand);
681       setOperationAction(ISD::FDIV, VT, Expand);
682       setOperationAction(ISD::FREM, VT, Expand);
683       setOperationAction(ISD::FNEG, VT, Expand);
684       setOperationAction(ISD::FSQRT, VT, Expand);
685       setOperationAction(ISD::FLOG, VT, Expand);
686       setOperationAction(ISD::FLOG10, VT, Expand);
687       setOperationAction(ISD::FLOG2, VT, Expand);
688       setOperationAction(ISD::FEXP, VT, Expand);
689       setOperationAction(ISD::FEXP2, VT, Expand);
690       setOperationAction(ISD::FSIN, VT, Expand);
691       setOperationAction(ISD::FCOS, VT, Expand);
692       setOperationAction(ISD::FABS, VT, Expand);
693       setOperationAction(ISD::FFLOOR, VT, Expand);
694       setOperationAction(ISD::FCEIL,  VT, Expand);
695       setOperationAction(ISD::FTRUNC, VT, Expand);
696       setOperationAction(ISD::FRINT,  VT, Expand);
697       setOperationAction(ISD::FNEARBYINT, VT, Expand);
698       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
699       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
700       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
701       setOperationAction(ISD::MULHU, VT, Expand);
702       setOperationAction(ISD::MULHS, VT, Expand);
703       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
705       setOperationAction(ISD::UDIVREM, VT, Expand);
706       setOperationAction(ISD::SDIVREM, VT, Expand);
707       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
708       setOperationAction(ISD::FPOW, VT, Expand);
709       setOperationAction(ISD::BSWAP, VT, Expand);
710       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
711       setOperationAction(ISD::ROTL, VT, Expand);
712       setOperationAction(ISD::ROTR, VT, Expand);
713 
714       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
715         setTruncStoreAction(VT, InnerVT, Expand);
716         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
717         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
718         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
719       }
720     }
721     if (!Subtarget.hasP8Vector()) {
722       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
723       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
724       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
725       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
726     }
727 
728     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
729       setOperationAction(ISD::ABS, VT, Custom);
730 
731     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
732     // with merges, splats, etc.
733     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
734 
735     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
736     // are cheap, so handle them before they get expanded to scalar.
737     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
738     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
739     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
740     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
741     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
742 
743     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
744     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
745     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
746     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
747     setOperationAction(ISD::SELECT, MVT::v4i32,
748                        Subtarget.useCRBits() ? Legal : Expand);
749     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
750     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
751     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
752     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
753     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
754     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
755     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
756     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
757     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
758 
759     // Without hasP8Altivec set, v2i64 SMAX isn't available.
760     // But ABS custom lowering requires SMAX support.
761     if (!Subtarget.hasP8Altivec())
762       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
763 
764     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
765     if (Subtarget.hasAltivec())
766       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
767         setOperationAction(ISD::ROTL, VT, Legal);
768     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
769     if (Subtarget.hasP8Altivec())
770       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
771 
772     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
773     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
774     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
775     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
776 
777     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
778     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
779 
780     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
781       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
782       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
783     }
784 
785     if (Subtarget.hasP8Altivec())
786       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
787     else
788       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
789 
790     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
791     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
792 
793     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
794     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
795 
796     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
797     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
798     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
799     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
800 
801     // Altivec does not contain unordered floating-point compare instructions
802     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
803     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
804     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
805     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
806 
807     if (Subtarget.hasVSX()) {
808       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
809       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
810       if (Subtarget.hasP8Vector()) {
811         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
812         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
813       }
814       if (Subtarget.hasDirectMove() && isPPC64) {
815         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
816         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
817         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
818         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
819         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
820         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
821         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
822         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
823       }
824       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
825 
826       // The nearbyint variants are not allowed to raise the inexact exception
827       // so we can only code-gen them with unsafe math.
828       if (TM.Options.UnsafeFPMath) {
829         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
830         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
831       }
832 
833       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
834       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
835       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
836       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
837       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
838       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
839       setOperationAction(ISD::FROUND, MVT::f64, Legal);
840       setOperationAction(ISD::FRINT, MVT::f64, Legal);
841 
842       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
843       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
844       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
845       setOperationAction(ISD::FROUND, MVT::f32, Legal);
846       setOperationAction(ISD::FRINT, MVT::f32, Legal);
847 
848       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
849       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
850 
851       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
852       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
853 
854       // Share the Altivec comparison restrictions.
855       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
856       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
857       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
858       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
859 
860       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
861       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
862 
863       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
864 
865       if (Subtarget.hasP8Vector())
866         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
867 
868       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
869 
870       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
871       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
872       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
873 
874       if (Subtarget.hasP8Altivec()) {
875         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
876         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
877         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
878 
879         // 128 bit shifts can be accomplished via 3 instructions for SHL and
880         // SRL, but not for SRA because of the instructions available:
881         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
882         // doing
883         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
884         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
885         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
886 
887         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
888       }
889       else {
890         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
891         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
892         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
893 
894         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
895 
896         // VSX v2i64 only supports non-arithmetic operations.
897         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
898         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
899       }
900 
901       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
902       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
903       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
904       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
905 
906       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
907 
908       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
909       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
910       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
911       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
912 
913       // Custom handling for partial vectors of integers converted to
914       // floating point. We already have optimal handling for v2i32 through
915       // the DAG combine, so those aren't necessary.
916       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
917       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
918       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
919       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
920       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
921       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
922       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
923       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
924 
925       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
926       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
927       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
928       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
929       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
930       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
931 
932       if (Subtarget.hasDirectMove())
933         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
934       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
935 
936       // Handle constrained floating-point operations of vector.
937       // The predictor is `hasVSX` because altivec instruction has
938       // no exception but VSX vector instruction has.
939       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
940       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
941       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
942       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
943       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
944       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
945       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
946       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
947 
948       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
949       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
950       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
951       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
952       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
953       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
954       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
955       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
956 
957       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
958     }
959 
960     if (Subtarget.hasP8Altivec()) {
961       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
962       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
963     }
964 
965     if (Subtarget.hasP9Vector()) {
966       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
967       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
968 
969       // 128 bit shifts can be accomplished via 3 instructions for SHL and
970       // SRL, but not for SRA because of the instructions available:
971       // VS{RL} and VS{RL}O.
972       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
973       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
974       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
975 
976       if (EnableQuadPrecision) {
977         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
978         setOperationAction(ISD::FADD, MVT::f128, Legal);
979         setOperationAction(ISD::FSUB, MVT::f128, Legal);
980         setOperationAction(ISD::FDIV, MVT::f128, Legal);
981         setOperationAction(ISD::FMUL, MVT::f128, Legal);
982         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
983         // No extending loads to f128 on PPC.
984         for (MVT FPT : MVT::fp_valuetypes())
985           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
986         setOperationAction(ISD::FMA, MVT::f128, Legal);
987         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
988         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
989         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
990         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
991         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
992         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
993 
994         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
995         setOperationAction(ISD::FRINT, MVT::f128, Legal);
996         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
997         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
998         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
999         setOperationAction(ISD::FROUND, MVT::f128, Legal);
1000 
1001         setOperationAction(ISD::SELECT, MVT::f128, Expand);
1002         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1003         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1004         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1005         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1006         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1007         // No implementation for these ops for PowerPC.
1008         setOperationAction(ISD::FSIN , MVT::f128, Expand);
1009         setOperationAction(ISD::FCOS , MVT::f128, Expand);
1010         setOperationAction(ISD::FPOW, MVT::f128, Expand);
1011         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1012         setOperationAction(ISD::FREM, MVT::f128, Expand);
1013 
1014         // Handle constrained floating-point operations of fp128
1015         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1016         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1017         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1018         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1019         setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1020         setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1021       }
1022       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1023       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1024       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1025       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1026       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1027     }
1028 
1029     if (Subtarget.hasP9Altivec()) {
1030       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1031       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1032 
1033       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1034       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1035       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1036       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1037       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1038       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1039       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1040     }
1041   }
1042 
1043   if (Subtarget.hasQPX()) {
1044     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1045     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1046     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1047     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1048 
1049     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1050     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1051 
1052     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1053     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1054 
1055     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1056     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1057 
1058     if (!Subtarget.useCRBits())
1059       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1060     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1061 
1062     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1063     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1064     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1065     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1066     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1067     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1068     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1069 
1070     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1071     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1072 
1073     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1074     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1075 
1076     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1077     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1078     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1079     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1080     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1081     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1082     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1083     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1084     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1085     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1086 
1087     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1088     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1089 
1090     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1091     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1092 
1093     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1094 
1095     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1096     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1097     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1098     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1099 
1100     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1101     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1102 
1103     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1104     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1105 
1106     if (!Subtarget.useCRBits())
1107       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1108     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1109 
1110     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1111     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1112     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1113     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1114     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1115     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1116     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1117 
1118     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1119     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1120 
1121     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1122     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1123     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1124     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1125     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1126     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1127     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1128     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1129     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1130     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1131 
1132     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1133     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1134 
1135     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1136     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1137 
1138     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1139 
1140     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1141     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1142     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1143 
1144     if (!Subtarget.useCRBits())
1145       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1146     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1147 
1148     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1149     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1150 
1151     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1152     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1153     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1154     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1155     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1156     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1157     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1158 
1159     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1160     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1161 
1162     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1163 
1164     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1165     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1166     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1167     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1168 
1169     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1170     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1171     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1172     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1173 
1174     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1175     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1176 
1177     // These need to set FE_INEXACT, and so cannot be vectorized here.
1178     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1179     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1180 
1181     if (TM.Options.UnsafeFPMath) {
1182       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1183       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1184 
1185       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1186       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1187     } else {
1188       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1189       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1190 
1191       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1192       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1193     }
1194 
1195     // TODO: Handle constrained floating-point operations of v4f64
1196   }
1197 
1198   if (Subtarget.has64BitSupport())
1199     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1200 
1201   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1202 
1203   if (!isPPC64) {
1204     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1205     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1206   }
1207 
1208   setBooleanContents(ZeroOrOneBooleanContent);
1209 
1210   if (Subtarget.hasAltivec()) {
1211     // Altivec instructions set fields to all zeros or all ones.
1212     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1213   }
1214 
1215   if (!isPPC64) {
1216     // These libcalls are not available in 32-bit.
1217     setLibcallName(RTLIB::SHL_I128, nullptr);
1218     setLibcallName(RTLIB::SRL_I128, nullptr);
1219     setLibcallName(RTLIB::SRA_I128, nullptr);
1220   }
1221 
1222   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1223 
1224   // We have target-specific dag combine patterns for the following nodes:
1225   setTargetDAGCombine(ISD::ADD);
1226   setTargetDAGCombine(ISD::SHL);
1227   setTargetDAGCombine(ISD::SRA);
1228   setTargetDAGCombine(ISD::SRL);
1229   setTargetDAGCombine(ISD::MUL);
1230   setTargetDAGCombine(ISD::SINT_TO_FP);
1231   setTargetDAGCombine(ISD::BUILD_VECTOR);
1232   if (Subtarget.hasFPCVT())
1233     setTargetDAGCombine(ISD::UINT_TO_FP);
1234   setTargetDAGCombine(ISD::LOAD);
1235   setTargetDAGCombine(ISD::STORE);
1236   setTargetDAGCombine(ISD::BR_CC);
1237   if (Subtarget.useCRBits())
1238     setTargetDAGCombine(ISD::BRCOND);
1239   setTargetDAGCombine(ISD::BSWAP);
1240   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1241   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1242   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1243 
1244   setTargetDAGCombine(ISD::SIGN_EXTEND);
1245   setTargetDAGCombine(ISD::ZERO_EXTEND);
1246   setTargetDAGCombine(ISD::ANY_EXTEND);
1247 
1248   setTargetDAGCombine(ISD::TRUNCATE);
1249   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1250 
1251 
1252   if (Subtarget.useCRBits()) {
1253     setTargetDAGCombine(ISD::TRUNCATE);
1254     setTargetDAGCombine(ISD::SETCC);
1255     setTargetDAGCombine(ISD::SELECT_CC);
1256   }
1257 
1258   // Use reciprocal estimates.
1259   if (TM.Options.UnsafeFPMath) {
1260     setTargetDAGCombine(ISD::FDIV);
1261     setTargetDAGCombine(ISD::FSQRT);
1262   }
1263 
1264   if (Subtarget.hasP9Altivec()) {
1265     setTargetDAGCombine(ISD::ABS);
1266     setTargetDAGCombine(ISD::VSELECT);
1267   }
1268 
1269   if (EnableQuadPrecision) {
1270     setLibcallName(RTLIB::LOG_F128, "logf128");
1271     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1272     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1273     setLibcallName(RTLIB::EXP_F128, "expf128");
1274     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1275     setLibcallName(RTLIB::SIN_F128, "sinf128");
1276     setLibcallName(RTLIB::COS_F128, "cosf128");
1277     setLibcallName(RTLIB::POW_F128, "powf128");
1278     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1279     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1280     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1281     setLibcallName(RTLIB::REM_F128, "fmodf128");
1282   }
1283 
1284   // With 32 condition bits, we don't need to sink (and duplicate) compares
1285   // aggressively in CodeGenPrep.
1286   if (Subtarget.useCRBits()) {
1287     setHasMultipleConditionRegisters();
1288     setJumpIsExpensive();
1289   }
1290 
1291   setMinFunctionAlignment(Align(4));
1292 
1293   switch (Subtarget.getCPUDirective()) {
1294   default: break;
1295   case PPC::DIR_970:
1296   case PPC::DIR_A2:
1297   case PPC::DIR_E500:
1298   case PPC::DIR_E500mc:
1299   case PPC::DIR_E5500:
1300   case PPC::DIR_PWR4:
1301   case PPC::DIR_PWR5:
1302   case PPC::DIR_PWR5X:
1303   case PPC::DIR_PWR6:
1304   case PPC::DIR_PWR6X:
1305   case PPC::DIR_PWR7:
1306   case PPC::DIR_PWR8:
1307   case PPC::DIR_PWR9:
1308   case PPC::DIR_PWR_FUTURE:
1309     setPrefLoopAlignment(Align(16));
1310     setPrefFunctionAlignment(Align(16));
1311     break;
1312   }
1313 
1314   if (Subtarget.enableMachineScheduler())
1315     setSchedulingPreference(Sched::Source);
1316   else
1317     setSchedulingPreference(Sched::Hybrid);
1318 
1319   computeRegisterProperties(STI.getRegisterInfo());
1320 
1321   // The Freescale cores do better with aggressive inlining of memcpy and
1322   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1323   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1324       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1325     MaxStoresPerMemset = 32;
1326     MaxStoresPerMemsetOptSize = 16;
1327     MaxStoresPerMemcpy = 32;
1328     MaxStoresPerMemcpyOptSize = 8;
1329     MaxStoresPerMemmove = 32;
1330     MaxStoresPerMemmoveOptSize = 8;
1331   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1332     // The A2 also benefits from (very) aggressive inlining of memcpy and
1333     // friends. The overhead of a the function call, even when warm, can be
1334     // over one hundred cycles.
1335     MaxStoresPerMemset = 128;
1336     MaxStoresPerMemcpy = 128;
1337     MaxStoresPerMemmove = 128;
1338     MaxLoadsPerMemcmp = 128;
1339   } else {
1340     MaxLoadsPerMemcmp = 8;
1341     MaxLoadsPerMemcmpOptSize = 4;
1342   }
1343 
1344   // Let the subtarget (CPU) decide if a predictable select is more expensive
1345   // than the corresponding branch. This information is used in CGP to decide
1346   // when to convert selects into branches.
1347   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1348 }
1349 
1350 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1351 /// the desired ByVal argument alignment.
1352 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1353                              unsigned MaxMaxAlign) {
1354   if (MaxAlign == MaxMaxAlign)
1355     return;
1356   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1357     if (MaxMaxAlign >= 32 &&
1358         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1359       MaxAlign = 32;
1360     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1361              MaxAlign < 16)
1362       MaxAlign = 16;
1363   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1364     unsigned EltAlign = 0;
1365     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1366     if (EltAlign > MaxAlign)
1367       MaxAlign = EltAlign;
1368   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1369     for (auto *EltTy : STy->elements()) {
1370       unsigned EltAlign = 0;
1371       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1372       if (EltAlign > MaxAlign)
1373         MaxAlign = EltAlign;
1374       if (MaxAlign == MaxMaxAlign)
1375         break;
1376     }
1377   }
1378 }
1379 
1380 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1381 /// function arguments in the caller parameter area.
1382 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1383                                                   const DataLayout &DL) const {
1384   // 16byte and wider vectors are passed on 16byte boundary.
1385   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1386   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1387   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1388     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1389   return Align;
1390 }
1391 
1392 bool PPCTargetLowering::useSoftFloat() const {
1393   return Subtarget.useSoftFloat();
1394 }
1395 
1396 bool PPCTargetLowering::hasSPE() const {
1397   return Subtarget.hasSPE();
1398 }
1399 
1400 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1401   return VT.isScalarInteger();
1402 }
1403 
1404 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1405   switch ((PPCISD::NodeType)Opcode) {
1406   case PPCISD::FIRST_NUMBER:    break;
1407   case PPCISD::FSEL:            return "PPCISD::FSEL";
1408   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1409   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1410   case PPCISD::FCFID:           return "PPCISD::FCFID";
1411   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1412   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1413   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1414   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1415   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1416   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1417   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1418   case PPCISD::FP_TO_UINT_IN_VSR:
1419                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1420   case PPCISD::FP_TO_SINT_IN_VSR:
1421                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1422   case PPCISD::FRE:             return "PPCISD::FRE";
1423   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1424   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1425   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1426   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1427   case PPCISD::VPERM:           return "PPCISD::VPERM";
1428   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1429   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1430   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1431   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1432   case PPCISD::CMPB:            return "PPCISD::CMPB";
1433   case PPCISD::Hi:              return "PPCISD::Hi";
1434   case PPCISD::Lo:              return "PPCISD::Lo";
1435   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1436   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1437   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1438   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1439   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1440   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1441   case PPCISD::SRL:             return "PPCISD::SRL";
1442   case PPCISD::SRA:             return "PPCISD::SRA";
1443   case PPCISD::SHL:             return "PPCISD::SHL";
1444   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1445   case PPCISD::CALL:            return "PPCISD::CALL";
1446   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1447   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1448   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1449   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1450   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1451   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1452   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1453   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1454   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1455   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1456   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1457   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1458   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1459   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1460   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1461   case PPCISD::ANDI_rec_1_EQ_BIT:
1462     return "PPCISD::ANDI_rec_1_EQ_BIT";
1463   case PPCISD::ANDI_rec_1_GT_BIT:
1464     return "PPCISD::ANDI_rec_1_GT_BIT";
1465   case PPCISD::VCMP:            return "PPCISD::VCMP";
1466   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1467   case PPCISD::LBRX:            return "PPCISD::LBRX";
1468   case PPCISD::STBRX:           return "PPCISD::STBRX";
1469   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1470   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1471   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1472   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1473   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1474   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1475   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1476   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1477   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1478   case PPCISD::ST_VSR_SCAL_INT:
1479                                 return "PPCISD::ST_VSR_SCAL_INT";
1480   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1481   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1482   case PPCISD::BDZ:             return "PPCISD::BDZ";
1483   case PPCISD::MFFS:            return "PPCISD::MFFS";
1484   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1485   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1486   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1487   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1488   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1489   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1490   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1491   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1492   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1493   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1494   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1495   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1496   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1497   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1498   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1499   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1500   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1501   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1502   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1503   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1504   case PPCISD::SC:              return "PPCISD::SC";
1505   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1506   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1507   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1508   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1509   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1510   case PPCISD::VABSD:           return "PPCISD::VABSD";
1511   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1512   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1513   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1514   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1515   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1516   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1517   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1518   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1519   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1520   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1521   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1522   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1523   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1524   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1525   }
1526   return nullptr;
1527 }
1528 
1529 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1530                                           EVT VT) const {
1531   if (!VT.isVector())
1532     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1533 
1534   if (Subtarget.hasQPX())
1535     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1536 
1537   return VT.changeVectorElementTypeToInteger();
1538 }
1539 
1540 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1541   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1542   return true;
1543 }
1544 
1545 //===----------------------------------------------------------------------===//
1546 // Node matching predicates, for use by the tblgen matching code.
1547 //===----------------------------------------------------------------------===//
1548 
1549 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1550 static bool isFloatingPointZero(SDValue Op) {
1551   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1552     return CFP->getValueAPF().isZero();
1553   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1554     // Maybe this has already been legalized into the constant pool?
1555     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1556       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1557         return CFP->getValueAPF().isZero();
1558   }
1559   return false;
1560 }
1561 
1562 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1563 /// true if Op is undef or if it matches the specified value.
1564 static bool isConstantOrUndef(int Op, int Val) {
1565   return Op < 0 || Op == Val;
1566 }
1567 
1568 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1569 /// VPKUHUM instruction.
1570 /// The ShuffleKind distinguishes between big-endian operations with
1571 /// two different inputs (0), either-endian operations with two identical
1572 /// inputs (1), and little-endian operations with two different inputs (2).
1573 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1574 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1575                                SelectionDAG &DAG) {
1576   bool IsLE = DAG.getDataLayout().isLittleEndian();
1577   if (ShuffleKind == 0) {
1578     if (IsLE)
1579       return false;
1580     for (unsigned i = 0; i != 16; ++i)
1581       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1582         return false;
1583   } else if (ShuffleKind == 2) {
1584     if (!IsLE)
1585       return false;
1586     for (unsigned i = 0; i != 16; ++i)
1587       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1588         return false;
1589   } else if (ShuffleKind == 1) {
1590     unsigned j = IsLE ? 0 : 1;
1591     for (unsigned i = 0; i != 8; ++i)
1592       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1593           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1594         return false;
1595   }
1596   return true;
1597 }
1598 
1599 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1600 /// VPKUWUM instruction.
1601 /// The ShuffleKind distinguishes between big-endian operations with
1602 /// two different inputs (0), either-endian operations with two identical
1603 /// inputs (1), and little-endian operations with two different inputs (2).
1604 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1605 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1606                                SelectionDAG &DAG) {
1607   bool IsLE = DAG.getDataLayout().isLittleEndian();
1608   if (ShuffleKind == 0) {
1609     if (IsLE)
1610       return false;
1611     for (unsigned i = 0; i != 16; i += 2)
1612       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1613           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1614         return false;
1615   } else if (ShuffleKind == 2) {
1616     if (!IsLE)
1617       return false;
1618     for (unsigned i = 0; i != 16; i += 2)
1619       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1620           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1621         return false;
1622   } else if (ShuffleKind == 1) {
1623     unsigned j = IsLE ? 0 : 2;
1624     for (unsigned i = 0; i != 8; i += 2)
1625       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1626           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1627           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1628           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1629         return false;
1630   }
1631   return true;
1632 }
1633 
1634 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1635 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1636 /// current subtarget.
1637 ///
1638 /// The ShuffleKind distinguishes between big-endian operations with
1639 /// two different inputs (0), either-endian operations with two identical
1640 /// inputs (1), and little-endian operations with two different inputs (2).
1641 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1642 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1643                                SelectionDAG &DAG) {
1644   const PPCSubtarget& Subtarget =
1645       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1646   if (!Subtarget.hasP8Vector())
1647     return false;
1648 
1649   bool IsLE = DAG.getDataLayout().isLittleEndian();
1650   if (ShuffleKind == 0) {
1651     if (IsLE)
1652       return false;
1653     for (unsigned i = 0; i != 16; i += 4)
1654       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1655           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1656           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1657           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1658         return false;
1659   } else if (ShuffleKind == 2) {
1660     if (!IsLE)
1661       return false;
1662     for (unsigned i = 0; i != 16; i += 4)
1663       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1664           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1665           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1666           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1667         return false;
1668   } else if (ShuffleKind == 1) {
1669     unsigned j = IsLE ? 0 : 4;
1670     for (unsigned i = 0; i != 8; i += 4)
1671       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1672           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1673           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1674           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1675           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1676           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1677           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1678           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1679         return false;
1680   }
1681   return true;
1682 }
1683 
1684 /// isVMerge - Common function, used to match vmrg* shuffles.
1685 ///
1686 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1687                      unsigned LHSStart, unsigned RHSStart) {
1688   if (N->getValueType(0) != MVT::v16i8)
1689     return false;
1690   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1691          "Unsupported merge size!");
1692 
1693   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1694     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1695       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1696                              LHSStart+j+i*UnitSize) ||
1697           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1698                              RHSStart+j+i*UnitSize))
1699         return false;
1700     }
1701   return true;
1702 }
1703 
1704 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1705 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1706 /// The ShuffleKind distinguishes between big-endian merges with two
1707 /// different inputs (0), either-endian merges with two identical inputs (1),
1708 /// and little-endian merges with two different inputs (2).  For the latter,
1709 /// the input operands are swapped (see PPCInstrAltivec.td).
1710 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1711                              unsigned ShuffleKind, SelectionDAG &DAG) {
1712   if (DAG.getDataLayout().isLittleEndian()) {
1713     if (ShuffleKind == 1) // unary
1714       return isVMerge(N, UnitSize, 0, 0);
1715     else if (ShuffleKind == 2) // swapped
1716       return isVMerge(N, UnitSize, 0, 16);
1717     else
1718       return false;
1719   } else {
1720     if (ShuffleKind == 1) // unary
1721       return isVMerge(N, UnitSize, 8, 8);
1722     else if (ShuffleKind == 0) // normal
1723       return isVMerge(N, UnitSize, 8, 24);
1724     else
1725       return false;
1726   }
1727 }
1728 
1729 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1730 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1731 /// The ShuffleKind distinguishes between big-endian merges with two
1732 /// different inputs (0), either-endian merges with two identical inputs (1),
1733 /// and little-endian merges with two different inputs (2).  For the latter,
1734 /// the input operands are swapped (see PPCInstrAltivec.td).
1735 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1736                              unsigned ShuffleKind, SelectionDAG &DAG) {
1737   if (DAG.getDataLayout().isLittleEndian()) {
1738     if (ShuffleKind == 1) // unary
1739       return isVMerge(N, UnitSize, 8, 8);
1740     else if (ShuffleKind == 2) // swapped
1741       return isVMerge(N, UnitSize, 8, 24);
1742     else
1743       return false;
1744   } else {
1745     if (ShuffleKind == 1) // unary
1746       return isVMerge(N, UnitSize, 0, 0);
1747     else if (ShuffleKind == 0) // normal
1748       return isVMerge(N, UnitSize, 0, 16);
1749     else
1750       return false;
1751   }
1752 }
1753 
1754 /**
1755  * Common function used to match vmrgew and vmrgow shuffles
1756  *
1757  * The indexOffset determines whether to look for even or odd words in
1758  * the shuffle mask. This is based on the of the endianness of the target
1759  * machine.
1760  *   - Little Endian:
1761  *     - Use offset of 0 to check for odd elements
1762  *     - Use offset of 4 to check for even elements
1763  *   - Big Endian:
1764  *     - Use offset of 0 to check for even elements
1765  *     - Use offset of 4 to check for odd elements
1766  * A detailed description of the vector element ordering for little endian and
1767  * big endian can be found at
1768  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1769  * Targeting your applications - what little endian and big endian IBM XL C/C++
1770  * compiler differences mean to you
1771  *
1772  * The mask to the shuffle vector instruction specifies the indices of the
1773  * elements from the two input vectors to place in the result. The elements are
1774  * numbered in array-access order, starting with the first vector. These vectors
1775  * are always of type v16i8, thus each vector will contain 16 elements of size
1776  * 8. More info on the shuffle vector can be found in the
1777  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1778  * Language Reference.
1779  *
1780  * The RHSStartValue indicates whether the same input vectors are used (unary)
1781  * or two different input vectors are used, based on the following:
1782  *   - If the instruction uses the same vector for both inputs, the range of the
1783  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1784  *     be 0.
1785  *   - If the instruction has two different vectors then the range of the
1786  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1787  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1788  *     to 31 specify elements in the second vector).
1789  *
1790  * \param[in] N The shuffle vector SD Node to analyze
1791  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1792  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1793  * vector to the shuffle_vector instruction
1794  * \return true iff this shuffle vector represents an even or odd word merge
1795  */
1796 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1797                      unsigned RHSStartValue) {
1798   if (N->getValueType(0) != MVT::v16i8)
1799     return false;
1800 
1801   for (unsigned i = 0; i < 2; ++i)
1802     for (unsigned j = 0; j < 4; ++j)
1803       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1804                              i*RHSStartValue+j+IndexOffset) ||
1805           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1806                              i*RHSStartValue+j+IndexOffset+8))
1807         return false;
1808   return true;
1809 }
1810 
1811 /**
1812  * Determine if the specified shuffle mask is suitable for the vmrgew or
1813  * vmrgow instructions.
1814  *
1815  * \param[in] N The shuffle vector SD Node to analyze
1816  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1817  * \param[in] ShuffleKind Identify the type of merge:
1818  *   - 0 = big-endian merge with two different inputs;
1819  *   - 1 = either-endian merge with two identical inputs;
1820  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1821  *     little-endian merges).
1822  * \param[in] DAG The current SelectionDAG
1823  * \return true iff this shuffle mask
1824  */
1825 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1826                               unsigned ShuffleKind, SelectionDAG &DAG) {
1827   if (DAG.getDataLayout().isLittleEndian()) {
1828     unsigned indexOffset = CheckEven ? 4 : 0;
1829     if (ShuffleKind == 1) // Unary
1830       return isVMerge(N, indexOffset, 0);
1831     else if (ShuffleKind == 2) // swapped
1832       return isVMerge(N, indexOffset, 16);
1833     else
1834       return false;
1835   }
1836   else {
1837     unsigned indexOffset = CheckEven ? 0 : 4;
1838     if (ShuffleKind == 1) // Unary
1839       return isVMerge(N, indexOffset, 0);
1840     else if (ShuffleKind == 0) // Normal
1841       return isVMerge(N, indexOffset, 16);
1842     else
1843       return false;
1844   }
1845   return false;
1846 }
1847 
1848 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1849 /// amount, otherwise return -1.
1850 /// The ShuffleKind distinguishes between big-endian operations with two
1851 /// different inputs (0), either-endian operations with two identical inputs
1852 /// (1), and little-endian operations with two different inputs (2).  For the
1853 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1854 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1855                              SelectionDAG &DAG) {
1856   if (N->getValueType(0) != MVT::v16i8)
1857     return -1;
1858 
1859   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1860 
1861   // Find the first non-undef value in the shuffle mask.
1862   unsigned i;
1863   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1864     /*search*/;
1865 
1866   if (i == 16) return -1;  // all undef.
1867 
1868   // Otherwise, check to see if the rest of the elements are consecutively
1869   // numbered from this value.
1870   unsigned ShiftAmt = SVOp->getMaskElt(i);
1871   if (ShiftAmt < i) return -1;
1872 
1873   ShiftAmt -= i;
1874   bool isLE = DAG.getDataLayout().isLittleEndian();
1875 
1876   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1877     // Check the rest of the elements to see if they are consecutive.
1878     for (++i; i != 16; ++i)
1879       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1880         return -1;
1881   } else if (ShuffleKind == 1) {
1882     // Check the rest of the elements to see if they are consecutive.
1883     for (++i; i != 16; ++i)
1884       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1885         return -1;
1886   } else
1887     return -1;
1888 
1889   if (isLE)
1890     ShiftAmt = 16 - ShiftAmt;
1891 
1892   return ShiftAmt;
1893 }
1894 
1895 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1896 /// specifies a splat of a single element that is suitable for input to
1897 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1898 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1899   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1900          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1901 
1902   // The consecutive indices need to specify an element, not part of two
1903   // different elements.  So abandon ship early if this isn't the case.
1904   if (N->getMaskElt(0) % EltSize != 0)
1905     return false;
1906 
1907   // This is a splat operation if each element of the permute is the same, and
1908   // if the value doesn't reference the second vector.
1909   unsigned ElementBase = N->getMaskElt(0);
1910 
1911   // FIXME: Handle UNDEF elements too!
1912   if (ElementBase >= 16)
1913     return false;
1914 
1915   // Check that the indices are consecutive, in the case of a multi-byte element
1916   // splatted with a v16i8 mask.
1917   for (unsigned i = 1; i != EltSize; ++i)
1918     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1919       return false;
1920 
1921   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1922     if (N->getMaskElt(i) < 0) continue;
1923     for (unsigned j = 0; j != EltSize; ++j)
1924       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1925         return false;
1926   }
1927   return true;
1928 }
1929 
1930 /// Check that the mask is shuffling N byte elements. Within each N byte
1931 /// element of the mask, the indices could be either in increasing or
1932 /// decreasing order as long as they are consecutive.
1933 /// \param[in] N the shuffle vector SD Node to analyze
1934 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1935 /// Word/DoubleWord/QuadWord).
1936 /// \param[in] StepLen the delta indices number among the N byte element, if
1937 /// the mask is in increasing/decreasing order then it is 1/-1.
1938 /// \return true iff the mask is shuffling N byte elements.
1939 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1940                                    int StepLen) {
1941   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1942          "Unexpected element width.");
1943   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1944 
1945   unsigned NumOfElem = 16 / Width;
1946   unsigned MaskVal[16]; //  Width is never greater than 16
1947   for (unsigned i = 0; i < NumOfElem; ++i) {
1948     MaskVal[0] = N->getMaskElt(i * Width);
1949     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1950       return false;
1951     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1952       return false;
1953     }
1954 
1955     for (unsigned int j = 1; j < Width; ++j) {
1956       MaskVal[j] = N->getMaskElt(i * Width + j);
1957       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1958         return false;
1959       }
1960     }
1961   }
1962 
1963   return true;
1964 }
1965 
1966 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1967                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1968   if (!isNByteElemShuffleMask(N, 4, 1))
1969     return false;
1970 
1971   // Now we look at mask elements 0,4,8,12
1972   unsigned M0 = N->getMaskElt(0) / 4;
1973   unsigned M1 = N->getMaskElt(4) / 4;
1974   unsigned M2 = N->getMaskElt(8) / 4;
1975   unsigned M3 = N->getMaskElt(12) / 4;
1976   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1977   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1978 
1979   // Below, let H and L be arbitrary elements of the shuffle mask
1980   // where H is in the range [4,7] and L is in the range [0,3].
1981   // H, 1, 2, 3 or L, 5, 6, 7
1982   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1983       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1984     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1985     InsertAtByte = IsLE ? 12 : 0;
1986     Swap = M0 < 4;
1987     return true;
1988   }
1989   // 0, H, 2, 3 or 4, L, 6, 7
1990   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1991       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1992     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1993     InsertAtByte = IsLE ? 8 : 4;
1994     Swap = M1 < 4;
1995     return true;
1996   }
1997   // 0, 1, H, 3 or 4, 5, L, 7
1998   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1999       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2000     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2001     InsertAtByte = IsLE ? 4 : 8;
2002     Swap = M2 < 4;
2003     return true;
2004   }
2005   // 0, 1, 2, H or 4, 5, 6, L
2006   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2007       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2008     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2009     InsertAtByte = IsLE ? 0 : 12;
2010     Swap = M3 < 4;
2011     return true;
2012   }
2013 
2014   // If both vector operands for the shuffle are the same vector, the mask will
2015   // contain only elements from the first one and the second one will be undef.
2016   if (N->getOperand(1).isUndef()) {
2017     ShiftElts = 0;
2018     Swap = true;
2019     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2020     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2021       InsertAtByte = IsLE ? 12 : 0;
2022       return true;
2023     }
2024     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2025       InsertAtByte = IsLE ? 8 : 4;
2026       return true;
2027     }
2028     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2029       InsertAtByte = IsLE ? 4 : 8;
2030       return true;
2031     }
2032     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2033       InsertAtByte = IsLE ? 0 : 12;
2034       return true;
2035     }
2036   }
2037 
2038   return false;
2039 }
2040 
2041 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2042                                bool &Swap, bool IsLE) {
2043   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2044   // Ensure each byte index of the word is consecutive.
2045   if (!isNByteElemShuffleMask(N, 4, 1))
2046     return false;
2047 
2048   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2049   unsigned M0 = N->getMaskElt(0) / 4;
2050   unsigned M1 = N->getMaskElt(4) / 4;
2051   unsigned M2 = N->getMaskElt(8) / 4;
2052   unsigned M3 = N->getMaskElt(12) / 4;
2053 
2054   // If both vector operands for the shuffle are the same vector, the mask will
2055   // contain only elements from the first one and the second one will be undef.
2056   if (N->getOperand(1).isUndef()) {
2057     assert(M0 < 4 && "Indexing into an undef vector?");
2058     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2059       return false;
2060 
2061     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2062     Swap = false;
2063     return true;
2064   }
2065 
2066   // Ensure each word index of the ShuffleVector Mask is consecutive.
2067   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2068     return false;
2069 
2070   if (IsLE) {
2071     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2072       // Input vectors don't need to be swapped if the leading element
2073       // of the result is one of the 3 left elements of the second vector
2074       // (or if there is no shift to be done at all).
2075       Swap = false;
2076       ShiftElts = (8 - M0) % 8;
2077     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2078       // Input vectors need to be swapped if the leading element
2079       // of the result is one of the 3 left elements of the first vector
2080       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2081       Swap = true;
2082       ShiftElts = (4 - M0) % 4;
2083     }
2084 
2085     return true;
2086   } else {                                          // BE
2087     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2088       // Input vectors don't need to be swapped if the leading element
2089       // of the result is one of the 4 elements of the first vector.
2090       Swap = false;
2091       ShiftElts = M0;
2092     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2093       // Input vectors need to be swapped if the leading element
2094       // of the result is one of the 4 elements of the right vector.
2095       Swap = true;
2096       ShiftElts = M0 - 4;
2097     }
2098 
2099     return true;
2100   }
2101 }
2102 
2103 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2104   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2105 
2106   if (!isNByteElemShuffleMask(N, Width, -1))
2107     return false;
2108 
2109   for (int i = 0; i < 16; i += Width)
2110     if (N->getMaskElt(i) != i + Width - 1)
2111       return false;
2112 
2113   return true;
2114 }
2115 
2116 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2117   return isXXBRShuffleMaskHelper(N, 2);
2118 }
2119 
2120 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2121   return isXXBRShuffleMaskHelper(N, 4);
2122 }
2123 
2124 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2125   return isXXBRShuffleMaskHelper(N, 8);
2126 }
2127 
2128 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2129   return isXXBRShuffleMaskHelper(N, 16);
2130 }
2131 
2132 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2133 /// if the inputs to the instruction should be swapped and set \p DM to the
2134 /// value for the immediate.
2135 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2136 /// AND element 0 of the result comes from the first input (LE) or second input
2137 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2138 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2139 /// mask.
2140 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2141                                bool &Swap, bool IsLE) {
2142   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2143 
2144   // Ensure each byte index of the double word is consecutive.
2145   if (!isNByteElemShuffleMask(N, 8, 1))
2146     return false;
2147 
2148   unsigned M0 = N->getMaskElt(0) / 8;
2149   unsigned M1 = N->getMaskElt(8) / 8;
2150   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2151 
2152   // If both vector operands for the shuffle are the same vector, the mask will
2153   // contain only elements from the first one and the second one will be undef.
2154   if (N->getOperand(1).isUndef()) {
2155     if ((M0 | M1) < 2) {
2156       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2157       Swap = false;
2158       return true;
2159     } else
2160       return false;
2161   }
2162 
2163   if (IsLE) {
2164     if (M0 > 1 && M1 < 2) {
2165       Swap = false;
2166     } else if (M0 < 2 && M1 > 1) {
2167       M0 = (M0 + 2) % 4;
2168       M1 = (M1 + 2) % 4;
2169       Swap = true;
2170     } else
2171       return false;
2172 
2173     // Note: if control flow comes here that means Swap is already set above
2174     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2175     return true;
2176   } else { // BE
2177     if (M0 < 2 && M1 > 1) {
2178       Swap = false;
2179     } else if (M0 > 1 && M1 < 2) {
2180       M0 = (M0 + 2) % 4;
2181       M1 = (M1 + 2) % 4;
2182       Swap = true;
2183     } else
2184       return false;
2185 
2186     // Note: if control flow comes here that means Swap is already set above
2187     DM = (M0 << 1) + (M1 & 1);
2188     return true;
2189   }
2190 }
2191 
2192 
2193 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2194 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2195 /// elements are counted from the left of the vector register).
2196 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2197                                          SelectionDAG &DAG) {
2198   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2199   assert(isSplatShuffleMask(SVOp, EltSize));
2200   if (DAG.getDataLayout().isLittleEndian())
2201     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2202   else
2203     return SVOp->getMaskElt(0) / EltSize;
2204 }
2205 
2206 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2207 /// by using a vspltis[bhw] instruction of the specified element size, return
2208 /// the constant being splatted.  The ByteSize field indicates the number of
2209 /// bytes of each element [124] -> [bhw].
2210 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2211   SDValue OpVal(nullptr, 0);
2212 
2213   // If ByteSize of the splat is bigger than the element size of the
2214   // build_vector, then we have a case where we are checking for a splat where
2215   // multiple elements of the buildvector are folded together into a single
2216   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2217   unsigned EltSize = 16/N->getNumOperands();
2218   if (EltSize < ByteSize) {
2219     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2220     SDValue UniquedVals[4];
2221     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2222 
2223     // See if all of the elements in the buildvector agree across.
2224     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2225       if (N->getOperand(i).isUndef()) continue;
2226       // If the element isn't a constant, bail fully out.
2227       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2228 
2229       if (!UniquedVals[i&(Multiple-1)].getNode())
2230         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2231       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2232         return SDValue();  // no match.
2233     }
2234 
2235     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2236     // either constant or undef values that are identical for each chunk.  See
2237     // if these chunks can form into a larger vspltis*.
2238 
2239     // Check to see if all of the leading entries are either 0 or -1.  If
2240     // neither, then this won't fit into the immediate field.
2241     bool LeadingZero = true;
2242     bool LeadingOnes = true;
2243     for (unsigned i = 0; i != Multiple-1; ++i) {
2244       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2245 
2246       LeadingZero &= isNullConstant(UniquedVals[i]);
2247       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2248     }
2249     // Finally, check the least significant entry.
2250     if (LeadingZero) {
2251       if (!UniquedVals[Multiple-1].getNode())
2252         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2253       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2254       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2255         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2256     }
2257     if (LeadingOnes) {
2258       if (!UniquedVals[Multiple-1].getNode())
2259         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2260       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2261       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2262         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2263     }
2264 
2265     return SDValue();
2266   }
2267 
2268   // Check to see if this buildvec has a single non-undef value in its elements.
2269   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2270     if (N->getOperand(i).isUndef()) continue;
2271     if (!OpVal.getNode())
2272       OpVal = N->getOperand(i);
2273     else if (OpVal != N->getOperand(i))
2274       return SDValue();
2275   }
2276 
2277   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2278 
2279   unsigned ValSizeInBytes = EltSize;
2280   uint64_t Value = 0;
2281   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2282     Value = CN->getZExtValue();
2283   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2284     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2285     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2286   }
2287 
2288   // If the splat value is larger than the element value, then we can never do
2289   // this splat.  The only case that we could fit the replicated bits into our
2290   // immediate field for would be zero, and we prefer to use vxor for it.
2291   if (ValSizeInBytes < ByteSize) return SDValue();
2292 
2293   // If the element value is larger than the splat value, check if it consists
2294   // of a repeated bit pattern of size ByteSize.
2295   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2296     return SDValue();
2297 
2298   // Properly sign extend the value.
2299   int MaskVal = SignExtend32(Value, ByteSize * 8);
2300 
2301   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2302   if (MaskVal == 0) return SDValue();
2303 
2304   // Finally, if this value fits in a 5 bit sext field, return it
2305   if (SignExtend32<5>(MaskVal) == MaskVal)
2306     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2307   return SDValue();
2308 }
2309 
2310 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2311 /// amount, otherwise return -1.
2312 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2313   EVT VT = N->getValueType(0);
2314   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2315     return -1;
2316 
2317   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2318 
2319   // Find the first non-undef value in the shuffle mask.
2320   unsigned i;
2321   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2322     /*search*/;
2323 
2324   if (i == 4) return -1;  // all undef.
2325 
2326   // Otherwise, check to see if the rest of the elements are consecutively
2327   // numbered from this value.
2328   unsigned ShiftAmt = SVOp->getMaskElt(i);
2329   if (ShiftAmt < i) return -1;
2330   ShiftAmt -= i;
2331 
2332   // Check the rest of the elements to see if they are consecutive.
2333   for (++i; i != 4; ++i)
2334     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2335       return -1;
2336 
2337   return ShiftAmt;
2338 }
2339 
2340 //===----------------------------------------------------------------------===//
2341 //  Addressing Mode Selection
2342 //===----------------------------------------------------------------------===//
2343 
2344 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2345 /// or 64-bit immediate, and if the value can be accurately represented as a
2346 /// sign extension from a 16-bit value.  If so, this returns true and the
2347 /// immediate.
2348 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2349   if (!isa<ConstantSDNode>(N))
2350     return false;
2351 
2352   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2353   if (N->getValueType(0) == MVT::i32)
2354     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2355   else
2356     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2357 }
2358 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2359   return isIntS16Immediate(Op.getNode(), Imm);
2360 }
2361 
2362 
2363 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2364 /// be represented as an indexed [r+r] operation.
2365 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2366                                                SDValue &Index,
2367                                                SelectionDAG &DAG) const {
2368   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2369       UI != E; ++UI) {
2370     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2371       if (Memop->getMemoryVT() == MVT::f64) {
2372           Base = N.getOperand(0);
2373           Index = N.getOperand(1);
2374           return true;
2375       }
2376     }
2377   }
2378   return false;
2379 }
2380 
2381 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2382 /// can be represented as an indexed [r+r] operation.  Returns false if it
2383 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2384 /// non-zero and N can be represented by a base register plus a signed 16-bit
2385 /// displacement, make a more precise judgement by checking (displacement % \p
2386 /// EncodingAlignment).
2387 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2388                                             SDValue &Index, SelectionDAG &DAG,
2389                                             unsigned EncodingAlignment) const {
2390   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2391   // a [pc+imm].
2392   if (SelectAddressPCRel(N, Base))
2393     return false;
2394 
2395   int16_t imm = 0;
2396   if (N.getOpcode() == ISD::ADD) {
2397     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2398     // SPE load/store can only handle 8-bit offsets.
2399     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2400         return true;
2401     if (isIntS16Immediate(N.getOperand(1), imm) &&
2402         (!EncodingAlignment || !(imm % EncodingAlignment)))
2403       return false; // r+i
2404     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2405       return false;    // r+i
2406 
2407     Base = N.getOperand(0);
2408     Index = N.getOperand(1);
2409     return true;
2410   } else if (N.getOpcode() == ISD::OR) {
2411     if (isIntS16Immediate(N.getOperand(1), imm) &&
2412         (!EncodingAlignment || !(imm % EncodingAlignment)))
2413       return false; // r+i can fold it if we can.
2414 
2415     // If this is an or of disjoint bitfields, we can codegen this as an add
2416     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2417     // disjoint.
2418     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2419 
2420     if (LHSKnown.Zero.getBoolValue()) {
2421       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2422       // If all of the bits are known zero on the LHS or RHS, the add won't
2423       // carry.
2424       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2425         Base = N.getOperand(0);
2426         Index = N.getOperand(1);
2427         return true;
2428       }
2429     }
2430   }
2431 
2432   return false;
2433 }
2434 
2435 // If we happen to be doing an i64 load or store into a stack slot that has
2436 // less than a 4-byte alignment, then the frame-index elimination may need to
2437 // use an indexed load or store instruction (because the offset may not be a
2438 // multiple of 4). The extra register needed to hold the offset comes from the
2439 // register scavenger, and it is possible that the scavenger will need to use
2440 // an emergency spill slot. As a result, we need to make sure that a spill slot
2441 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2442 // stack slot.
2443 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2444   // FIXME: This does not handle the LWA case.
2445   if (VT != MVT::i64)
2446     return;
2447 
2448   // NOTE: We'll exclude negative FIs here, which come from argument
2449   // lowering, because there are no known test cases triggering this problem
2450   // using packed structures (or similar). We can remove this exclusion if
2451   // we find such a test case. The reason why this is so test-case driven is
2452   // because this entire 'fixup' is only to prevent crashes (from the
2453   // register scavenger) on not-really-valid inputs. For example, if we have:
2454   //   %a = alloca i1
2455   //   %b = bitcast i1* %a to i64*
2456   //   store i64* a, i64 b
2457   // then the store should really be marked as 'align 1', but is not. If it
2458   // were marked as 'align 1' then the indexed form would have been
2459   // instruction-selected initially, and the problem this 'fixup' is preventing
2460   // won't happen regardless.
2461   if (FrameIdx < 0)
2462     return;
2463 
2464   MachineFunction &MF = DAG.getMachineFunction();
2465   MachineFrameInfo &MFI = MF.getFrameInfo();
2466 
2467   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2468     return;
2469 
2470   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2471   FuncInfo->setHasNonRISpills();
2472 }
2473 
2474 /// Returns true if the address N can be represented by a base register plus
2475 /// a signed 16-bit displacement [r+imm], and if it is not better
2476 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2477 /// displacements that are multiples of that value.
2478 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2479                                             SDValue &Base,
2480                                             SelectionDAG &DAG,
2481                                             unsigned EncodingAlignment) const {
2482   // FIXME dl should come from parent load or store, not from address
2483   SDLoc dl(N);
2484 
2485   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2486   // a [pc+imm].
2487   if (SelectAddressPCRel(N, Base))
2488     return false;
2489 
2490   // If this can be more profitably realized as r+r, fail.
2491   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2492     return false;
2493 
2494   if (N.getOpcode() == ISD::ADD) {
2495     int16_t imm = 0;
2496     if (isIntS16Immediate(N.getOperand(1), imm) &&
2497         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2498       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2499       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2500         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2501         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2502       } else {
2503         Base = N.getOperand(0);
2504       }
2505       return true; // [r+i]
2506     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2507       // Match LOAD (ADD (X, Lo(G))).
2508       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2509              && "Cannot handle constant offsets yet!");
2510       Disp = N.getOperand(1).getOperand(0);  // The global address.
2511       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2512              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2513              Disp.getOpcode() == ISD::TargetConstantPool ||
2514              Disp.getOpcode() == ISD::TargetJumpTable);
2515       Base = N.getOperand(0);
2516       return true;  // [&g+r]
2517     }
2518   } else if (N.getOpcode() == ISD::OR) {
2519     int16_t imm = 0;
2520     if (isIntS16Immediate(N.getOperand(1), imm) &&
2521         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2522       // If this is an or of disjoint bitfields, we can codegen this as an add
2523       // (for better address arithmetic) if the LHS and RHS of the OR are
2524       // provably disjoint.
2525       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2526 
2527       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2528         // If all of the bits are known zero on the LHS or RHS, the add won't
2529         // carry.
2530         if (FrameIndexSDNode *FI =
2531               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2532           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2533           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2534         } else {
2535           Base = N.getOperand(0);
2536         }
2537         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2538         return true;
2539       }
2540     }
2541   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2542     // Loading from a constant address.
2543 
2544     // If this address fits entirely in a 16-bit sext immediate field, codegen
2545     // this as "d, 0"
2546     int16_t Imm;
2547     if (isIntS16Immediate(CN, Imm) &&
2548         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2549       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2550       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2551                              CN->getValueType(0));
2552       return true;
2553     }
2554 
2555     // Handle 32-bit sext immediates with LIS + addr mode.
2556     if ((CN->getValueType(0) == MVT::i32 ||
2557          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2558         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2559       int Addr = (int)CN->getZExtValue();
2560 
2561       // Otherwise, break this down into an LIS + disp.
2562       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2563 
2564       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2565                                    MVT::i32);
2566       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2567       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2568       return true;
2569     }
2570   }
2571 
2572   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2573   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2574     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2575     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2576   } else
2577     Base = N;
2578   return true;      // [r+0]
2579 }
2580 
2581 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2582 /// represented as an indexed [r+r] operation.
2583 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2584                                                 SDValue &Index,
2585                                                 SelectionDAG &DAG) const {
2586   // Check to see if we can easily represent this as an [r+r] address.  This
2587   // will fail if it thinks that the address is more profitably represented as
2588   // reg+imm, e.g. where imm = 0.
2589   if (SelectAddressRegReg(N, Base, Index, DAG))
2590     return true;
2591 
2592   // If the address is the result of an add, we will utilize the fact that the
2593   // address calculation includes an implicit add.  However, we can reduce
2594   // register pressure if we do not materialize a constant just for use as the
2595   // index register.  We only get rid of the add if it is not an add of a
2596   // value and a 16-bit signed constant and both have a single use.
2597   int16_t imm = 0;
2598   if (N.getOpcode() == ISD::ADD &&
2599       (!isIntS16Immediate(N.getOperand(1), imm) ||
2600        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2601     Base = N.getOperand(0);
2602     Index = N.getOperand(1);
2603     return true;
2604   }
2605 
2606   // Otherwise, do it the hard way, using R0 as the base register.
2607   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2608                          N.getValueType());
2609   Index = N;
2610   return true;
2611 }
2612 
2613 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2614   Ty *PCRelCand = dyn_cast<Ty>(N);
2615   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2616 }
2617 
2618 /// Returns true if this address is a PC Relative address.
2619 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2620 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2621 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2622   // This is a materialize PC Relative node. Always select this as PC Relative.
2623   Base = N;
2624   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2625     return true;
2626   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2627       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2628       isValidPCRelNode<JumpTableSDNode>(N) ||
2629       isValidPCRelNode<BlockAddressSDNode>(N))
2630     return true;
2631   return false;
2632 }
2633 
2634 /// Returns true if we should use a direct load into vector instruction
2635 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2636 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2637 
2638   // If there are any other uses other than scalar to vector, then we should
2639   // keep it as a scalar load -> direct move pattern to prevent multiple
2640   // loads.
2641   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2642   if (!LD)
2643     return false;
2644 
2645   EVT MemVT = LD->getMemoryVT();
2646   if (!MemVT.isSimple())
2647     return false;
2648   switch(MemVT.getSimpleVT().SimpleTy) {
2649   case MVT::i64:
2650     break;
2651   case MVT::i32:
2652     if (!ST.hasP8Vector())
2653       return false;
2654     break;
2655   case MVT::i16:
2656   case MVT::i8:
2657     if (!ST.hasP9Vector())
2658       return false;
2659     break;
2660   default:
2661     return false;
2662   }
2663 
2664   SDValue LoadedVal(N, 0);
2665   if (!LoadedVal.hasOneUse())
2666     return false;
2667 
2668   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2669        UI != UE; ++UI)
2670     if (UI.getUse().get().getResNo() == 0 &&
2671         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2672       return false;
2673 
2674   return true;
2675 }
2676 
2677 /// getPreIndexedAddressParts - returns true by value, base pointer and
2678 /// offset pointer and addressing mode by reference if the node's address
2679 /// can be legally represented as pre-indexed load / store address.
2680 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2681                                                   SDValue &Offset,
2682                                                   ISD::MemIndexedMode &AM,
2683                                                   SelectionDAG &DAG) const {
2684   if (DisablePPCPreinc) return false;
2685 
2686   bool isLoad = true;
2687   SDValue Ptr;
2688   EVT VT;
2689   unsigned Alignment;
2690   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2691     Ptr = LD->getBasePtr();
2692     VT = LD->getMemoryVT();
2693     Alignment = LD->getAlignment();
2694   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2695     Ptr = ST->getBasePtr();
2696     VT  = ST->getMemoryVT();
2697     Alignment = ST->getAlignment();
2698     isLoad = false;
2699   } else
2700     return false;
2701 
2702   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2703   // instructions because we can fold these into a more efficient instruction
2704   // instead, (such as LXSD).
2705   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2706     return false;
2707   }
2708 
2709   // PowerPC doesn't have preinc load/store instructions for vectors (except
2710   // for QPX, which does have preinc r+r forms).
2711   if (VT.isVector()) {
2712     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2713       return false;
2714     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2715       AM = ISD::PRE_INC;
2716       return true;
2717     }
2718   }
2719 
2720   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2721     // Common code will reject creating a pre-inc form if the base pointer
2722     // is a frame index, or if N is a store and the base pointer is either
2723     // the same as or a predecessor of the value being stored.  Check for
2724     // those situations here, and try with swapped Base/Offset instead.
2725     bool Swap = false;
2726 
2727     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2728       Swap = true;
2729     else if (!isLoad) {
2730       SDValue Val = cast<StoreSDNode>(N)->getValue();
2731       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2732         Swap = true;
2733     }
2734 
2735     if (Swap)
2736       std::swap(Base, Offset);
2737 
2738     AM = ISD::PRE_INC;
2739     return true;
2740   }
2741 
2742   // LDU/STU can only handle immediates that are a multiple of 4.
2743   if (VT != MVT::i64) {
2744     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2745       return false;
2746   } else {
2747     // LDU/STU need an address with at least 4-byte alignment.
2748     if (Alignment < 4)
2749       return false;
2750 
2751     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2752       return false;
2753   }
2754 
2755   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2756     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2757     // sext i32 to i64 when addr mode is r+i.
2758     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2759         LD->getExtensionType() == ISD::SEXTLOAD &&
2760         isa<ConstantSDNode>(Offset))
2761       return false;
2762   }
2763 
2764   AM = ISD::PRE_INC;
2765   return true;
2766 }
2767 
2768 //===----------------------------------------------------------------------===//
2769 //  LowerOperation implementation
2770 //===----------------------------------------------------------------------===//
2771 
2772 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2773 /// and LoOpFlags to the target MO flags.
2774 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2775                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2776                                const GlobalValue *GV = nullptr) {
2777   HiOpFlags = PPCII::MO_HA;
2778   LoOpFlags = PPCII::MO_LO;
2779 
2780   // Don't use the pic base if not in PIC relocation model.
2781   if (IsPIC) {
2782     HiOpFlags |= PPCII::MO_PIC_FLAG;
2783     LoOpFlags |= PPCII::MO_PIC_FLAG;
2784   }
2785 }
2786 
2787 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2788                              SelectionDAG &DAG) {
2789   SDLoc DL(HiPart);
2790   EVT PtrVT = HiPart.getValueType();
2791   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2792 
2793   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2794   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2795 
2796   // With PIC, the first instruction is actually "GR+hi(&G)".
2797   if (isPIC)
2798     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2799                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2800 
2801   // Generate non-pic code that has direct accesses to the constant pool.
2802   // The address of the global is just (hi(&g)+lo(&g)).
2803   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2804 }
2805 
2806 static void setUsesTOCBasePtr(MachineFunction &MF) {
2807   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2808   FuncInfo->setUsesTOCBasePtr();
2809 }
2810 
2811 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2812   setUsesTOCBasePtr(DAG.getMachineFunction());
2813 }
2814 
2815 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2816                                        SDValue GA) const {
2817   const bool Is64Bit = Subtarget.isPPC64();
2818   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2819   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2820                         : Subtarget.isAIXABI()
2821                               ? DAG.getRegister(PPC::R2, VT)
2822                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2823   SDValue Ops[] = { GA, Reg };
2824   return DAG.getMemIntrinsicNode(
2825       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2826       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2827       MachineMemOperand::MOLoad);
2828 }
2829 
2830 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2831                                              SelectionDAG &DAG) const {
2832   EVT PtrVT = Op.getValueType();
2833   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2834   const Constant *C = CP->getConstVal();
2835 
2836   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2837   // The actual address of the GlobalValue is stored in the TOC.
2838   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2839     if (Subtarget.isUsingPCRelativeCalls()) {
2840       SDLoc DL(CP);
2841       EVT Ty = getPointerTy(DAG.getDataLayout());
2842       SDValue ConstPool = DAG.getTargetConstantPool(
2843           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2844       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2845     }
2846     setUsesTOCBasePtr(DAG);
2847     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2848     return getTOCEntry(DAG, SDLoc(CP), GA);
2849   }
2850 
2851   unsigned MOHiFlag, MOLoFlag;
2852   bool IsPIC = isPositionIndependent();
2853   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2854 
2855   if (IsPIC && Subtarget.isSVR4ABI()) {
2856     SDValue GA =
2857         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2858     return getTOCEntry(DAG, SDLoc(CP), GA);
2859   }
2860 
2861   SDValue CPIHi =
2862       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2863   SDValue CPILo =
2864       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2865   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2866 }
2867 
2868 // For 64-bit PowerPC, prefer the more compact relative encodings.
2869 // This trades 32 bits per jump table entry for one or two instructions
2870 // on the jump site.
2871 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2872   if (isJumpTableRelative())
2873     return MachineJumpTableInfo::EK_LabelDifference32;
2874 
2875   return TargetLowering::getJumpTableEncoding();
2876 }
2877 
2878 bool PPCTargetLowering::isJumpTableRelative() const {
2879   if (UseAbsoluteJumpTables)
2880     return false;
2881   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2882     return true;
2883   return TargetLowering::isJumpTableRelative();
2884 }
2885 
2886 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2887                                                     SelectionDAG &DAG) const {
2888   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2889     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2890 
2891   switch (getTargetMachine().getCodeModel()) {
2892   case CodeModel::Small:
2893   case CodeModel::Medium:
2894     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2895   default:
2896     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2897                        getPointerTy(DAG.getDataLayout()));
2898   }
2899 }
2900 
2901 const MCExpr *
2902 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2903                                                 unsigned JTI,
2904                                                 MCContext &Ctx) const {
2905   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2906     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2907 
2908   switch (getTargetMachine().getCodeModel()) {
2909   case CodeModel::Small:
2910   case CodeModel::Medium:
2911     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2912   default:
2913     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2914   }
2915 }
2916 
2917 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2918   EVT PtrVT = Op.getValueType();
2919   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2920 
2921   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2922   if (Subtarget.isUsingPCRelativeCalls()) {
2923     SDLoc DL(JT);
2924     EVT Ty = getPointerTy(DAG.getDataLayout());
2925     SDValue GA =
2926         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2927     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2928     return MatAddr;
2929   }
2930 
2931   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2932   // The actual address of the GlobalValue is stored in the TOC.
2933   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2934     setUsesTOCBasePtr(DAG);
2935     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2936     return getTOCEntry(DAG, SDLoc(JT), GA);
2937   }
2938 
2939   unsigned MOHiFlag, MOLoFlag;
2940   bool IsPIC = isPositionIndependent();
2941   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2942 
2943   if (IsPIC && Subtarget.isSVR4ABI()) {
2944     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2945                                         PPCII::MO_PIC_FLAG);
2946     return getTOCEntry(DAG, SDLoc(GA), GA);
2947   }
2948 
2949   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2950   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2951   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2952 }
2953 
2954 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2955                                              SelectionDAG &DAG) const {
2956   EVT PtrVT = Op.getValueType();
2957   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2958   const BlockAddress *BA = BASDN->getBlockAddress();
2959 
2960   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2961   if (Subtarget.isUsingPCRelativeCalls()) {
2962     SDLoc DL(BASDN);
2963     EVT Ty = getPointerTy(DAG.getDataLayout());
2964     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2965                                            PPCII::MO_PCREL_FLAG);
2966     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2967     return MatAddr;
2968   }
2969 
2970   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2971   // The actual BlockAddress is stored in the TOC.
2972   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2973     setUsesTOCBasePtr(DAG);
2974     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2975     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2976   }
2977 
2978   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2979   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2980     return getTOCEntry(
2981         DAG, SDLoc(BASDN),
2982         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2983 
2984   unsigned MOHiFlag, MOLoFlag;
2985   bool IsPIC = isPositionIndependent();
2986   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2987   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2988   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2989   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2990 }
2991 
2992 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2993                                               SelectionDAG &DAG) const {
2994   // FIXME: TLS addresses currently use medium model code sequences,
2995   // which is the most useful form.  Eventually support for small and
2996   // large models could be added if users need it, at the cost of
2997   // additional complexity.
2998   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2999   if (DAG.getTarget().useEmulatedTLS())
3000     return LowerToTLSEmulatedModel(GA, DAG);
3001 
3002   SDLoc dl(GA);
3003   const GlobalValue *GV = GA->getGlobal();
3004   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3005   bool is64bit = Subtarget.isPPC64();
3006   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3007   PICLevel::Level picLevel = M->getPICLevel();
3008 
3009   const TargetMachine &TM = getTargetMachine();
3010   TLSModel::Model Model = TM.getTLSModel(GV);
3011 
3012   if (Model == TLSModel::LocalExec) {
3013     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3014                                                PPCII::MO_TPREL_HA);
3015     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3016                                                PPCII::MO_TPREL_LO);
3017     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3018                              : DAG.getRegister(PPC::R2, MVT::i32);
3019 
3020     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3021     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3022   }
3023 
3024   if (Model == TLSModel::InitialExec) {
3025     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3026     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3027                                                 PPCII::MO_TLS);
3028     SDValue GOTPtr;
3029     if (is64bit) {
3030       setUsesTOCBasePtr(DAG);
3031       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3032       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
3033                            PtrVT, GOTReg, TGA);
3034     } else {
3035       if (!TM.isPositionIndependent())
3036         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3037       else if (picLevel == PICLevel::SmallPIC)
3038         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3039       else
3040         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3041     }
3042     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3043                                    PtrVT, TGA, GOTPtr);
3044     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3045   }
3046 
3047   if (Model == TLSModel::GeneralDynamic) {
3048     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3049     SDValue GOTPtr;
3050     if (is64bit) {
3051       setUsesTOCBasePtr(DAG);
3052       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3053       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3054                                    GOTReg, TGA);
3055     } else {
3056       if (picLevel == PICLevel::SmallPIC)
3057         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3058       else
3059         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3060     }
3061     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3062                        GOTPtr, TGA, TGA);
3063   }
3064 
3065   if (Model == TLSModel::LocalDynamic) {
3066     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3067     SDValue GOTPtr;
3068     if (is64bit) {
3069       setUsesTOCBasePtr(DAG);
3070       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3071       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3072                            GOTReg, TGA);
3073     } else {
3074       if (picLevel == PICLevel::SmallPIC)
3075         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3076       else
3077         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3078     }
3079     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3080                                   PtrVT, GOTPtr, TGA, TGA);
3081     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3082                                       PtrVT, TLSAddr, TGA);
3083     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3084   }
3085 
3086   llvm_unreachable("Unknown TLS model!");
3087 }
3088 
3089 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3090                                               SelectionDAG &DAG) const {
3091   EVT PtrVT = Op.getValueType();
3092   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3093   SDLoc DL(GSDN);
3094   const GlobalValue *GV = GSDN->getGlobal();
3095 
3096   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3097   // The actual address of the GlobalValue is stored in the TOC.
3098   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3099     if (Subtarget.isUsingPCRelativeCalls()) {
3100       EVT Ty = getPointerTy(DAG.getDataLayout());
3101       if (isAccessedAsGotIndirect(Op)) {
3102         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3103                                                 PPCII::MO_PCREL_FLAG |
3104                                                     PPCII::MO_GOT_FLAG);
3105         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3106         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3107                                    MachinePointerInfo());
3108         return Load;
3109       } else {
3110         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3111                                                 PPCII::MO_PCREL_FLAG);
3112         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3113       }
3114     }
3115     setUsesTOCBasePtr(DAG);
3116     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3117     return getTOCEntry(DAG, DL, GA);
3118   }
3119 
3120   unsigned MOHiFlag, MOLoFlag;
3121   bool IsPIC = isPositionIndependent();
3122   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3123 
3124   if (IsPIC && Subtarget.isSVR4ABI()) {
3125     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3126                                             GSDN->getOffset(),
3127                                             PPCII::MO_PIC_FLAG);
3128     return getTOCEntry(DAG, DL, GA);
3129   }
3130 
3131   SDValue GAHi =
3132     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3133   SDValue GALo =
3134     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3135 
3136   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3137 }
3138 
3139 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3140   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3141   SDLoc dl(Op);
3142 
3143   if (Op.getValueType() == MVT::v2i64) {
3144     // When the operands themselves are v2i64 values, we need to do something
3145     // special because VSX has no underlying comparison operations for these.
3146     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3147       // Equality can be handled by casting to the legal type for Altivec
3148       // comparisons, everything else needs to be expanded.
3149       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3150         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3151                  DAG.getSetCC(dl, MVT::v4i32,
3152                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3153                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3154                    CC));
3155       }
3156 
3157       return SDValue();
3158     }
3159 
3160     // We handle most of these in the usual way.
3161     return Op;
3162   }
3163 
3164   // If we're comparing for equality to zero, expose the fact that this is
3165   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3166   // fold the new nodes.
3167   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3168     return V;
3169 
3170   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3171     // Leave comparisons against 0 and -1 alone for now, since they're usually
3172     // optimized.  FIXME: revisit this when we can custom lower all setcc
3173     // optimizations.
3174     if (C->isAllOnesValue() || C->isNullValue())
3175       return SDValue();
3176   }
3177 
3178   // If we have an integer seteq/setne, turn it into a compare against zero
3179   // by xor'ing the rhs with the lhs, which is faster than setting a
3180   // condition register, reading it back out, and masking the correct bit.  The
3181   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3182   // the result to other bit-twiddling opportunities.
3183   EVT LHSVT = Op.getOperand(0).getValueType();
3184   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3185     EVT VT = Op.getValueType();
3186     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3187                                 Op.getOperand(1));
3188     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3189   }
3190   return SDValue();
3191 }
3192 
3193 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3194   SDNode *Node = Op.getNode();
3195   EVT VT = Node->getValueType(0);
3196   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3197   SDValue InChain = Node->getOperand(0);
3198   SDValue VAListPtr = Node->getOperand(1);
3199   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3200   SDLoc dl(Node);
3201 
3202   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3203 
3204   // gpr_index
3205   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3206                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3207   InChain = GprIndex.getValue(1);
3208 
3209   if (VT == MVT::i64) {
3210     // Check if GprIndex is even
3211     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3212                                  DAG.getConstant(1, dl, MVT::i32));
3213     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3214                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3215     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3216                                           DAG.getConstant(1, dl, MVT::i32));
3217     // Align GprIndex to be even if it isn't
3218     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3219                            GprIndex);
3220   }
3221 
3222   // fpr index is 1 byte after gpr
3223   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3224                                DAG.getConstant(1, dl, MVT::i32));
3225 
3226   // fpr
3227   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3228                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3229   InChain = FprIndex.getValue(1);
3230 
3231   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3232                                        DAG.getConstant(8, dl, MVT::i32));
3233 
3234   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3235                                         DAG.getConstant(4, dl, MVT::i32));
3236 
3237   // areas
3238   SDValue OverflowArea =
3239       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3240   InChain = OverflowArea.getValue(1);
3241 
3242   SDValue RegSaveArea =
3243       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3244   InChain = RegSaveArea.getValue(1);
3245 
3246   // select overflow_area if index > 8
3247   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3248                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3249 
3250   // adjustment constant gpr_index * 4/8
3251   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3252                                     VT.isInteger() ? GprIndex : FprIndex,
3253                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3254                                                     MVT::i32));
3255 
3256   // OurReg = RegSaveArea + RegConstant
3257   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3258                                RegConstant);
3259 
3260   // Floating types are 32 bytes into RegSaveArea
3261   if (VT.isFloatingPoint())
3262     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3263                          DAG.getConstant(32, dl, MVT::i32));
3264 
3265   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3266   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3267                                    VT.isInteger() ? GprIndex : FprIndex,
3268                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3269                                                    MVT::i32));
3270 
3271   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3272                               VT.isInteger() ? VAListPtr : FprPtr,
3273                               MachinePointerInfo(SV), MVT::i8);
3274 
3275   // determine if we should load from reg_save_area or overflow_area
3276   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3277 
3278   // increase overflow_area by 4/8 if gpr/fpr > 8
3279   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3280                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3281                                           dl, MVT::i32));
3282 
3283   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3284                              OverflowAreaPlusN);
3285 
3286   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3287                               MachinePointerInfo(), MVT::i32);
3288 
3289   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3290 }
3291 
3292 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3293   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3294 
3295   // We have to copy the entire va_list struct:
3296   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3297   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3298                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3299                        false, true, false, MachinePointerInfo(),
3300                        MachinePointerInfo());
3301 }
3302 
3303 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3304                                                   SelectionDAG &DAG) const {
3305   if (Subtarget.isAIXABI())
3306     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3307 
3308   return Op.getOperand(0);
3309 }
3310 
3311 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3312                                                 SelectionDAG &DAG) const {
3313   if (Subtarget.isAIXABI())
3314     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3315 
3316   SDValue Chain = Op.getOperand(0);
3317   SDValue Trmp = Op.getOperand(1); // trampoline
3318   SDValue FPtr = Op.getOperand(2); // nested function
3319   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3320   SDLoc dl(Op);
3321 
3322   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3323   bool isPPC64 = (PtrVT == MVT::i64);
3324   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3325 
3326   TargetLowering::ArgListTy Args;
3327   TargetLowering::ArgListEntry Entry;
3328 
3329   Entry.Ty = IntPtrTy;
3330   Entry.Node = Trmp; Args.push_back(Entry);
3331 
3332   // TrampSize == (isPPC64 ? 48 : 40);
3333   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3334                                isPPC64 ? MVT::i64 : MVT::i32);
3335   Args.push_back(Entry);
3336 
3337   Entry.Node = FPtr; Args.push_back(Entry);
3338   Entry.Node = Nest; Args.push_back(Entry);
3339 
3340   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3341   TargetLowering::CallLoweringInfo CLI(DAG);
3342   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3343       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3344       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3345 
3346   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3347   return CallResult.second;
3348 }
3349 
3350 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3351   MachineFunction &MF = DAG.getMachineFunction();
3352   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3353   EVT PtrVT = getPointerTy(MF.getDataLayout());
3354 
3355   SDLoc dl(Op);
3356 
3357   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3358     // vastart just stores the address of the VarArgsFrameIndex slot into the
3359     // memory location argument.
3360     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3361     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3362     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3363                         MachinePointerInfo(SV));
3364   }
3365 
3366   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3367   // We suppose the given va_list is already allocated.
3368   //
3369   // typedef struct {
3370   //  char gpr;     /* index into the array of 8 GPRs
3371   //                 * stored in the register save area
3372   //                 * gpr=0 corresponds to r3,
3373   //                 * gpr=1 to r4, etc.
3374   //                 */
3375   //  char fpr;     /* index into the array of 8 FPRs
3376   //                 * stored in the register save area
3377   //                 * fpr=0 corresponds to f1,
3378   //                 * fpr=1 to f2, etc.
3379   //                 */
3380   //  char *overflow_arg_area;
3381   //                /* location on stack that holds
3382   //                 * the next overflow argument
3383   //                 */
3384   //  char *reg_save_area;
3385   //               /* where r3:r10 and f1:f8 (if saved)
3386   //                * are stored
3387   //                */
3388   // } va_list[1];
3389 
3390   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3391   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3392   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3393                                             PtrVT);
3394   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3395                                  PtrVT);
3396 
3397   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3398   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3399 
3400   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3401   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3402 
3403   uint64_t FPROffset = 1;
3404   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3405 
3406   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3407 
3408   // Store first byte : number of int regs
3409   SDValue firstStore =
3410       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3411                         MachinePointerInfo(SV), MVT::i8);
3412   uint64_t nextOffset = FPROffset;
3413   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3414                                   ConstFPROffset);
3415 
3416   // Store second byte : number of float regs
3417   SDValue secondStore =
3418       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3419                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3420   nextOffset += StackOffset;
3421   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3422 
3423   // Store second word : arguments given on stack
3424   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3425                                     MachinePointerInfo(SV, nextOffset));
3426   nextOffset += FrameOffset;
3427   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3428 
3429   // Store third word : arguments given in registers
3430   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3431                       MachinePointerInfo(SV, nextOffset));
3432 }
3433 
3434 /// FPR - The set of FP registers that should be allocated for arguments
3435 /// on Darwin and AIX.
3436 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3437                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3438                                 PPC::F11, PPC::F12, PPC::F13};
3439 
3440 /// QFPR - The set of QPX registers that should be allocated for arguments.
3441 static const MCPhysReg QFPR[] = {
3442     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3443     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3444 
3445 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3446 /// the stack.
3447 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3448                                        unsigned PtrByteSize) {
3449   unsigned ArgSize = ArgVT.getStoreSize();
3450   if (Flags.isByVal())
3451     ArgSize = Flags.getByValSize();
3452 
3453   // Round up to multiples of the pointer size, except for array members,
3454   // which are always packed.
3455   if (!Flags.isInConsecutiveRegs())
3456     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3457 
3458   return ArgSize;
3459 }
3460 
3461 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3462 /// on the stack.
3463 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3464                                          ISD::ArgFlagsTy Flags,
3465                                          unsigned PtrByteSize) {
3466   Align Alignment(PtrByteSize);
3467 
3468   // Altivec parameters are padded to a 16 byte boundary.
3469   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3470       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3471       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3472       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3473     Alignment = Align(16);
3474   // QPX vector types stored in double-precision are padded to a 32 byte
3475   // boundary.
3476   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3477     Alignment = Align(32);
3478 
3479   // ByVal parameters are aligned as requested.
3480   if (Flags.isByVal()) {
3481     auto BVAlign = Flags.getNonZeroByValAlign();
3482     if (BVAlign > PtrByteSize) {
3483       if (BVAlign.value() % PtrByteSize != 0)
3484         llvm_unreachable(
3485             "ByVal alignment is not a multiple of the pointer size");
3486 
3487       Alignment = BVAlign;
3488     }
3489   }
3490 
3491   // Array members are always packed to their original alignment.
3492   if (Flags.isInConsecutiveRegs()) {
3493     // If the array member was split into multiple registers, the first
3494     // needs to be aligned to the size of the full type.  (Except for
3495     // ppcf128, which is only aligned as its f64 components.)
3496     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3497       Alignment = Align(OrigVT.getStoreSize());
3498     else
3499       Alignment = Align(ArgVT.getStoreSize());
3500   }
3501 
3502   return Alignment;
3503 }
3504 
3505 /// CalculateStackSlotUsed - Return whether this argument will use its
3506 /// stack slot (instead of being passed in registers).  ArgOffset,
3507 /// AvailableFPRs, and AvailableVRs must hold the current argument
3508 /// position, and will be updated to account for this argument.
3509 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3510                                    ISD::ArgFlagsTy Flags,
3511                                    unsigned PtrByteSize,
3512                                    unsigned LinkageSize,
3513                                    unsigned ParamAreaSize,
3514                                    unsigned &ArgOffset,
3515                                    unsigned &AvailableFPRs,
3516                                    unsigned &AvailableVRs, bool HasQPX) {
3517   bool UseMemory = false;
3518 
3519   // Respect alignment of argument on the stack.
3520   Align Alignment =
3521       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3522   ArgOffset = alignTo(ArgOffset, Alignment);
3523   // If there's no space left in the argument save area, we must
3524   // use memory (this check also catches zero-sized arguments).
3525   if (ArgOffset >= LinkageSize + ParamAreaSize)
3526     UseMemory = true;
3527 
3528   // Allocate argument on the stack.
3529   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3530   if (Flags.isInConsecutiveRegsLast())
3531     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3532   // If we overran the argument save area, we must use memory
3533   // (this check catches arguments passed partially in memory)
3534   if (ArgOffset > LinkageSize + ParamAreaSize)
3535     UseMemory = true;
3536 
3537   // However, if the argument is actually passed in an FPR or a VR,
3538   // we don't use memory after all.
3539   if (!Flags.isByVal()) {
3540     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3541         // QPX registers overlap with the scalar FP registers.
3542         (HasQPX && (ArgVT == MVT::v4f32 ||
3543                     ArgVT == MVT::v4f64 ||
3544                     ArgVT == MVT::v4i1)))
3545       if (AvailableFPRs > 0) {
3546         --AvailableFPRs;
3547         return false;
3548       }
3549     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3550         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3551         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3552         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3553       if (AvailableVRs > 0) {
3554         --AvailableVRs;
3555         return false;
3556       }
3557   }
3558 
3559   return UseMemory;
3560 }
3561 
3562 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3563 /// ensure minimum alignment required for target.
3564 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3565                                      unsigned NumBytes) {
3566   return alignTo(NumBytes, Lowering->getStackAlign());
3567 }
3568 
3569 SDValue PPCTargetLowering::LowerFormalArguments(
3570     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3571     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3572     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3573   if (Subtarget.isAIXABI())
3574     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3575                                     InVals);
3576   if (Subtarget.is64BitELFABI())
3577     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3578                                        InVals);
3579   if (Subtarget.is32BitELFABI())
3580     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3581                                        InVals);
3582 
3583   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3584                                      InVals);
3585 }
3586 
3587 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3588     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3589     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3590     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3591 
3592   // 32-bit SVR4 ABI Stack Frame Layout:
3593   //              +-----------------------------------+
3594   //        +-->  |            Back chain             |
3595   //        |     +-----------------------------------+
3596   //        |     | Floating-point register save area |
3597   //        |     +-----------------------------------+
3598   //        |     |    General register save area     |
3599   //        |     +-----------------------------------+
3600   //        |     |          CR save word             |
3601   //        |     +-----------------------------------+
3602   //        |     |         VRSAVE save word          |
3603   //        |     +-----------------------------------+
3604   //        |     |         Alignment padding         |
3605   //        |     +-----------------------------------+
3606   //        |     |     Vector register save area     |
3607   //        |     +-----------------------------------+
3608   //        |     |       Local variable space        |
3609   //        |     +-----------------------------------+
3610   //        |     |        Parameter list area        |
3611   //        |     +-----------------------------------+
3612   //        |     |           LR save word            |
3613   //        |     +-----------------------------------+
3614   // SP-->  +---  |            Back chain             |
3615   //              +-----------------------------------+
3616   //
3617   // Specifications:
3618   //   System V Application Binary Interface PowerPC Processor Supplement
3619   //   AltiVec Technology Programming Interface Manual
3620 
3621   MachineFunction &MF = DAG.getMachineFunction();
3622   MachineFrameInfo &MFI = MF.getFrameInfo();
3623   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3624 
3625   EVT PtrVT = getPointerTy(MF.getDataLayout());
3626   // Potential tail calls could cause overwriting of argument stack slots.
3627   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3628                        (CallConv == CallingConv::Fast));
3629   unsigned PtrByteSize = 4;
3630 
3631   // Assign locations to all of the incoming arguments.
3632   SmallVector<CCValAssign, 16> ArgLocs;
3633   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3634                  *DAG.getContext());
3635 
3636   // Reserve space for the linkage area on the stack.
3637   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3638   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3639   if (useSoftFloat())
3640     CCInfo.PreAnalyzeFormalArguments(Ins);
3641 
3642   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3643   CCInfo.clearWasPPCF128();
3644 
3645   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3646     CCValAssign &VA = ArgLocs[i];
3647 
3648     // Arguments stored in registers.
3649     if (VA.isRegLoc()) {
3650       const TargetRegisterClass *RC;
3651       EVT ValVT = VA.getValVT();
3652 
3653       switch (ValVT.getSimpleVT().SimpleTy) {
3654         default:
3655           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3656         case MVT::i1:
3657         case MVT::i32:
3658           RC = &PPC::GPRCRegClass;
3659           break;
3660         case MVT::f32:
3661           if (Subtarget.hasP8Vector())
3662             RC = &PPC::VSSRCRegClass;
3663           else if (Subtarget.hasSPE())
3664             RC = &PPC::GPRCRegClass;
3665           else
3666             RC = &PPC::F4RCRegClass;
3667           break;
3668         case MVT::f64:
3669           if (Subtarget.hasVSX())
3670             RC = &PPC::VSFRCRegClass;
3671           else if (Subtarget.hasSPE())
3672             // SPE passes doubles in GPR pairs.
3673             RC = &PPC::GPRCRegClass;
3674           else
3675             RC = &PPC::F8RCRegClass;
3676           break;
3677         case MVT::v16i8:
3678         case MVT::v8i16:
3679         case MVT::v4i32:
3680           RC = &PPC::VRRCRegClass;
3681           break;
3682         case MVT::v4f32:
3683           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3684           break;
3685         case MVT::v2f64:
3686         case MVT::v2i64:
3687           RC = &PPC::VRRCRegClass;
3688           break;
3689         case MVT::v4f64:
3690           RC = &PPC::QFRCRegClass;
3691           break;
3692         case MVT::v4i1:
3693           RC = &PPC::QBRCRegClass;
3694           break;
3695       }
3696 
3697       SDValue ArgValue;
3698       // Transform the arguments stored in physical registers into
3699       // virtual ones.
3700       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3701         assert(i + 1 < e && "No second half of double precision argument");
3702         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3703         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3704         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3705         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3706         if (!Subtarget.isLittleEndian())
3707           std::swap (ArgValueLo, ArgValueHi);
3708         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3709                                ArgValueHi);
3710       } else {
3711         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3712         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3713                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3714         if (ValVT == MVT::i1)
3715           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3716       }
3717 
3718       InVals.push_back(ArgValue);
3719     } else {
3720       // Argument stored in memory.
3721       assert(VA.isMemLoc());
3722 
3723       // Get the extended size of the argument type in stack
3724       unsigned ArgSize = VA.getLocVT().getStoreSize();
3725       // Get the actual size of the argument type
3726       unsigned ObjSize = VA.getValVT().getStoreSize();
3727       unsigned ArgOffset = VA.getLocMemOffset();
3728       // Stack objects in PPC32 are right justified.
3729       ArgOffset += ArgSize - ObjSize;
3730       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3731 
3732       // Create load nodes to retrieve arguments from the stack.
3733       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3734       InVals.push_back(
3735           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3736     }
3737   }
3738 
3739   // Assign locations to all of the incoming aggregate by value arguments.
3740   // Aggregates passed by value are stored in the local variable space of the
3741   // caller's stack frame, right above the parameter list area.
3742   SmallVector<CCValAssign, 16> ByValArgLocs;
3743   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3744                       ByValArgLocs, *DAG.getContext());
3745 
3746   // Reserve stack space for the allocations in CCInfo.
3747   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3748 
3749   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3750 
3751   // Area that is at least reserved in the caller of this function.
3752   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3753   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3754 
3755   // Set the size that is at least reserved in caller of this function.  Tail
3756   // call optimized function's reserved stack space needs to be aligned so that
3757   // taking the difference between two stack areas will result in an aligned
3758   // stack.
3759   MinReservedArea =
3760       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3761   FuncInfo->setMinReservedArea(MinReservedArea);
3762 
3763   SmallVector<SDValue, 8> MemOps;
3764 
3765   // If the function takes variable number of arguments, make a frame index for
3766   // the start of the first vararg value... for expansion of llvm.va_start.
3767   if (isVarArg) {
3768     static const MCPhysReg GPArgRegs[] = {
3769       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3770       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3771     };
3772     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3773 
3774     static const MCPhysReg FPArgRegs[] = {
3775       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3776       PPC::F8
3777     };
3778     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3779 
3780     if (useSoftFloat() || hasSPE())
3781        NumFPArgRegs = 0;
3782 
3783     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3784     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3785 
3786     // Make room for NumGPArgRegs and NumFPArgRegs.
3787     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3788                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3789 
3790     FuncInfo->setVarArgsStackOffset(
3791       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3792                             CCInfo.getNextStackOffset(), true));
3793 
3794     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3795     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3796 
3797     // The fixed integer arguments of a variadic function are stored to the
3798     // VarArgsFrameIndex on the stack so that they may be loaded by
3799     // dereferencing the result of va_next.
3800     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3801       // Get an existing live-in vreg, or add a new one.
3802       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3803       if (!VReg)
3804         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3805 
3806       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3807       SDValue Store =
3808           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3809       MemOps.push_back(Store);
3810       // Increment the address by four for the next argument to store
3811       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3812       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3813     }
3814 
3815     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3816     // is set.
3817     // The double arguments are stored to the VarArgsFrameIndex
3818     // on the stack.
3819     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3820       // Get an existing live-in vreg, or add a new one.
3821       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3822       if (!VReg)
3823         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3824 
3825       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3826       SDValue Store =
3827           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3828       MemOps.push_back(Store);
3829       // Increment the address by eight for the next argument to store
3830       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3831                                          PtrVT);
3832       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3833     }
3834   }
3835 
3836   if (!MemOps.empty())
3837     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3838 
3839   return Chain;
3840 }
3841 
3842 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3843 // value to MVT::i64 and then truncate to the correct register size.
3844 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3845                                              EVT ObjectVT, SelectionDAG &DAG,
3846                                              SDValue ArgVal,
3847                                              const SDLoc &dl) const {
3848   if (Flags.isSExt())
3849     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3850                          DAG.getValueType(ObjectVT));
3851   else if (Flags.isZExt())
3852     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3853                          DAG.getValueType(ObjectVT));
3854 
3855   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3856 }
3857 
3858 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3859     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3860     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3861     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3862   // TODO: add description of PPC stack frame format, or at least some docs.
3863   //
3864   bool isELFv2ABI = Subtarget.isELFv2ABI();
3865   bool isLittleEndian = Subtarget.isLittleEndian();
3866   MachineFunction &MF = DAG.getMachineFunction();
3867   MachineFrameInfo &MFI = MF.getFrameInfo();
3868   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3869 
3870   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3871          "fastcc not supported on varargs functions");
3872 
3873   EVT PtrVT = getPointerTy(MF.getDataLayout());
3874   // Potential tail calls could cause overwriting of argument stack slots.
3875   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3876                        (CallConv == CallingConv::Fast));
3877   unsigned PtrByteSize = 8;
3878   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3879 
3880   static const MCPhysReg GPR[] = {
3881     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3882     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3883   };
3884   static const MCPhysReg VR[] = {
3885     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3886     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3887   };
3888 
3889   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3890   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3891   const unsigned Num_VR_Regs  = array_lengthof(VR);
3892   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3893 
3894   // Do a first pass over the arguments to determine whether the ABI
3895   // guarantees that our caller has allocated the parameter save area
3896   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3897   // in the ELFv2 ABI, it is true if this is a vararg function or if
3898   // any parameter is located in a stack slot.
3899 
3900   bool HasParameterArea = !isELFv2ABI || isVarArg;
3901   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3902   unsigned NumBytes = LinkageSize;
3903   unsigned AvailableFPRs = Num_FPR_Regs;
3904   unsigned AvailableVRs = Num_VR_Regs;
3905   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3906     if (Ins[i].Flags.isNest())
3907       continue;
3908 
3909     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3910                                PtrByteSize, LinkageSize, ParamAreaSize,
3911                                NumBytes, AvailableFPRs, AvailableVRs,
3912                                Subtarget.hasQPX()))
3913       HasParameterArea = true;
3914   }
3915 
3916   // Add DAG nodes to load the arguments or copy them out of registers.  On
3917   // entry to a function on PPC, the arguments start after the linkage area,
3918   // although the first ones are often in registers.
3919 
3920   unsigned ArgOffset = LinkageSize;
3921   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3922   unsigned &QFPR_idx = FPR_idx;
3923   SmallVector<SDValue, 8> MemOps;
3924   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3925   unsigned CurArgIdx = 0;
3926   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3927     SDValue ArgVal;
3928     bool needsLoad = false;
3929     EVT ObjectVT = Ins[ArgNo].VT;
3930     EVT OrigVT = Ins[ArgNo].ArgVT;
3931     unsigned ObjSize = ObjectVT.getStoreSize();
3932     unsigned ArgSize = ObjSize;
3933     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3934     if (Ins[ArgNo].isOrigArg()) {
3935       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3936       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3937     }
3938     // We re-align the argument offset for each argument, except when using the
3939     // fast calling convention, when we need to make sure we do that only when
3940     // we'll actually use a stack slot.
3941     unsigned CurArgOffset;
3942     Align Alignment;
3943     auto ComputeArgOffset = [&]() {
3944       /* Respect alignment of argument on the stack.  */
3945       Alignment =
3946           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3947       ArgOffset = alignTo(ArgOffset, Alignment);
3948       CurArgOffset = ArgOffset;
3949     };
3950 
3951     if (CallConv != CallingConv::Fast) {
3952       ComputeArgOffset();
3953 
3954       /* Compute GPR index associated with argument offset.  */
3955       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3956       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3957     }
3958 
3959     // FIXME the codegen can be much improved in some cases.
3960     // We do not have to keep everything in memory.
3961     if (Flags.isByVal()) {
3962       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3963 
3964       if (CallConv == CallingConv::Fast)
3965         ComputeArgOffset();
3966 
3967       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3968       ObjSize = Flags.getByValSize();
3969       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3970       // Empty aggregate parameters do not take up registers.  Examples:
3971       //   struct { } a;
3972       //   union  { } b;
3973       //   int c[0];
3974       // etc.  However, we have to provide a place-holder in InVals, so
3975       // pretend we have an 8-byte item at the current address for that
3976       // purpose.
3977       if (!ObjSize) {
3978         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3979         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3980         InVals.push_back(FIN);
3981         continue;
3982       }
3983 
3984       // Create a stack object covering all stack doublewords occupied
3985       // by the argument.  If the argument is (fully or partially) on
3986       // the stack, or if the argument is fully in registers but the
3987       // caller has allocated the parameter save anyway, we can refer
3988       // directly to the caller's stack frame.  Otherwise, create a
3989       // local copy in our own frame.
3990       int FI;
3991       if (HasParameterArea ||
3992           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3993         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3994       else
3995         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3996       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3997 
3998       // Handle aggregates smaller than 8 bytes.
3999       if (ObjSize < PtrByteSize) {
4000         // The value of the object is its address, which differs from the
4001         // address of the enclosing doubleword on big-endian systems.
4002         SDValue Arg = FIN;
4003         if (!isLittleEndian) {
4004           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4005           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4006         }
4007         InVals.push_back(Arg);
4008 
4009         if (GPR_idx != Num_GPR_Regs) {
4010           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4011           FuncInfo->addLiveInAttr(VReg, Flags);
4012           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4013           SDValue Store;
4014 
4015           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4016             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4017                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4018             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4019                                       MachinePointerInfo(&*FuncArg), ObjType);
4020           } else {
4021             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4022             // store the whole register as-is to the parameter save area
4023             // slot.
4024             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4025                                  MachinePointerInfo(&*FuncArg));
4026           }
4027 
4028           MemOps.push_back(Store);
4029         }
4030         // Whether we copied from a register or not, advance the offset
4031         // into the parameter save area by a full doubleword.
4032         ArgOffset += PtrByteSize;
4033         continue;
4034       }
4035 
4036       // The value of the object is its address, which is the address of
4037       // its first stack doubleword.
4038       InVals.push_back(FIN);
4039 
4040       // Store whatever pieces of the object are in registers to memory.
4041       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4042         if (GPR_idx == Num_GPR_Regs)
4043           break;
4044 
4045         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4046         FuncInfo->addLiveInAttr(VReg, Flags);
4047         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4048         SDValue Addr = FIN;
4049         if (j) {
4050           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4051           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4052         }
4053         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4054                                      MachinePointerInfo(&*FuncArg, j));
4055         MemOps.push_back(Store);
4056         ++GPR_idx;
4057       }
4058       ArgOffset += ArgSize;
4059       continue;
4060     }
4061 
4062     switch (ObjectVT.getSimpleVT().SimpleTy) {
4063     default: llvm_unreachable("Unhandled argument type!");
4064     case MVT::i1:
4065     case MVT::i32:
4066     case MVT::i64:
4067       if (Flags.isNest()) {
4068         // The 'nest' parameter, if any, is passed in R11.
4069         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4070         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4071 
4072         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4073           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4074 
4075         break;
4076       }
4077 
4078       // These can be scalar arguments or elements of an integer array type
4079       // passed directly.  Clang may use those instead of "byval" aggregate
4080       // types to avoid forcing arguments to memory unnecessarily.
4081       if (GPR_idx != Num_GPR_Regs) {
4082         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4083         FuncInfo->addLiveInAttr(VReg, Flags);
4084         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4085 
4086         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4087           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4088           // value to MVT::i64 and then truncate to the correct register size.
4089           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4090       } else {
4091         if (CallConv == CallingConv::Fast)
4092           ComputeArgOffset();
4093 
4094         needsLoad = true;
4095         ArgSize = PtrByteSize;
4096       }
4097       if (CallConv != CallingConv::Fast || needsLoad)
4098         ArgOffset += 8;
4099       break;
4100 
4101     case MVT::f32:
4102     case MVT::f64:
4103       // These can be scalar arguments or elements of a float array type
4104       // passed directly.  The latter are used to implement ELFv2 homogenous
4105       // float aggregates.
4106       if (FPR_idx != Num_FPR_Regs) {
4107         unsigned VReg;
4108 
4109         if (ObjectVT == MVT::f32)
4110           VReg = MF.addLiveIn(FPR[FPR_idx],
4111                               Subtarget.hasP8Vector()
4112                                   ? &PPC::VSSRCRegClass
4113                                   : &PPC::F4RCRegClass);
4114         else
4115           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4116                                                 ? &PPC::VSFRCRegClass
4117                                                 : &PPC::F8RCRegClass);
4118 
4119         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4120         ++FPR_idx;
4121       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4122         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4123         // once we support fp <-> gpr moves.
4124 
4125         // This can only ever happen in the presence of f32 array types,
4126         // since otherwise we never run out of FPRs before running out
4127         // of GPRs.
4128         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4129         FuncInfo->addLiveInAttr(VReg, Flags);
4130         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4131 
4132         if (ObjectVT == MVT::f32) {
4133           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4134             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4135                                  DAG.getConstant(32, dl, MVT::i32));
4136           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4137         }
4138 
4139         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4140       } else {
4141         if (CallConv == CallingConv::Fast)
4142           ComputeArgOffset();
4143 
4144         needsLoad = true;
4145       }
4146 
4147       // When passing an array of floats, the array occupies consecutive
4148       // space in the argument area; only round up to the next doubleword
4149       // at the end of the array.  Otherwise, each float takes 8 bytes.
4150       if (CallConv != CallingConv::Fast || needsLoad) {
4151         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4152         ArgOffset += ArgSize;
4153         if (Flags.isInConsecutiveRegsLast())
4154           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4155       }
4156       break;
4157     case MVT::v4f32:
4158     case MVT::v4i32:
4159     case MVT::v8i16:
4160     case MVT::v16i8:
4161     case MVT::v2f64:
4162     case MVT::v2i64:
4163     case MVT::v1i128:
4164     case MVT::f128:
4165       if (!Subtarget.hasQPX()) {
4166         // These can be scalar arguments or elements of a vector array type
4167         // passed directly.  The latter are used to implement ELFv2 homogenous
4168         // vector aggregates.
4169         if (VR_idx != Num_VR_Regs) {
4170           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4171           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4172           ++VR_idx;
4173         } else {
4174           if (CallConv == CallingConv::Fast)
4175             ComputeArgOffset();
4176           needsLoad = true;
4177         }
4178         if (CallConv != CallingConv::Fast || needsLoad)
4179           ArgOffset += 16;
4180         break;
4181       } // not QPX
4182 
4183       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4184              "Invalid QPX parameter type");
4185       LLVM_FALLTHROUGH;
4186 
4187     case MVT::v4f64:
4188     case MVT::v4i1:
4189       // QPX vectors are treated like their scalar floating-point subregisters
4190       // (except that they're larger).
4191       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4192       if (QFPR_idx != Num_QFPR_Regs) {
4193         const TargetRegisterClass *RC;
4194         switch (ObjectVT.getSimpleVT().SimpleTy) {
4195         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4196         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4197         default:         RC = &PPC::QBRCRegClass; break;
4198         }
4199 
4200         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4201         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4202         ++QFPR_idx;
4203       } else {
4204         if (CallConv == CallingConv::Fast)
4205           ComputeArgOffset();
4206         needsLoad = true;
4207       }
4208       if (CallConv != CallingConv::Fast || needsLoad)
4209         ArgOffset += Sz;
4210       break;
4211     }
4212 
4213     // We need to load the argument to a virtual register if we determined
4214     // above that we ran out of physical registers of the appropriate type.
4215     if (needsLoad) {
4216       if (ObjSize < ArgSize && !isLittleEndian)
4217         CurArgOffset += ArgSize - ObjSize;
4218       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4219       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4220       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4221     }
4222 
4223     InVals.push_back(ArgVal);
4224   }
4225 
4226   // Area that is at least reserved in the caller of this function.
4227   unsigned MinReservedArea;
4228   if (HasParameterArea)
4229     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4230   else
4231     MinReservedArea = LinkageSize;
4232 
4233   // Set the size that is at least reserved in caller of this function.  Tail
4234   // call optimized functions' reserved stack space needs to be aligned so that
4235   // taking the difference between two stack areas will result in an aligned
4236   // stack.
4237   MinReservedArea =
4238       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4239   FuncInfo->setMinReservedArea(MinReservedArea);
4240 
4241   // If the function takes variable number of arguments, make a frame index for
4242   // the start of the first vararg value... for expansion of llvm.va_start.
4243   if (isVarArg) {
4244     int Depth = ArgOffset;
4245 
4246     FuncInfo->setVarArgsFrameIndex(
4247       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4248     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4249 
4250     // If this function is vararg, store any remaining integer argument regs
4251     // to their spots on the stack so that they may be loaded by dereferencing
4252     // the result of va_next.
4253     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4254          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4255       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4256       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4257       SDValue Store =
4258           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4259       MemOps.push_back(Store);
4260       // Increment the address by four for the next argument to store
4261       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4262       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4263     }
4264   }
4265 
4266   if (!MemOps.empty())
4267     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4268 
4269   return Chain;
4270 }
4271 
4272 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4273     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4274     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4275     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4276   // TODO: add description of PPC stack frame format, or at least some docs.
4277   //
4278   MachineFunction &MF = DAG.getMachineFunction();
4279   MachineFrameInfo &MFI = MF.getFrameInfo();
4280   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4281 
4282   EVT PtrVT = getPointerTy(MF.getDataLayout());
4283   bool isPPC64 = PtrVT == MVT::i64;
4284   // Potential tail calls could cause overwriting of argument stack slots.
4285   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4286                        (CallConv == CallingConv::Fast));
4287   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4288   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4289   unsigned ArgOffset = LinkageSize;
4290   // Area that is at least reserved in caller of this function.
4291   unsigned MinReservedArea = ArgOffset;
4292 
4293   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4294     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4295     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4296   };
4297   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4298     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4299     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4300   };
4301   static const MCPhysReg VR[] = {
4302     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4303     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4304   };
4305 
4306   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4307   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4308   const unsigned Num_VR_Regs  = array_lengthof( VR);
4309 
4310   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4311 
4312   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4313 
4314   // In 32-bit non-varargs functions, the stack space for vectors is after the
4315   // stack space for non-vectors.  We do not use this space unless we have
4316   // too many vectors to fit in registers, something that only occurs in
4317   // constructed examples:), but we have to walk the arglist to figure
4318   // that out...for the pathological case, compute VecArgOffset as the
4319   // start of the vector parameter area.  Computing VecArgOffset is the
4320   // entire point of the following loop.
4321   unsigned VecArgOffset = ArgOffset;
4322   if (!isVarArg && !isPPC64) {
4323     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4324          ++ArgNo) {
4325       EVT ObjectVT = Ins[ArgNo].VT;
4326       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4327 
4328       if (Flags.isByVal()) {
4329         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4330         unsigned ObjSize = Flags.getByValSize();
4331         unsigned ArgSize =
4332                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4333         VecArgOffset += ArgSize;
4334         continue;
4335       }
4336 
4337       switch(ObjectVT.getSimpleVT().SimpleTy) {
4338       default: llvm_unreachable("Unhandled argument type!");
4339       case MVT::i1:
4340       case MVT::i32:
4341       case MVT::f32:
4342         VecArgOffset += 4;
4343         break;
4344       case MVT::i64:  // PPC64
4345       case MVT::f64:
4346         // FIXME: We are guaranteed to be !isPPC64 at this point.
4347         // Does MVT::i64 apply?
4348         VecArgOffset += 8;
4349         break;
4350       case MVT::v4f32:
4351       case MVT::v4i32:
4352       case MVT::v8i16:
4353       case MVT::v16i8:
4354         // Nothing to do, we're only looking at Nonvector args here.
4355         break;
4356       }
4357     }
4358   }
4359   // We've found where the vector parameter area in memory is.  Skip the
4360   // first 12 parameters; these don't use that memory.
4361   VecArgOffset = ((VecArgOffset+15)/16)*16;
4362   VecArgOffset += 12*16;
4363 
4364   // Add DAG nodes to load the arguments or copy them out of registers.  On
4365   // entry to a function on PPC, the arguments start after the linkage area,
4366   // although the first ones are often in registers.
4367 
4368   SmallVector<SDValue, 8> MemOps;
4369   unsigned nAltivecParamsAtEnd = 0;
4370   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4371   unsigned CurArgIdx = 0;
4372   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4373     SDValue ArgVal;
4374     bool needsLoad = false;
4375     EVT ObjectVT = Ins[ArgNo].VT;
4376     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4377     unsigned ArgSize = ObjSize;
4378     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4379     if (Ins[ArgNo].isOrigArg()) {
4380       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4381       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4382     }
4383     unsigned CurArgOffset = ArgOffset;
4384 
4385     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4386     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4387         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4388       if (isVarArg || isPPC64) {
4389         MinReservedArea = ((MinReservedArea+15)/16)*16;
4390         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4391                                                   Flags,
4392                                                   PtrByteSize);
4393       } else  nAltivecParamsAtEnd++;
4394     } else
4395       // Calculate min reserved area.
4396       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4397                                                 Flags,
4398                                                 PtrByteSize);
4399 
4400     // FIXME the codegen can be much improved in some cases.
4401     // We do not have to keep everything in memory.
4402     if (Flags.isByVal()) {
4403       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4404 
4405       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4406       ObjSize = Flags.getByValSize();
4407       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4408       // Objects of size 1 and 2 are right justified, everything else is
4409       // left justified.  This means the memory address is adjusted forwards.
4410       if (ObjSize==1 || ObjSize==2) {
4411         CurArgOffset = CurArgOffset + (4 - ObjSize);
4412       }
4413       // The value of the object is its address.
4414       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4415       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4416       InVals.push_back(FIN);
4417       if (ObjSize==1 || ObjSize==2) {
4418         if (GPR_idx != Num_GPR_Regs) {
4419           unsigned VReg;
4420           if (isPPC64)
4421             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4422           else
4423             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4424           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4425           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4426           SDValue Store =
4427               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4428                                 MachinePointerInfo(&*FuncArg), ObjType);
4429           MemOps.push_back(Store);
4430           ++GPR_idx;
4431         }
4432 
4433         ArgOffset += PtrByteSize;
4434 
4435         continue;
4436       }
4437       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4438         // Store whatever pieces of the object are in registers
4439         // to memory.  ArgOffset will be the address of the beginning
4440         // of the object.
4441         if (GPR_idx != Num_GPR_Regs) {
4442           unsigned VReg;
4443           if (isPPC64)
4444             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4445           else
4446             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4447           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4448           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4449           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4450           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4451                                        MachinePointerInfo(&*FuncArg, j));
4452           MemOps.push_back(Store);
4453           ++GPR_idx;
4454           ArgOffset += PtrByteSize;
4455         } else {
4456           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4457           break;
4458         }
4459       }
4460       continue;
4461     }
4462 
4463     switch (ObjectVT.getSimpleVT().SimpleTy) {
4464     default: llvm_unreachable("Unhandled argument type!");
4465     case MVT::i1:
4466     case MVT::i32:
4467       if (!isPPC64) {
4468         if (GPR_idx != Num_GPR_Regs) {
4469           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4470           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4471 
4472           if (ObjectVT == MVT::i1)
4473             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4474 
4475           ++GPR_idx;
4476         } else {
4477           needsLoad = true;
4478           ArgSize = PtrByteSize;
4479         }
4480         // All int arguments reserve stack space in the Darwin ABI.
4481         ArgOffset += PtrByteSize;
4482         break;
4483       }
4484       LLVM_FALLTHROUGH;
4485     case MVT::i64:  // PPC64
4486       if (GPR_idx != Num_GPR_Regs) {
4487         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4488         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4489 
4490         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4491           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4492           // value to MVT::i64 and then truncate to the correct register size.
4493           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4494 
4495         ++GPR_idx;
4496       } else {
4497         needsLoad = true;
4498         ArgSize = PtrByteSize;
4499       }
4500       // All int arguments reserve stack space in the Darwin ABI.
4501       ArgOffset += 8;
4502       break;
4503 
4504     case MVT::f32:
4505     case MVT::f64:
4506       // Every 4 bytes of argument space consumes one of the GPRs available for
4507       // argument passing.
4508       if (GPR_idx != Num_GPR_Regs) {
4509         ++GPR_idx;
4510         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4511           ++GPR_idx;
4512       }
4513       if (FPR_idx != Num_FPR_Regs) {
4514         unsigned VReg;
4515 
4516         if (ObjectVT == MVT::f32)
4517           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4518         else
4519           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4520 
4521         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4522         ++FPR_idx;
4523       } else {
4524         needsLoad = true;
4525       }
4526 
4527       // All FP arguments reserve stack space in the Darwin ABI.
4528       ArgOffset += isPPC64 ? 8 : ObjSize;
4529       break;
4530     case MVT::v4f32:
4531     case MVT::v4i32:
4532     case MVT::v8i16:
4533     case MVT::v16i8:
4534       // Note that vector arguments in registers don't reserve stack space,
4535       // except in varargs functions.
4536       if (VR_idx != Num_VR_Regs) {
4537         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4538         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4539         if (isVarArg) {
4540           while ((ArgOffset % 16) != 0) {
4541             ArgOffset += PtrByteSize;
4542             if (GPR_idx != Num_GPR_Regs)
4543               GPR_idx++;
4544           }
4545           ArgOffset += 16;
4546           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4547         }
4548         ++VR_idx;
4549       } else {
4550         if (!isVarArg && !isPPC64) {
4551           // Vectors go after all the nonvectors.
4552           CurArgOffset = VecArgOffset;
4553           VecArgOffset += 16;
4554         } else {
4555           // Vectors are aligned.
4556           ArgOffset = ((ArgOffset+15)/16)*16;
4557           CurArgOffset = ArgOffset;
4558           ArgOffset += 16;
4559         }
4560         needsLoad = true;
4561       }
4562       break;
4563     }
4564 
4565     // We need to load the argument to a virtual register if we determined above
4566     // that we ran out of physical registers of the appropriate type.
4567     if (needsLoad) {
4568       int FI = MFI.CreateFixedObject(ObjSize,
4569                                      CurArgOffset + (ArgSize - ObjSize),
4570                                      isImmutable);
4571       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4572       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4573     }
4574 
4575     InVals.push_back(ArgVal);
4576   }
4577 
4578   // Allow for Altivec parameters at the end, if needed.
4579   if (nAltivecParamsAtEnd) {
4580     MinReservedArea = ((MinReservedArea+15)/16)*16;
4581     MinReservedArea += 16*nAltivecParamsAtEnd;
4582   }
4583 
4584   // Area that is at least reserved in the caller of this function.
4585   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4586 
4587   // Set the size that is at least reserved in caller of this function.  Tail
4588   // call optimized functions' reserved stack space needs to be aligned so that
4589   // taking the difference between two stack areas will result in an aligned
4590   // stack.
4591   MinReservedArea =
4592       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4593   FuncInfo->setMinReservedArea(MinReservedArea);
4594 
4595   // If the function takes variable number of arguments, make a frame index for
4596   // the start of the first vararg value... for expansion of llvm.va_start.
4597   if (isVarArg) {
4598     int Depth = ArgOffset;
4599 
4600     FuncInfo->setVarArgsFrameIndex(
4601       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4602                             Depth, true));
4603     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4604 
4605     // If this function is vararg, store any remaining integer argument regs
4606     // to their spots on the stack so that they may be loaded by dereferencing
4607     // the result of va_next.
4608     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4609       unsigned VReg;
4610 
4611       if (isPPC64)
4612         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4613       else
4614         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4615 
4616       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4617       SDValue Store =
4618           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4619       MemOps.push_back(Store);
4620       // Increment the address by four for the next argument to store
4621       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4622       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4623     }
4624   }
4625 
4626   if (!MemOps.empty())
4627     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4628 
4629   return Chain;
4630 }
4631 
4632 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4633 /// adjusted to accommodate the arguments for the tailcall.
4634 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4635                                    unsigned ParamSize) {
4636 
4637   if (!isTailCall) return 0;
4638 
4639   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4640   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4641   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4642   // Remember only if the new adjustment is bigger.
4643   if (SPDiff < FI->getTailCallSPDelta())
4644     FI->setTailCallSPDelta(SPDiff);
4645 
4646   return SPDiff;
4647 }
4648 
4649 static bool isFunctionGlobalAddress(SDValue Callee);
4650 
4651 static bool
4652 callsShareTOCBase(const Function *Caller, SDValue Callee,
4653                     const TargetMachine &TM) {
4654    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4655    // don't have enough information to determine if the caller and calle share
4656    // the same  TOC base, so we have to pessimistically assume they don't for
4657    // correctness.
4658    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4659    if (!G)
4660      return false;
4661 
4662    const GlobalValue *GV = G->getGlobal();
4663   // The medium and large code models are expected to provide a sufficiently
4664   // large TOC to provide all data addressing needs of a module with a
4665   // single TOC. Since each module will be addressed with a single TOC then we
4666   // only need to check that caller and callee don't cross dso boundaries.
4667   if (CodeModel::Medium == TM.getCodeModel() ||
4668       CodeModel::Large == TM.getCodeModel())
4669     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4670 
4671   // Otherwise we need to ensure callee and caller are in the same section,
4672   // since the linker may allocate multiple TOCs, and we don't know which
4673   // sections will belong to the same TOC base.
4674 
4675   if (!GV->isStrongDefinitionForLinker())
4676     return false;
4677 
4678   // Any explicitly-specified sections and section prefixes must also match.
4679   // Also, if we're using -ffunction-sections, then each function is always in
4680   // a different section (the same is true for COMDAT functions).
4681   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4682       GV->getSection() != Caller->getSection())
4683     return false;
4684   if (const auto *F = dyn_cast<Function>(GV)) {
4685     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4686       return false;
4687   }
4688 
4689   // If the callee might be interposed, then we can't assume the ultimate call
4690   // target will be in the same section. Even in cases where we can assume that
4691   // interposition won't happen, in any case where the linker might insert a
4692   // stub to allow for interposition, we must generate code as though
4693   // interposition might occur. To understand why this matters, consider a
4694   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4695   // in the same section, but a is in a different module (i.e. has a different
4696   // TOC base pointer). If the linker allows for interposition between b and c,
4697   // then it will generate a stub for the call edge between b and c which will
4698   // save the TOC pointer into the designated stack slot allocated by b. If we
4699   // return true here, and therefore allow a tail call between b and c, that
4700   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4701   // pointer into the stack slot allocated by a (where the a -> b stub saved
4702   // a's TOC base pointer). If we're not considering a tail call, but rather,
4703   // whether a nop is needed after the call instruction in b, because the linker
4704   // will insert a stub, it might complain about a missing nop if we omit it
4705   // (although many don't complain in this case).
4706   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4707     return false;
4708 
4709   return true;
4710 }
4711 
4712 static bool
4713 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4714                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4715   assert(Subtarget.is64BitELFABI());
4716 
4717   const unsigned PtrByteSize = 8;
4718   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4719 
4720   static const MCPhysReg GPR[] = {
4721     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4722     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4723   };
4724   static const MCPhysReg VR[] = {
4725     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4726     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4727   };
4728 
4729   const unsigned NumGPRs = array_lengthof(GPR);
4730   const unsigned NumFPRs = 13;
4731   const unsigned NumVRs = array_lengthof(VR);
4732   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4733 
4734   unsigned NumBytes = LinkageSize;
4735   unsigned AvailableFPRs = NumFPRs;
4736   unsigned AvailableVRs = NumVRs;
4737 
4738   for (const ISD::OutputArg& Param : Outs) {
4739     if (Param.Flags.isNest()) continue;
4740 
4741     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4742                                PtrByteSize, LinkageSize, ParamAreaSize,
4743                                NumBytes, AvailableFPRs, AvailableVRs,
4744                                Subtarget.hasQPX()))
4745       return true;
4746   }
4747   return false;
4748 }
4749 
4750 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4751   if (CB.arg_size() != CallerFn->arg_size())
4752     return false;
4753 
4754   auto CalleeArgIter = CB.arg_begin();
4755   auto CalleeArgEnd = CB.arg_end();
4756   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4757 
4758   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4759     const Value* CalleeArg = *CalleeArgIter;
4760     const Value* CallerArg = &(*CallerArgIter);
4761     if (CalleeArg == CallerArg)
4762       continue;
4763 
4764     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4765     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4766     //      }
4767     // 1st argument of callee is undef and has the same type as caller.
4768     if (CalleeArg->getType() == CallerArg->getType() &&
4769         isa<UndefValue>(CalleeArg))
4770       continue;
4771 
4772     return false;
4773   }
4774 
4775   return true;
4776 }
4777 
4778 // Returns true if TCO is possible between the callers and callees
4779 // calling conventions.
4780 static bool
4781 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4782                                     CallingConv::ID CalleeCC) {
4783   // Tail calls are possible with fastcc and ccc.
4784   auto isTailCallableCC  = [] (CallingConv::ID CC){
4785       return  CC == CallingConv::C || CC == CallingConv::Fast;
4786   };
4787   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4788     return false;
4789 
4790   // We can safely tail call both fastcc and ccc callees from a c calling
4791   // convention caller. If the caller is fastcc, we may have less stack space
4792   // than a non-fastcc caller with the same signature so disable tail-calls in
4793   // that case.
4794   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4795 }
4796 
4797 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4798     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4799     const SmallVectorImpl<ISD::OutputArg> &Outs,
4800     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4801   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4802 
4803   if (DisableSCO && !TailCallOpt) return false;
4804 
4805   // Variadic argument functions are not supported.
4806   if (isVarArg) return false;
4807 
4808   auto &Caller = DAG.getMachineFunction().getFunction();
4809   // Check that the calling conventions are compatible for tco.
4810   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4811     return false;
4812 
4813   // Caller contains any byval parameter is not supported.
4814   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4815     return false;
4816 
4817   // Callee contains any byval parameter is not supported, too.
4818   // Note: This is a quick work around, because in some cases, e.g.
4819   // caller's stack size > callee's stack size, we are still able to apply
4820   // sibling call optimization. For example, gcc is able to do SCO for caller1
4821   // in the following example, but not for caller2.
4822   //   struct test {
4823   //     long int a;
4824   //     char ary[56];
4825   //   } gTest;
4826   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4827   //     b->a = v.a;
4828   //     return 0;
4829   //   }
4830   //   void caller1(struct test a, struct test c, struct test *b) {
4831   //     callee(gTest, b); }
4832   //   void caller2(struct test *b) { callee(gTest, b); }
4833   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4834     return false;
4835 
4836   // If callee and caller use different calling conventions, we cannot pass
4837   // parameters on stack since offsets for the parameter area may be different.
4838   if (Caller.getCallingConv() != CalleeCC &&
4839       needStackSlotPassParameters(Subtarget, Outs))
4840     return false;
4841 
4842   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4843   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4844   // callee potentially have different TOC bases then we cannot tail call since
4845   // we need to restore the TOC pointer after the call.
4846   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4847   // We cannot guarantee this for indirect calls or calls to external functions.
4848   // When PC-Relative addressing is used, the concept of the TOC is no longer
4849   // applicable so this check is not required.
4850   // Check first for indirect calls.
4851   if (!Subtarget.isUsingPCRelativeCalls() &&
4852       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4853     return false;
4854 
4855   // Check if we share the TOC base.
4856   if (!Subtarget.isUsingPCRelativeCalls() &&
4857       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4858     return false;
4859 
4860   // TCO allows altering callee ABI, so we don't have to check further.
4861   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4862     return true;
4863 
4864   if (DisableSCO) return false;
4865 
4866   // If callee use the same argument list that caller is using, then we can
4867   // apply SCO on this case. If it is not, then we need to check if callee needs
4868   // stack for passing arguments.
4869   // PC Relative tail calls may not have a CallBase.
4870   // If there is no CallBase we cannot verify if we have the same argument
4871   // list so assume that we don't have the same argument list.
4872   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4873       needStackSlotPassParameters(Subtarget, Outs))
4874     return false;
4875   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4876     return false;
4877 
4878   return true;
4879 }
4880 
4881 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4882 /// for tail call optimization. Targets which want to do tail call
4883 /// optimization should implement this function.
4884 bool
4885 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4886                                                      CallingConv::ID CalleeCC,
4887                                                      bool isVarArg,
4888                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4889                                                      SelectionDAG& DAG) const {
4890   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4891     return false;
4892 
4893   // Variable argument functions are not supported.
4894   if (isVarArg)
4895     return false;
4896 
4897   MachineFunction &MF = DAG.getMachineFunction();
4898   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4899   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4900     // Functions containing by val parameters are not supported.
4901     for (unsigned i = 0; i != Ins.size(); i++) {
4902        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4903        if (Flags.isByVal()) return false;
4904     }
4905 
4906     // Non-PIC/GOT tail calls are supported.
4907     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4908       return true;
4909 
4910     // At the moment we can only do local tail calls (in same module, hidden
4911     // or protected) if we are generating PIC.
4912     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4913       return G->getGlobal()->hasHiddenVisibility()
4914           || G->getGlobal()->hasProtectedVisibility();
4915   }
4916 
4917   return false;
4918 }
4919 
4920 /// isCallCompatibleAddress - Return the immediate to use if the specified
4921 /// 32-bit value is representable in the immediate field of a BxA instruction.
4922 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4923   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4924   if (!C) return nullptr;
4925 
4926   int Addr = C->getZExtValue();
4927   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4928       SignExtend32<26>(Addr) != Addr)
4929     return nullptr;  // Top 6 bits have to be sext of immediate.
4930 
4931   return DAG
4932       .getConstant(
4933           (int)C->getZExtValue() >> 2, SDLoc(Op),
4934           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4935       .getNode();
4936 }
4937 
4938 namespace {
4939 
4940 struct TailCallArgumentInfo {
4941   SDValue Arg;
4942   SDValue FrameIdxOp;
4943   int FrameIdx = 0;
4944 
4945   TailCallArgumentInfo() = default;
4946 };
4947 
4948 } // end anonymous namespace
4949 
4950 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4951 static void StoreTailCallArgumentsToStackSlot(
4952     SelectionDAG &DAG, SDValue Chain,
4953     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4954     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4955   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4956     SDValue Arg = TailCallArgs[i].Arg;
4957     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4958     int FI = TailCallArgs[i].FrameIdx;
4959     // Store relative to framepointer.
4960     MemOpChains.push_back(DAG.getStore(
4961         Chain, dl, Arg, FIN,
4962         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4963   }
4964 }
4965 
4966 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4967 /// the appropriate stack slot for the tail call optimized function call.
4968 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4969                                              SDValue OldRetAddr, SDValue OldFP,
4970                                              int SPDiff, const SDLoc &dl) {
4971   if (SPDiff) {
4972     // Calculate the new stack slot for the return address.
4973     MachineFunction &MF = DAG.getMachineFunction();
4974     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4975     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4976     bool isPPC64 = Subtarget.isPPC64();
4977     int SlotSize = isPPC64 ? 8 : 4;
4978     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4979     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4980                                                          NewRetAddrLoc, true);
4981     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4982     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4983     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4984                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4985   }
4986   return Chain;
4987 }
4988 
4989 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4990 /// the position of the argument.
4991 static void
4992 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4993                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4994                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4995   int Offset = ArgOffset + SPDiff;
4996   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4997   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4998   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4999   SDValue FIN = DAG.getFrameIndex(FI, VT);
5000   TailCallArgumentInfo Info;
5001   Info.Arg = Arg;
5002   Info.FrameIdxOp = FIN;
5003   Info.FrameIdx = FI;
5004   TailCallArguments.push_back(Info);
5005 }
5006 
5007 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5008 /// stack slot. Returns the chain as result and the loaded frame pointers in
5009 /// LROpOut/FPOpout. Used when tail calling.
5010 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5011     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5012     SDValue &FPOpOut, const SDLoc &dl) const {
5013   if (SPDiff) {
5014     // Load the LR and FP stack slot for later adjusting.
5015     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5016     LROpOut = getReturnAddrFrameIndex(DAG);
5017     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5018     Chain = SDValue(LROpOut.getNode(), 1);
5019   }
5020   return Chain;
5021 }
5022 
5023 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5024 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5025 /// specified by the specific parameter attribute. The copy will be passed as
5026 /// a byval function parameter.
5027 /// Sometimes what we are copying is the end of a larger object, the part that
5028 /// does not fit in registers.
5029 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5030                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5031                                          SelectionDAG &DAG, const SDLoc &dl) {
5032   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5033   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5034                        Flags.getNonZeroByValAlign(), false, false, false,
5035                        MachinePointerInfo(), MachinePointerInfo());
5036 }
5037 
5038 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5039 /// tail calls.
5040 static void LowerMemOpCallTo(
5041     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5042     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5043     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5044     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5045   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5046   if (!isTailCall) {
5047     if (isVector) {
5048       SDValue StackPtr;
5049       if (isPPC64)
5050         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5051       else
5052         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5053       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5054                            DAG.getConstant(ArgOffset, dl, PtrVT));
5055     }
5056     MemOpChains.push_back(
5057         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5058     // Calculate and remember argument location.
5059   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5060                                   TailCallArguments);
5061 }
5062 
5063 static void
5064 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5065                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5066                 SDValue FPOp,
5067                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5068   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5069   // might overwrite each other in case of tail call optimization.
5070   SmallVector<SDValue, 8> MemOpChains2;
5071   // Do not flag preceding copytoreg stuff together with the following stuff.
5072   InFlag = SDValue();
5073   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5074                                     MemOpChains2, dl);
5075   if (!MemOpChains2.empty())
5076     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5077 
5078   // Store the return address to the appropriate stack slot.
5079   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5080 
5081   // Emit callseq_end just before tailcall node.
5082   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5083                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5084   InFlag = Chain.getValue(1);
5085 }
5086 
5087 // Is this global address that of a function that can be called by name? (as
5088 // opposed to something that must hold a descriptor for an indirect call).
5089 static bool isFunctionGlobalAddress(SDValue Callee) {
5090   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5091     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5092         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5093       return false;
5094 
5095     return G->getGlobal()->getValueType()->isFunctionTy();
5096   }
5097 
5098   return false;
5099 }
5100 
5101 SDValue PPCTargetLowering::LowerCallResult(
5102     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5103     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5104     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5105   SmallVector<CCValAssign, 16> RVLocs;
5106   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5107                     *DAG.getContext());
5108 
5109   CCRetInfo.AnalyzeCallResult(
5110       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5111                ? RetCC_PPC_Cold
5112                : RetCC_PPC);
5113 
5114   // Copy all of the result registers out of their specified physreg.
5115   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5116     CCValAssign &VA = RVLocs[i];
5117     assert(VA.isRegLoc() && "Can only return in registers!");
5118 
5119     SDValue Val;
5120 
5121     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5122       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5123                                       InFlag);
5124       Chain = Lo.getValue(1);
5125       InFlag = Lo.getValue(2);
5126       VA = RVLocs[++i]; // skip ahead to next loc
5127       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5128                                       InFlag);
5129       Chain = Hi.getValue(1);
5130       InFlag = Hi.getValue(2);
5131       if (!Subtarget.isLittleEndian())
5132         std::swap (Lo, Hi);
5133       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5134     } else {
5135       Val = DAG.getCopyFromReg(Chain, dl,
5136                                VA.getLocReg(), VA.getLocVT(), InFlag);
5137       Chain = Val.getValue(1);
5138       InFlag = Val.getValue(2);
5139     }
5140 
5141     switch (VA.getLocInfo()) {
5142     default: llvm_unreachable("Unknown loc info!");
5143     case CCValAssign::Full: break;
5144     case CCValAssign::AExt:
5145       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5146       break;
5147     case CCValAssign::ZExt:
5148       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5149                         DAG.getValueType(VA.getValVT()));
5150       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5151       break;
5152     case CCValAssign::SExt:
5153       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5154                         DAG.getValueType(VA.getValVT()));
5155       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5156       break;
5157     }
5158 
5159     InVals.push_back(Val);
5160   }
5161 
5162   return Chain;
5163 }
5164 
5165 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5166                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5167   // PatchPoint calls are not indirect.
5168   if (isPatchPoint)
5169     return false;
5170 
5171   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5172     return false;
5173 
5174   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5175   // becuase the immediate function pointer points to a descriptor instead of
5176   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5177   // pointer immediate points to the global entry point, while the BLA would
5178   // need to jump to the local entry point (see rL211174).
5179   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5180       isBLACompatibleAddress(Callee, DAG))
5181     return false;
5182 
5183   return true;
5184 }
5185 
5186 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5187 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5188   return Subtarget.isAIXABI() ||
5189          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5190 }
5191 
5192 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5193                               const Function &Caller,
5194                               const SDValue &Callee,
5195                               const PPCSubtarget &Subtarget,
5196                               const TargetMachine &TM) {
5197   if (CFlags.IsTailCall)
5198     return PPCISD::TC_RETURN;
5199 
5200   // This is a call through a function pointer.
5201   if (CFlags.IsIndirect) {
5202     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5203     // indirect calls. The save of the caller's TOC pointer to the stack will be
5204     // inserted into the DAG as part of call lowering. The restore of the TOC
5205     // pointer is modeled by using a pseudo instruction for the call opcode that
5206     // represents the 2 instruction sequence of an indirect branch and link,
5207     // immediately followed by a load of the TOC pointer from the the stack save
5208     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5209     // as it is not saved or used.
5210     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5211                                                : PPCISD::BCTRL;
5212   }
5213 
5214   if (Subtarget.isUsingPCRelativeCalls()) {
5215     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5216     return PPCISD::CALL_NOTOC;
5217   }
5218 
5219   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5220   // immediately following the call instruction if the caller and callee may
5221   // have different TOC bases. At link time if the linker determines the calls
5222   // may not share a TOC base, the call is redirected to a trampoline inserted
5223   // by the linker. The trampoline will (among other things) save the callers
5224   // TOC pointer at an ABI designated offset in the linkage area and the linker
5225   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5226   // into gpr2.
5227   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5228       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5229                                                     : PPCISD::CALL_NOP;
5230 
5231   return PPCISD::CALL;
5232 }
5233 
5234 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5235                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5236   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5237     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5238       return SDValue(Dest, 0);
5239 
5240   // Returns true if the callee is local, and false otherwise.
5241   auto isLocalCallee = [&]() {
5242     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5243     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5244     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5245 
5246     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5247            !dyn_cast_or_null<GlobalIFunc>(GV);
5248   };
5249 
5250   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5251   // a static relocation model causes some versions of GNU LD (2.17.50, at
5252   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5253   // built with secure-PLT.
5254   bool UsePlt =
5255       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5256       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5257 
5258   // On AIX, direct function calls reference the symbol for the function's
5259   // entry point, which is named by prepending a "." before the function's
5260   // C-linkage name.
5261   const auto getAIXFuncEntryPointSymbolSDNode =
5262       [&](StringRef FuncName, bool IsDeclaration,
5263           const XCOFF::StorageClass &SC) {
5264         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5265 
5266         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5267             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5268 
5269         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5270           // On AIX, an undefined symbol needs to be associated with a
5271           // MCSectionXCOFF to get the correct storage mapping class.
5272           // In this case, XCOFF::XMC_PR.
5273           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5274               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5275               SectionKind::getMetadata());
5276           S->setRepresentedCsect(Sec);
5277         }
5278 
5279         MVT PtrVT =
5280             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5281         return DAG.getMCSymbol(S, PtrVT);
5282       };
5283 
5284   if (isFunctionGlobalAddress(Callee)) {
5285     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5286     const GlobalValue *GV = G->getGlobal();
5287 
5288     if (!Subtarget.isAIXABI())
5289       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5290                                         UsePlt ? PPCII::MO_PLT : 0);
5291 
5292     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5293     const GlobalObject *GO = cast<GlobalObject>(GV);
5294     const XCOFF::StorageClass SC =
5295         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5296     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5297                                             SC);
5298   }
5299 
5300   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5301     const char *SymName = S->getSymbol();
5302     if (!Subtarget.isAIXABI())
5303       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5304                                          UsePlt ? PPCII::MO_PLT : 0);
5305 
5306     // If there exists a user-declared function whose name is the same as the
5307     // ExternalSymbol's, then we pick up the user-declared version.
5308     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5309     if (const Function *F =
5310             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5311       const XCOFF::StorageClass SC =
5312           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5313       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5314                                               SC);
5315     }
5316 
5317     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5318   }
5319 
5320   // No transformation needed.
5321   assert(Callee.getNode() && "What no callee?");
5322   return Callee;
5323 }
5324 
5325 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5326   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5327          "Expected a CALLSEQ_STARTSDNode.");
5328 
5329   // The last operand is the chain, except when the node has glue. If the node
5330   // has glue, then the last operand is the glue, and the chain is the second
5331   // last operand.
5332   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5333   if (LastValue.getValueType() != MVT::Glue)
5334     return LastValue;
5335 
5336   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5337 }
5338 
5339 // Creates the node that moves a functions address into the count register
5340 // to prepare for an indirect call instruction.
5341 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5342                                 SDValue &Glue, SDValue &Chain,
5343                                 const SDLoc &dl) {
5344   SDValue MTCTROps[] = {Chain, Callee, Glue};
5345   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5346   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5347                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5348   // The glue is the second value produced.
5349   Glue = Chain.getValue(1);
5350 }
5351 
5352 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5353                                           SDValue &Glue, SDValue &Chain,
5354                                           SDValue CallSeqStart,
5355                                           const CallBase *CB, const SDLoc &dl,
5356                                           bool hasNest,
5357                                           const PPCSubtarget &Subtarget) {
5358   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5359   // entry point, but to the function descriptor (the function entry point
5360   // address is part of the function descriptor though).
5361   // The function descriptor is a three doubleword structure with the
5362   // following fields: function entry point, TOC base address and
5363   // environment pointer.
5364   // Thus for a call through a function pointer, the following actions need
5365   // to be performed:
5366   //   1. Save the TOC of the caller in the TOC save area of its stack
5367   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5368   //   2. Load the address of the function entry point from the function
5369   //      descriptor.
5370   //   3. Load the TOC of the callee from the function descriptor into r2.
5371   //   4. Load the environment pointer from the function descriptor into
5372   //      r11.
5373   //   5. Branch to the function entry point address.
5374   //   6. On return of the callee, the TOC of the caller needs to be
5375   //      restored (this is done in FinishCall()).
5376   //
5377   // The loads are scheduled at the beginning of the call sequence, and the
5378   // register copies are flagged together to ensure that no other
5379   // operations can be scheduled in between. E.g. without flagging the
5380   // copies together, a TOC access in the caller could be scheduled between
5381   // the assignment of the callee TOC and the branch to the callee, which leads
5382   // to incorrect code.
5383 
5384   // Start by loading the function address from the descriptor.
5385   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5386   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5387                       ? (MachineMemOperand::MODereferenceable |
5388                          MachineMemOperand::MOInvariant)
5389                       : MachineMemOperand::MONone;
5390 
5391   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5392 
5393   // Registers used in building the DAG.
5394   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5395   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5396 
5397   // Offsets of descriptor members.
5398   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5399   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5400 
5401   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5402   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5403 
5404   // One load for the functions entry point address.
5405   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5406                                     Alignment, MMOFlags);
5407 
5408   // One for loading the TOC anchor for the module that contains the called
5409   // function.
5410   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5411   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5412   SDValue TOCPtr =
5413       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5414                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5415 
5416   // One for loading the environment pointer.
5417   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5418   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5419   SDValue LoadEnvPtr =
5420       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5421                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5422 
5423 
5424   // Then copy the newly loaded TOC anchor to the TOC pointer.
5425   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5426   Chain = TOCVal.getValue(0);
5427   Glue = TOCVal.getValue(1);
5428 
5429   // If the function call has an explicit 'nest' parameter, it takes the
5430   // place of the environment pointer.
5431   assert((!hasNest || !Subtarget.isAIXABI()) &&
5432          "Nest parameter is not supported on AIX.");
5433   if (!hasNest) {
5434     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5435     Chain = EnvVal.getValue(0);
5436     Glue = EnvVal.getValue(1);
5437   }
5438 
5439   // The rest of the indirect call sequence is the same as the non-descriptor
5440   // DAG.
5441   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5442 }
5443 
5444 static void
5445 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5446                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5447                   SelectionDAG &DAG,
5448                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5449                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5450                   const PPCSubtarget &Subtarget) {
5451   const bool IsPPC64 = Subtarget.isPPC64();
5452   // MVT for a general purpose register.
5453   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5454 
5455   // First operand is always the chain.
5456   Ops.push_back(Chain);
5457 
5458   // If it's a direct call pass the callee as the second operand.
5459   if (!CFlags.IsIndirect)
5460     Ops.push_back(Callee);
5461   else {
5462     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5463 
5464     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5465     // on the stack (this would have been done in `LowerCall_64SVR4` or
5466     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5467     // represents both the indirect branch and a load that restores the TOC
5468     // pointer from the linkage area. The operand for the TOC restore is an add
5469     // of the TOC save offset to the stack pointer. This must be the second
5470     // operand: after the chain input but before any other variadic arguments.
5471     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5472     // saved or used.
5473     if (isTOCSaveRestoreRequired(Subtarget)) {
5474       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5475 
5476       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5477       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5478       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5479       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5480       Ops.push_back(AddTOC);
5481     }
5482 
5483     // Add the register used for the environment pointer.
5484     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5485       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5486                                     RegVT));
5487 
5488 
5489     // Add CTR register as callee so a bctr can be emitted later.
5490     if (CFlags.IsTailCall)
5491       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5492   }
5493 
5494   // If this is a tail call add stack pointer delta.
5495   if (CFlags.IsTailCall)
5496     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5497 
5498   // Add argument registers to the end of the list so that they are known live
5499   // into the call.
5500   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5501     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5502                                   RegsToPass[i].second.getValueType()));
5503 
5504   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5505   // no way to mark dependencies as implicit here.
5506   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5507   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5508        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5509     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5510 
5511   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5512   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5513     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5514 
5515   // Add a register mask operand representing the call-preserved registers.
5516   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5517   const uint32_t *Mask =
5518       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5519   assert(Mask && "Missing call preserved mask for calling convention");
5520   Ops.push_back(DAG.getRegisterMask(Mask));
5521 
5522   // If the glue is valid, it is the last operand.
5523   if (Glue.getNode())
5524     Ops.push_back(Glue);
5525 }
5526 
5527 SDValue PPCTargetLowering::FinishCall(
5528     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5529     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5530     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5531     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5532     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5533 
5534   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5535       Subtarget.isAIXABI())
5536     setUsesTOCBasePtr(DAG);
5537 
5538   unsigned CallOpc =
5539       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5540                     Subtarget, DAG.getTarget());
5541 
5542   if (!CFlags.IsIndirect)
5543     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5544   else if (Subtarget.usesFunctionDescriptors())
5545     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5546                                   dl, CFlags.HasNest, Subtarget);
5547   else
5548     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5549 
5550   // Build the operand list for the call instruction.
5551   SmallVector<SDValue, 8> Ops;
5552   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5553                     SPDiff, Subtarget);
5554 
5555   // Emit tail call.
5556   if (CFlags.IsTailCall) {
5557     // Indirect tail call when using PC Relative calls do not have the same
5558     // constraints.
5559     assert(((Callee.getOpcode() == ISD::Register &&
5560              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5561             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5562             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5563             isa<ConstantSDNode>(Callee) ||
5564             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5565            "Expecting a global address, external symbol, absolute value, "
5566            "register or an indirect tail call when PC Relative calls are "
5567            "used.");
5568     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5569     assert(CallOpc == PPCISD::TC_RETURN &&
5570            "Unexpected call opcode for a tail call.");
5571     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5572     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5573   }
5574 
5575   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5576   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5577   Glue = Chain.getValue(1);
5578 
5579   // When performing tail call optimization the callee pops its arguments off
5580   // the stack. Account for this here so these bytes can be pushed back on in
5581   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5582   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5583                          getTargetMachine().Options.GuaranteedTailCallOpt)
5584                             ? NumBytes
5585                             : 0;
5586 
5587   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5588                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5589                              Glue, dl);
5590   Glue = Chain.getValue(1);
5591 
5592   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5593                          DAG, InVals);
5594 }
5595 
5596 SDValue
5597 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5598                              SmallVectorImpl<SDValue> &InVals) const {
5599   SelectionDAG &DAG                     = CLI.DAG;
5600   SDLoc &dl                             = CLI.DL;
5601   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5602   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5603   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5604   SDValue Chain                         = CLI.Chain;
5605   SDValue Callee                        = CLI.Callee;
5606   bool &isTailCall                      = CLI.IsTailCall;
5607   CallingConv::ID CallConv              = CLI.CallConv;
5608   bool isVarArg                         = CLI.IsVarArg;
5609   bool isPatchPoint                     = CLI.IsPatchPoint;
5610   const CallBase *CB                    = CLI.CB;
5611 
5612   if (isTailCall) {
5613     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5614       isTailCall = false;
5615     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5616       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5617           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5618     else
5619       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5620                                                      Ins, DAG);
5621     if (isTailCall) {
5622       ++NumTailCalls;
5623       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5624         ++NumSiblingCalls;
5625 
5626       // PC Relative calls no longer guarantee that the callee is a Global
5627       // Address Node. The callee could be an indirect tail call in which
5628       // case the SDValue for the callee could be a load (to load the address
5629       // of a function pointer) or it may be a register copy (to move the
5630       // address of the callee from a function parameter into a virtual
5631       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5632       assert((Subtarget.isUsingPCRelativeCalls() ||
5633               isa<GlobalAddressSDNode>(Callee)) &&
5634              "Callee should be an llvm::Function object.");
5635 
5636       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5637                         << "\nTCO callee: ");
5638       LLVM_DEBUG(Callee.dump());
5639     }
5640   }
5641 
5642   if (!isTailCall && CB && CB->isMustTailCall())
5643     report_fatal_error("failed to perform tail call elimination on a call "
5644                        "site marked musttail");
5645 
5646   // When long calls (i.e. indirect calls) are always used, calls are always
5647   // made via function pointer. If we have a function name, first translate it
5648   // into a pointer.
5649   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5650       !isTailCall)
5651     Callee = LowerGlobalAddress(Callee, DAG);
5652 
5653   CallFlags CFlags(
5654       CallConv, isTailCall, isVarArg, isPatchPoint,
5655       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5656       // hasNest
5657       Subtarget.is64BitELFABI() &&
5658           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5659 
5660   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5661     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5662                             InVals, CB);
5663 
5664   if (Subtarget.isSVR4ABI())
5665     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5666                             InVals, CB);
5667 
5668   if (Subtarget.isAIXABI())
5669     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5670                          InVals, CB);
5671 
5672   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5673                           InVals, CB);
5674 }
5675 
5676 SDValue PPCTargetLowering::LowerCall_32SVR4(
5677     SDValue Chain, SDValue Callee, CallFlags CFlags,
5678     const SmallVectorImpl<ISD::OutputArg> &Outs,
5679     const SmallVectorImpl<SDValue> &OutVals,
5680     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5681     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5682     const CallBase *CB) const {
5683   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5684   // of the 32-bit SVR4 ABI stack frame layout.
5685 
5686   const CallingConv::ID CallConv = CFlags.CallConv;
5687   const bool IsVarArg = CFlags.IsVarArg;
5688   const bool IsTailCall = CFlags.IsTailCall;
5689 
5690   assert((CallConv == CallingConv::C ||
5691           CallConv == CallingConv::Cold ||
5692           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5693 
5694   unsigned PtrByteSize = 4;
5695 
5696   MachineFunction &MF = DAG.getMachineFunction();
5697 
5698   // Mark this function as potentially containing a function that contains a
5699   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5700   // and restoring the callers stack pointer in this functions epilog. This is
5701   // done because by tail calling the called function might overwrite the value
5702   // in this function's (MF) stack pointer stack slot 0(SP).
5703   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5704       CallConv == CallingConv::Fast)
5705     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5706 
5707   // Count how many bytes are to be pushed on the stack, including the linkage
5708   // area, parameter list area and the part of the local variable space which
5709   // contains copies of aggregates which are passed by value.
5710 
5711   // Assign locations to all of the outgoing arguments.
5712   SmallVector<CCValAssign, 16> ArgLocs;
5713   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5714 
5715   // Reserve space for the linkage area on the stack.
5716   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5717                        PtrByteSize);
5718   if (useSoftFloat())
5719     CCInfo.PreAnalyzeCallOperands(Outs);
5720 
5721   if (IsVarArg) {
5722     // Handle fixed and variable vector arguments differently.
5723     // Fixed vector arguments go into registers as long as registers are
5724     // available. Variable vector arguments always go into memory.
5725     unsigned NumArgs = Outs.size();
5726 
5727     for (unsigned i = 0; i != NumArgs; ++i) {
5728       MVT ArgVT = Outs[i].VT;
5729       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5730       bool Result;
5731 
5732       if (Outs[i].IsFixed) {
5733         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5734                                CCInfo);
5735       } else {
5736         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5737                                       ArgFlags, CCInfo);
5738       }
5739 
5740       if (Result) {
5741 #ifndef NDEBUG
5742         errs() << "Call operand #" << i << " has unhandled type "
5743              << EVT(ArgVT).getEVTString() << "\n";
5744 #endif
5745         llvm_unreachable(nullptr);
5746       }
5747     }
5748   } else {
5749     // All arguments are treated the same.
5750     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5751   }
5752   CCInfo.clearWasPPCF128();
5753 
5754   // Assign locations to all of the outgoing aggregate by value arguments.
5755   SmallVector<CCValAssign, 16> ByValArgLocs;
5756   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5757 
5758   // Reserve stack space for the allocations in CCInfo.
5759   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5760 
5761   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5762 
5763   // Size of the linkage area, parameter list area and the part of the local
5764   // space variable where copies of aggregates which are passed by value are
5765   // stored.
5766   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5767 
5768   // Calculate by how many bytes the stack has to be adjusted in case of tail
5769   // call optimization.
5770   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5771 
5772   // Adjust the stack pointer for the new arguments...
5773   // These operations are automatically eliminated by the prolog/epilog pass
5774   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5775   SDValue CallSeqStart = Chain;
5776 
5777   // Load the return address and frame pointer so it can be moved somewhere else
5778   // later.
5779   SDValue LROp, FPOp;
5780   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5781 
5782   // Set up a copy of the stack pointer for use loading and storing any
5783   // arguments that may not fit in the registers available for argument
5784   // passing.
5785   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5786 
5787   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5788   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5789   SmallVector<SDValue, 8> MemOpChains;
5790 
5791   bool seenFloatArg = false;
5792   // Walk the register/memloc assignments, inserting copies/loads.
5793   // i - Tracks the index into the list of registers allocated for the call
5794   // RealArgIdx - Tracks the index into the list of actual function arguments
5795   // j - Tracks the index into the list of byval arguments
5796   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5797        i != e;
5798        ++i, ++RealArgIdx) {
5799     CCValAssign &VA = ArgLocs[i];
5800     SDValue Arg = OutVals[RealArgIdx];
5801     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5802 
5803     if (Flags.isByVal()) {
5804       // Argument is an aggregate which is passed by value, thus we need to
5805       // create a copy of it in the local variable space of the current stack
5806       // frame (which is the stack frame of the caller) and pass the address of
5807       // this copy to the callee.
5808       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5809       CCValAssign &ByValVA = ByValArgLocs[j++];
5810       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5811 
5812       // Memory reserved in the local variable space of the callers stack frame.
5813       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5814 
5815       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5816       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5817                            StackPtr, PtrOff);
5818 
5819       // Create a copy of the argument in the local area of the current
5820       // stack frame.
5821       SDValue MemcpyCall =
5822         CreateCopyOfByValArgument(Arg, PtrOff,
5823                                   CallSeqStart.getNode()->getOperand(0),
5824                                   Flags, DAG, dl);
5825 
5826       // This must go outside the CALLSEQ_START..END.
5827       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5828                                                      SDLoc(MemcpyCall));
5829       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5830                              NewCallSeqStart.getNode());
5831       Chain = CallSeqStart = NewCallSeqStart;
5832 
5833       // Pass the address of the aggregate copy on the stack either in a
5834       // physical register or in the parameter list area of the current stack
5835       // frame to the callee.
5836       Arg = PtrOff;
5837     }
5838 
5839     // When useCRBits() is true, there can be i1 arguments.
5840     // It is because getRegisterType(MVT::i1) => MVT::i1,
5841     // and for other integer types getRegisterType() => MVT::i32.
5842     // Extend i1 and ensure callee will get i32.
5843     if (Arg.getValueType() == MVT::i1)
5844       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5845                         dl, MVT::i32, Arg);
5846 
5847     if (VA.isRegLoc()) {
5848       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5849       // Put argument in a physical register.
5850       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5851         bool IsLE = Subtarget.isLittleEndian();
5852         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5853                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5854         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5855         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5856                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5857         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5858                              SVal.getValue(0)));
5859       } else
5860         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5861     } else {
5862       // Put argument in the parameter list area of the current stack frame.
5863       assert(VA.isMemLoc());
5864       unsigned LocMemOffset = VA.getLocMemOffset();
5865 
5866       if (!IsTailCall) {
5867         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5868         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5869                              StackPtr, PtrOff);
5870 
5871         MemOpChains.push_back(
5872             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5873       } else {
5874         // Calculate and remember argument location.
5875         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5876                                  TailCallArguments);
5877       }
5878     }
5879   }
5880 
5881   if (!MemOpChains.empty())
5882     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5883 
5884   // Build a sequence of copy-to-reg nodes chained together with token chain
5885   // and flag operands which copy the outgoing args into the appropriate regs.
5886   SDValue InFlag;
5887   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5888     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5889                              RegsToPass[i].second, InFlag);
5890     InFlag = Chain.getValue(1);
5891   }
5892 
5893   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5894   // registers.
5895   if (IsVarArg) {
5896     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5897     SDValue Ops[] = { Chain, InFlag };
5898 
5899     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5900                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5901 
5902     InFlag = Chain.getValue(1);
5903   }
5904 
5905   if (IsTailCall)
5906     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5907                     TailCallArguments);
5908 
5909   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5910                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5911 }
5912 
5913 // Copy an argument into memory, being careful to do this outside the
5914 // call sequence for the call to which the argument belongs.
5915 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5916     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5917     SelectionDAG &DAG, const SDLoc &dl) const {
5918   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5919                         CallSeqStart.getNode()->getOperand(0),
5920                         Flags, DAG, dl);
5921   // The MEMCPY must go outside the CALLSEQ_START..END.
5922   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5923   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5924                                                  SDLoc(MemcpyCall));
5925   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5926                          NewCallSeqStart.getNode());
5927   return NewCallSeqStart;
5928 }
5929 
5930 SDValue PPCTargetLowering::LowerCall_64SVR4(
5931     SDValue Chain, SDValue Callee, CallFlags CFlags,
5932     const SmallVectorImpl<ISD::OutputArg> &Outs,
5933     const SmallVectorImpl<SDValue> &OutVals,
5934     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5935     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5936     const CallBase *CB) const {
5937   bool isELFv2ABI = Subtarget.isELFv2ABI();
5938   bool isLittleEndian = Subtarget.isLittleEndian();
5939   unsigned NumOps = Outs.size();
5940   bool IsSibCall = false;
5941   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5942 
5943   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5944   unsigned PtrByteSize = 8;
5945 
5946   MachineFunction &MF = DAG.getMachineFunction();
5947 
5948   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5949     IsSibCall = true;
5950 
5951   // Mark this function as potentially containing a function that contains a
5952   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5953   // and restoring the callers stack pointer in this functions epilog. This is
5954   // done because by tail calling the called function might overwrite the value
5955   // in this function's (MF) stack pointer stack slot 0(SP).
5956   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5957     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5958 
5959   assert(!(IsFastCall && CFlags.IsVarArg) &&
5960          "fastcc not supported on varargs functions");
5961 
5962   // Count how many bytes are to be pushed on the stack, including the linkage
5963   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5964   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5965   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5966   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5967   unsigned NumBytes = LinkageSize;
5968   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5969   unsigned &QFPR_idx = FPR_idx;
5970 
5971   static const MCPhysReg GPR[] = {
5972     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5973     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5974   };
5975   static const MCPhysReg VR[] = {
5976     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5977     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5978   };
5979 
5980   const unsigned NumGPRs = array_lengthof(GPR);
5981   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5982   const unsigned NumVRs  = array_lengthof(VR);
5983   const unsigned NumQFPRs = NumFPRs;
5984 
5985   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5986   // can be passed to the callee in registers.
5987   // For the fast calling convention, there is another check below.
5988   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5989   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5990   if (!HasParameterArea) {
5991     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5992     unsigned AvailableFPRs = NumFPRs;
5993     unsigned AvailableVRs = NumVRs;
5994     unsigned NumBytesTmp = NumBytes;
5995     for (unsigned i = 0; i != NumOps; ++i) {
5996       if (Outs[i].Flags.isNest()) continue;
5997       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5998                                 PtrByteSize, LinkageSize, ParamAreaSize,
5999                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
6000                                 Subtarget.hasQPX()))
6001         HasParameterArea = true;
6002     }
6003   }
6004 
6005   // When using the fast calling convention, we don't provide backing for
6006   // arguments that will be in registers.
6007   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6008 
6009   // Avoid allocating parameter area for fastcc functions if all the arguments
6010   // can be passed in the registers.
6011   if (IsFastCall)
6012     HasParameterArea = false;
6013 
6014   // Add up all the space actually used.
6015   for (unsigned i = 0; i != NumOps; ++i) {
6016     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6017     EVT ArgVT = Outs[i].VT;
6018     EVT OrigVT = Outs[i].ArgVT;
6019 
6020     if (Flags.isNest())
6021       continue;
6022 
6023     if (IsFastCall) {
6024       if (Flags.isByVal()) {
6025         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6026         if (NumGPRsUsed > NumGPRs)
6027           HasParameterArea = true;
6028       } else {
6029         switch (ArgVT.getSimpleVT().SimpleTy) {
6030         default: llvm_unreachable("Unexpected ValueType for argument!");
6031         case MVT::i1:
6032         case MVT::i32:
6033         case MVT::i64:
6034           if (++NumGPRsUsed <= NumGPRs)
6035             continue;
6036           break;
6037         case MVT::v4i32:
6038         case MVT::v8i16:
6039         case MVT::v16i8:
6040         case MVT::v2f64:
6041         case MVT::v2i64:
6042         case MVT::v1i128:
6043         case MVT::f128:
6044           if (++NumVRsUsed <= NumVRs)
6045             continue;
6046           break;
6047         case MVT::v4f32:
6048           // When using QPX, this is handled like a FP register, otherwise, it
6049           // is an Altivec register.
6050           if (Subtarget.hasQPX()) {
6051             if (++NumFPRsUsed <= NumFPRs)
6052               continue;
6053           } else {
6054             if (++NumVRsUsed <= NumVRs)
6055               continue;
6056           }
6057           break;
6058         case MVT::f32:
6059         case MVT::f64:
6060         case MVT::v4f64: // QPX
6061         case MVT::v4i1:  // QPX
6062           if (++NumFPRsUsed <= NumFPRs)
6063             continue;
6064           break;
6065         }
6066         HasParameterArea = true;
6067       }
6068     }
6069 
6070     /* Respect alignment of argument on the stack.  */
6071     auto Alignement =
6072         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6073     NumBytes = alignTo(NumBytes, Alignement);
6074 
6075     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6076     if (Flags.isInConsecutiveRegsLast())
6077       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6078   }
6079 
6080   unsigned NumBytesActuallyUsed = NumBytes;
6081 
6082   // In the old ELFv1 ABI,
6083   // the prolog code of the callee may store up to 8 GPR argument registers to
6084   // the stack, allowing va_start to index over them in memory if its varargs.
6085   // Because we cannot tell if this is needed on the caller side, we have to
6086   // conservatively assume that it is needed.  As such, make sure we have at
6087   // least enough stack space for the caller to store the 8 GPRs.
6088   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6089   // really requires memory operands, e.g. a vararg function.
6090   if (HasParameterArea)
6091     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6092   else
6093     NumBytes = LinkageSize;
6094 
6095   // Tail call needs the stack to be aligned.
6096   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6097     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6098 
6099   int SPDiff = 0;
6100 
6101   // Calculate by how many bytes the stack has to be adjusted in case of tail
6102   // call optimization.
6103   if (!IsSibCall)
6104     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6105 
6106   // To protect arguments on the stack from being clobbered in a tail call,
6107   // force all the loads to happen before doing any other lowering.
6108   if (CFlags.IsTailCall)
6109     Chain = DAG.getStackArgumentTokenFactor(Chain);
6110 
6111   // Adjust the stack pointer for the new arguments...
6112   // These operations are automatically eliminated by the prolog/epilog pass
6113   if (!IsSibCall)
6114     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6115   SDValue CallSeqStart = Chain;
6116 
6117   // Load the return address and frame pointer so it can be move somewhere else
6118   // later.
6119   SDValue LROp, FPOp;
6120   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6121 
6122   // Set up a copy of the stack pointer for use loading and storing any
6123   // arguments that may not fit in the registers available for argument
6124   // passing.
6125   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6126 
6127   // Figure out which arguments are going to go in registers, and which in
6128   // memory.  Also, if this is a vararg function, floating point operations
6129   // must be stored to our stack, and loaded into integer regs as well, if
6130   // any integer regs are available for argument passing.
6131   unsigned ArgOffset = LinkageSize;
6132 
6133   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6134   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6135 
6136   SmallVector<SDValue, 8> MemOpChains;
6137   for (unsigned i = 0; i != NumOps; ++i) {
6138     SDValue Arg = OutVals[i];
6139     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6140     EVT ArgVT = Outs[i].VT;
6141     EVT OrigVT = Outs[i].ArgVT;
6142 
6143     // PtrOff will be used to store the current argument to the stack if a
6144     // register cannot be found for it.
6145     SDValue PtrOff;
6146 
6147     // We re-align the argument offset for each argument, except when using the
6148     // fast calling convention, when we need to make sure we do that only when
6149     // we'll actually use a stack slot.
6150     auto ComputePtrOff = [&]() {
6151       /* Respect alignment of argument on the stack.  */
6152       auto Alignment =
6153           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6154       ArgOffset = alignTo(ArgOffset, Alignment);
6155 
6156       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6157 
6158       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6159     };
6160 
6161     if (!IsFastCall) {
6162       ComputePtrOff();
6163 
6164       /* Compute GPR index associated with argument offset.  */
6165       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6166       GPR_idx = std::min(GPR_idx, NumGPRs);
6167     }
6168 
6169     // Promote integers to 64-bit values.
6170     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6171       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6172       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6173       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6174     }
6175 
6176     // FIXME memcpy is used way more than necessary.  Correctness first.
6177     // Note: "by value" is code for passing a structure by value, not
6178     // basic types.
6179     if (Flags.isByVal()) {
6180       // Note: Size includes alignment padding, so
6181       //   struct x { short a; char b; }
6182       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6183       // These are the proper values we need for right-justifying the
6184       // aggregate in a parameter register.
6185       unsigned Size = Flags.getByValSize();
6186 
6187       // An empty aggregate parameter takes up no storage and no
6188       // registers.
6189       if (Size == 0)
6190         continue;
6191 
6192       if (IsFastCall)
6193         ComputePtrOff();
6194 
6195       // All aggregates smaller than 8 bytes must be passed right-justified.
6196       if (Size==1 || Size==2 || Size==4) {
6197         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6198         if (GPR_idx != NumGPRs) {
6199           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6200                                         MachinePointerInfo(), VT);
6201           MemOpChains.push_back(Load.getValue(1));
6202           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6203 
6204           ArgOffset += PtrByteSize;
6205           continue;
6206         }
6207       }
6208 
6209       if (GPR_idx == NumGPRs && Size < 8) {
6210         SDValue AddPtr = PtrOff;
6211         if (!isLittleEndian) {
6212           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6213                                           PtrOff.getValueType());
6214           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6215         }
6216         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6217                                                           CallSeqStart,
6218                                                           Flags, DAG, dl);
6219         ArgOffset += PtrByteSize;
6220         continue;
6221       }
6222       // Copy entire object into memory.  There are cases where gcc-generated
6223       // code assumes it is there, even if it could be put entirely into
6224       // registers.  (This is not what the doc says.)
6225 
6226       // FIXME: The above statement is likely due to a misunderstanding of the
6227       // documents.  All arguments must be copied into the parameter area BY
6228       // THE CALLEE in the event that the callee takes the address of any
6229       // formal argument.  That has not yet been implemented.  However, it is
6230       // reasonable to use the stack area as a staging area for the register
6231       // load.
6232 
6233       // Skip this for small aggregates, as we will use the same slot for a
6234       // right-justified copy, below.
6235       if (Size >= 8)
6236         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6237                                                           CallSeqStart,
6238                                                           Flags, DAG, dl);
6239 
6240       // When a register is available, pass a small aggregate right-justified.
6241       if (Size < 8 && GPR_idx != NumGPRs) {
6242         // The easiest way to get this right-justified in a register
6243         // is to copy the structure into the rightmost portion of a
6244         // local variable slot, then load the whole slot into the
6245         // register.
6246         // FIXME: The memcpy seems to produce pretty awful code for
6247         // small aggregates, particularly for packed ones.
6248         // FIXME: It would be preferable to use the slot in the
6249         // parameter save area instead of a new local variable.
6250         SDValue AddPtr = PtrOff;
6251         if (!isLittleEndian) {
6252           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6253           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6254         }
6255         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6256                                                           CallSeqStart,
6257                                                           Flags, DAG, dl);
6258 
6259         // Load the slot into the register.
6260         SDValue Load =
6261             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6262         MemOpChains.push_back(Load.getValue(1));
6263         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6264 
6265         // Done with this argument.
6266         ArgOffset += PtrByteSize;
6267         continue;
6268       }
6269 
6270       // For aggregates larger than PtrByteSize, copy the pieces of the
6271       // object that fit into registers from the parameter save area.
6272       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6273         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6274         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6275         if (GPR_idx != NumGPRs) {
6276           SDValue Load =
6277               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6278           MemOpChains.push_back(Load.getValue(1));
6279           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6280           ArgOffset += PtrByteSize;
6281         } else {
6282           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6283           break;
6284         }
6285       }
6286       continue;
6287     }
6288 
6289     switch (Arg.getSimpleValueType().SimpleTy) {
6290     default: llvm_unreachable("Unexpected ValueType for argument!");
6291     case MVT::i1:
6292     case MVT::i32:
6293     case MVT::i64:
6294       if (Flags.isNest()) {
6295         // The 'nest' parameter, if any, is passed in R11.
6296         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6297         break;
6298       }
6299 
6300       // These can be scalar arguments or elements of an integer array type
6301       // passed directly.  Clang may use those instead of "byval" aggregate
6302       // types to avoid forcing arguments to memory unnecessarily.
6303       if (GPR_idx != NumGPRs) {
6304         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6305       } else {
6306         if (IsFastCall)
6307           ComputePtrOff();
6308 
6309         assert(HasParameterArea &&
6310                "Parameter area must exist to pass an argument in memory.");
6311         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6312                          true, CFlags.IsTailCall, false, MemOpChains,
6313                          TailCallArguments, dl);
6314         if (IsFastCall)
6315           ArgOffset += PtrByteSize;
6316       }
6317       if (!IsFastCall)
6318         ArgOffset += PtrByteSize;
6319       break;
6320     case MVT::f32:
6321     case MVT::f64: {
6322       // These can be scalar arguments or elements of a float array type
6323       // passed directly.  The latter are used to implement ELFv2 homogenous
6324       // float aggregates.
6325 
6326       // Named arguments go into FPRs first, and once they overflow, the
6327       // remaining arguments go into GPRs and then the parameter save area.
6328       // Unnamed arguments for vararg functions always go to GPRs and
6329       // then the parameter save area.  For now, put all arguments to vararg
6330       // routines always in both locations (FPR *and* GPR or stack slot).
6331       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6332       bool NeededLoad = false;
6333 
6334       // First load the argument into the next available FPR.
6335       if (FPR_idx != NumFPRs)
6336         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6337 
6338       // Next, load the argument into GPR or stack slot if needed.
6339       if (!NeedGPROrStack)
6340         ;
6341       else if (GPR_idx != NumGPRs && !IsFastCall) {
6342         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6343         // once we support fp <-> gpr moves.
6344 
6345         // In the non-vararg case, this can only ever happen in the
6346         // presence of f32 array types, since otherwise we never run
6347         // out of FPRs before running out of GPRs.
6348         SDValue ArgVal;
6349 
6350         // Double values are always passed in a single GPR.
6351         if (Arg.getValueType() != MVT::f32) {
6352           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6353 
6354         // Non-array float values are extended and passed in a GPR.
6355         } else if (!Flags.isInConsecutiveRegs()) {
6356           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6357           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6358 
6359         // If we have an array of floats, we collect every odd element
6360         // together with its predecessor into one GPR.
6361         } else if (ArgOffset % PtrByteSize != 0) {
6362           SDValue Lo, Hi;
6363           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6364           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6365           if (!isLittleEndian)
6366             std::swap(Lo, Hi);
6367           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6368 
6369         // The final element, if even, goes into the first half of a GPR.
6370         } else if (Flags.isInConsecutiveRegsLast()) {
6371           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6372           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6373           if (!isLittleEndian)
6374             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6375                                  DAG.getConstant(32, dl, MVT::i32));
6376 
6377         // Non-final even elements are skipped; they will be handled
6378         // together the with subsequent argument on the next go-around.
6379         } else
6380           ArgVal = SDValue();
6381 
6382         if (ArgVal.getNode())
6383           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6384       } else {
6385         if (IsFastCall)
6386           ComputePtrOff();
6387 
6388         // Single-precision floating-point values are mapped to the
6389         // second (rightmost) word of the stack doubleword.
6390         if (Arg.getValueType() == MVT::f32 &&
6391             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6392           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6393           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6394         }
6395 
6396         assert(HasParameterArea &&
6397                "Parameter area must exist to pass an argument in memory.");
6398         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6399                          true, CFlags.IsTailCall, false, MemOpChains,
6400                          TailCallArguments, dl);
6401 
6402         NeededLoad = true;
6403       }
6404       // When passing an array of floats, the array occupies consecutive
6405       // space in the argument area; only round up to the next doubleword
6406       // at the end of the array.  Otherwise, each float takes 8 bytes.
6407       if (!IsFastCall || NeededLoad) {
6408         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6409                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6410         if (Flags.isInConsecutiveRegsLast())
6411           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6412       }
6413       break;
6414     }
6415     case MVT::v4f32:
6416     case MVT::v4i32:
6417     case MVT::v8i16:
6418     case MVT::v16i8:
6419     case MVT::v2f64:
6420     case MVT::v2i64:
6421     case MVT::v1i128:
6422     case MVT::f128:
6423       if (!Subtarget.hasQPX()) {
6424       // These can be scalar arguments or elements of a vector array type
6425       // passed directly.  The latter are used to implement ELFv2 homogenous
6426       // vector aggregates.
6427 
6428       // For a varargs call, named arguments go into VRs or on the stack as
6429       // usual; unnamed arguments always go to the stack or the corresponding
6430       // GPRs when within range.  For now, we always put the value in both
6431       // locations (or even all three).
6432       if (CFlags.IsVarArg) {
6433         assert(HasParameterArea &&
6434                "Parameter area must exist if we have a varargs call.");
6435         // We could elide this store in the case where the object fits
6436         // entirely in R registers.  Maybe later.
6437         SDValue Store =
6438             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6439         MemOpChains.push_back(Store);
6440         if (VR_idx != NumVRs) {
6441           SDValue Load =
6442               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6443           MemOpChains.push_back(Load.getValue(1));
6444           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6445         }
6446         ArgOffset += 16;
6447         for (unsigned i=0; i<16; i+=PtrByteSize) {
6448           if (GPR_idx == NumGPRs)
6449             break;
6450           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6451                                    DAG.getConstant(i, dl, PtrVT));
6452           SDValue Load =
6453               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6454           MemOpChains.push_back(Load.getValue(1));
6455           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6456         }
6457         break;
6458       }
6459 
6460       // Non-varargs Altivec params go into VRs or on the stack.
6461       if (VR_idx != NumVRs) {
6462         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6463       } else {
6464         if (IsFastCall)
6465           ComputePtrOff();
6466 
6467         assert(HasParameterArea &&
6468                "Parameter area must exist to pass an argument in memory.");
6469         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6470                          true, CFlags.IsTailCall, true, MemOpChains,
6471                          TailCallArguments, dl);
6472         if (IsFastCall)
6473           ArgOffset += 16;
6474       }
6475 
6476       if (!IsFastCall)
6477         ArgOffset += 16;
6478       break;
6479       } // not QPX
6480 
6481       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6482              "Invalid QPX parameter type");
6483 
6484       LLVM_FALLTHROUGH;
6485     case MVT::v4f64:
6486     case MVT::v4i1: {
6487       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6488       if (CFlags.IsVarArg) {
6489         assert(HasParameterArea &&
6490                "Parameter area must exist if we have a varargs call.");
6491         // We could elide this store in the case where the object fits
6492         // entirely in R registers.  Maybe later.
6493         SDValue Store =
6494             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6495         MemOpChains.push_back(Store);
6496         if (QFPR_idx != NumQFPRs) {
6497           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6498                                      PtrOff, MachinePointerInfo());
6499           MemOpChains.push_back(Load.getValue(1));
6500           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6501         }
6502         ArgOffset += (IsF32 ? 16 : 32);
6503         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6504           if (GPR_idx == NumGPRs)
6505             break;
6506           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6507                                    DAG.getConstant(i, dl, PtrVT));
6508           SDValue Load =
6509               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6510           MemOpChains.push_back(Load.getValue(1));
6511           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6512         }
6513         break;
6514       }
6515 
6516       // Non-varargs QPX params go into registers or on the stack.
6517       if (QFPR_idx != NumQFPRs) {
6518         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6519       } else {
6520         if (IsFastCall)
6521           ComputePtrOff();
6522 
6523         assert(HasParameterArea &&
6524                "Parameter area must exist to pass an argument in memory.");
6525         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6526                          true, CFlags.IsTailCall, true, MemOpChains,
6527                          TailCallArguments, dl);
6528         if (IsFastCall)
6529           ArgOffset += (IsF32 ? 16 : 32);
6530       }
6531 
6532       if (!IsFastCall)
6533         ArgOffset += (IsF32 ? 16 : 32);
6534       break;
6535       }
6536     }
6537   }
6538 
6539   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6540          "mismatch in size of parameter area");
6541   (void)NumBytesActuallyUsed;
6542 
6543   if (!MemOpChains.empty())
6544     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6545 
6546   // Check if this is an indirect call (MTCTR/BCTRL).
6547   // See prepareDescriptorIndirectCall and buildCallOperands for more
6548   // information about calls through function pointers in the 64-bit SVR4 ABI.
6549   if (CFlags.IsIndirect) {
6550     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6551     // caller in the TOC save area.
6552     if (isTOCSaveRestoreRequired(Subtarget)) {
6553       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6554       // Load r2 into a virtual register and store it to the TOC save area.
6555       setUsesTOCBasePtr(DAG);
6556       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6557       // TOC save area offset.
6558       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6559       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6560       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6561       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6562                            MachinePointerInfo::getStack(
6563                                DAG.getMachineFunction(), TOCSaveOffset));
6564     }
6565     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6566     // This does not mean the MTCTR instruction must use R12; it's easier
6567     // to model this as an extra parameter, so do that.
6568     if (isELFv2ABI && !CFlags.IsPatchPoint)
6569       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6570   }
6571 
6572   // Build a sequence of copy-to-reg nodes chained together with token chain
6573   // and flag operands which copy the outgoing args into the appropriate regs.
6574   SDValue InFlag;
6575   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6576     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6577                              RegsToPass[i].second, InFlag);
6578     InFlag = Chain.getValue(1);
6579   }
6580 
6581   if (CFlags.IsTailCall && !IsSibCall)
6582     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6583                     TailCallArguments);
6584 
6585   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6586                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6587 }
6588 
6589 SDValue PPCTargetLowering::LowerCall_Darwin(
6590     SDValue Chain, SDValue Callee, CallFlags CFlags,
6591     const SmallVectorImpl<ISD::OutputArg> &Outs,
6592     const SmallVectorImpl<SDValue> &OutVals,
6593     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6594     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6595     const CallBase *CB) const {
6596   unsigned NumOps = Outs.size();
6597 
6598   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6599   bool isPPC64 = PtrVT == MVT::i64;
6600   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6601 
6602   MachineFunction &MF = DAG.getMachineFunction();
6603 
6604   // Mark this function as potentially containing a function that contains a
6605   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6606   // and restoring the callers stack pointer in this functions epilog. This is
6607   // done because by tail calling the called function might overwrite the value
6608   // in this function's (MF) stack pointer stack slot 0(SP).
6609   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6610       CFlags.CallConv == CallingConv::Fast)
6611     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6612 
6613   // Count how many bytes are to be pushed on the stack, including the linkage
6614   // area, and parameter passing area.  We start with 24/48 bytes, which is
6615   // prereserved space for [SP][CR][LR][3 x unused].
6616   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6617   unsigned NumBytes = LinkageSize;
6618 
6619   // Add up all the space actually used.
6620   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6621   // they all go in registers, but we must reserve stack space for them for
6622   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6623   // assigned stack space in order, with padding so Altivec parameters are
6624   // 16-byte aligned.
6625   unsigned nAltivecParamsAtEnd = 0;
6626   for (unsigned i = 0; i != NumOps; ++i) {
6627     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6628     EVT ArgVT = Outs[i].VT;
6629     // Varargs Altivec parameters are padded to a 16 byte boundary.
6630     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6631         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6632         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6633       if (!CFlags.IsVarArg && !isPPC64) {
6634         // Non-varargs Altivec parameters go after all the non-Altivec
6635         // parameters; handle those later so we know how much padding we need.
6636         nAltivecParamsAtEnd++;
6637         continue;
6638       }
6639       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6640       NumBytes = ((NumBytes+15)/16)*16;
6641     }
6642     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6643   }
6644 
6645   // Allow for Altivec parameters at the end, if needed.
6646   if (nAltivecParamsAtEnd) {
6647     NumBytes = ((NumBytes+15)/16)*16;
6648     NumBytes += 16*nAltivecParamsAtEnd;
6649   }
6650 
6651   // The prolog code of the callee may store up to 8 GPR argument registers to
6652   // the stack, allowing va_start to index over them in memory if its varargs.
6653   // Because we cannot tell if this is needed on the caller side, we have to
6654   // conservatively assume that it is needed.  As such, make sure we have at
6655   // least enough stack space for the caller to store the 8 GPRs.
6656   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6657 
6658   // Tail call needs the stack to be aligned.
6659   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6660       CFlags.CallConv == CallingConv::Fast)
6661     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6662 
6663   // Calculate by how many bytes the stack has to be adjusted in case of tail
6664   // call optimization.
6665   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6666 
6667   // To protect arguments on the stack from being clobbered in a tail call,
6668   // force all the loads to happen before doing any other lowering.
6669   if (CFlags.IsTailCall)
6670     Chain = DAG.getStackArgumentTokenFactor(Chain);
6671 
6672   // Adjust the stack pointer for the new arguments...
6673   // These operations are automatically eliminated by the prolog/epilog pass
6674   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6675   SDValue CallSeqStart = Chain;
6676 
6677   // Load the return address and frame pointer so it can be move somewhere else
6678   // later.
6679   SDValue LROp, FPOp;
6680   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6681 
6682   // Set up a copy of the stack pointer for use loading and storing any
6683   // arguments that may not fit in the registers available for argument
6684   // passing.
6685   SDValue StackPtr;
6686   if (isPPC64)
6687     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6688   else
6689     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6690 
6691   // Figure out which arguments are going to go in registers, and which in
6692   // memory.  Also, if this is a vararg function, floating point operations
6693   // must be stored to our stack, and loaded into integer regs as well, if
6694   // any integer regs are available for argument passing.
6695   unsigned ArgOffset = LinkageSize;
6696   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6697 
6698   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6699     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6700     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6701   };
6702   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6703     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6704     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6705   };
6706   static const MCPhysReg VR[] = {
6707     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6708     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6709   };
6710   const unsigned NumGPRs = array_lengthof(GPR_32);
6711   const unsigned NumFPRs = 13;
6712   const unsigned NumVRs  = array_lengthof(VR);
6713 
6714   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6715 
6716   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6717   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6718 
6719   SmallVector<SDValue, 8> MemOpChains;
6720   for (unsigned i = 0; i != NumOps; ++i) {
6721     SDValue Arg = OutVals[i];
6722     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6723 
6724     // PtrOff will be used to store the current argument to the stack if a
6725     // register cannot be found for it.
6726     SDValue PtrOff;
6727 
6728     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6729 
6730     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6731 
6732     // On PPC64, promote integers to 64-bit values.
6733     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6734       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6735       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6736       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6737     }
6738 
6739     // FIXME memcpy is used way more than necessary.  Correctness first.
6740     // Note: "by value" is code for passing a structure by value, not
6741     // basic types.
6742     if (Flags.isByVal()) {
6743       unsigned Size = Flags.getByValSize();
6744       // Very small objects are passed right-justified.  Everything else is
6745       // passed left-justified.
6746       if (Size==1 || Size==2) {
6747         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6748         if (GPR_idx != NumGPRs) {
6749           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6750                                         MachinePointerInfo(), VT);
6751           MemOpChains.push_back(Load.getValue(1));
6752           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6753 
6754           ArgOffset += PtrByteSize;
6755         } else {
6756           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6757                                           PtrOff.getValueType());
6758           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6759           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6760                                                             CallSeqStart,
6761                                                             Flags, DAG, dl);
6762           ArgOffset += PtrByteSize;
6763         }
6764         continue;
6765       }
6766       // Copy entire object into memory.  There are cases where gcc-generated
6767       // code assumes it is there, even if it could be put entirely into
6768       // registers.  (This is not what the doc says.)
6769       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6770                                                         CallSeqStart,
6771                                                         Flags, DAG, dl);
6772 
6773       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6774       // copy the pieces of the object that fit into registers from the
6775       // parameter save area.
6776       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6777         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6778         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6779         if (GPR_idx != NumGPRs) {
6780           SDValue Load =
6781               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6782           MemOpChains.push_back(Load.getValue(1));
6783           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6784           ArgOffset += PtrByteSize;
6785         } else {
6786           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6787           break;
6788         }
6789       }
6790       continue;
6791     }
6792 
6793     switch (Arg.getSimpleValueType().SimpleTy) {
6794     default: llvm_unreachable("Unexpected ValueType for argument!");
6795     case MVT::i1:
6796     case MVT::i32:
6797     case MVT::i64:
6798       if (GPR_idx != NumGPRs) {
6799         if (Arg.getValueType() == MVT::i1)
6800           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6801 
6802         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6803       } else {
6804         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6805                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6806                          TailCallArguments, dl);
6807       }
6808       ArgOffset += PtrByteSize;
6809       break;
6810     case MVT::f32:
6811     case MVT::f64:
6812       if (FPR_idx != NumFPRs) {
6813         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6814 
6815         if (CFlags.IsVarArg) {
6816           SDValue Store =
6817               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6818           MemOpChains.push_back(Store);
6819 
6820           // Float varargs are always shadowed in available integer registers
6821           if (GPR_idx != NumGPRs) {
6822             SDValue Load =
6823                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6824             MemOpChains.push_back(Load.getValue(1));
6825             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6826           }
6827           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6828             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6829             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6830             SDValue Load =
6831                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6832             MemOpChains.push_back(Load.getValue(1));
6833             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6834           }
6835         } else {
6836           // If we have any FPRs remaining, we may also have GPRs remaining.
6837           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6838           // GPRs.
6839           if (GPR_idx != NumGPRs)
6840             ++GPR_idx;
6841           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6842               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6843             ++GPR_idx;
6844         }
6845       } else
6846         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6847                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6848                          TailCallArguments, dl);
6849       if (isPPC64)
6850         ArgOffset += 8;
6851       else
6852         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6853       break;
6854     case MVT::v4f32:
6855     case MVT::v4i32:
6856     case MVT::v8i16:
6857     case MVT::v16i8:
6858       if (CFlags.IsVarArg) {
6859         // These go aligned on the stack, or in the corresponding R registers
6860         // when within range.  The Darwin PPC ABI doc claims they also go in
6861         // V registers; in fact gcc does this only for arguments that are
6862         // prototyped, not for those that match the ...  We do it for all
6863         // arguments, seems to work.
6864         while (ArgOffset % 16 !=0) {
6865           ArgOffset += PtrByteSize;
6866           if (GPR_idx != NumGPRs)
6867             GPR_idx++;
6868         }
6869         // We could elide this store in the case where the object fits
6870         // entirely in R registers.  Maybe later.
6871         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6872                              DAG.getConstant(ArgOffset, dl, PtrVT));
6873         SDValue Store =
6874             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6875         MemOpChains.push_back(Store);
6876         if (VR_idx != NumVRs) {
6877           SDValue Load =
6878               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6879           MemOpChains.push_back(Load.getValue(1));
6880           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6881         }
6882         ArgOffset += 16;
6883         for (unsigned i=0; i<16; i+=PtrByteSize) {
6884           if (GPR_idx == NumGPRs)
6885             break;
6886           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6887                                    DAG.getConstant(i, dl, PtrVT));
6888           SDValue Load =
6889               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6890           MemOpChains.push_back(Load.getValue(1));
6891           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6892         }
6893         break;
6894       }
6895 
6896       // Non-varargs Altivec params generally go in registers, but have
6897       // stack space allocated at the end.
6898       if (VR_idx != NumVRs) {
6899         // Doesn't have GPR space allocated.
6900         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6901       } else if (nAltivecParamsAtEnd==0) {
6902         // We are emitting Altivec params in order.
6903         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6904                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6905                          TailCallArguments, dl);
6906         ArgOffset += 16;
6907       }
6908       break;
6909     }
6910   }
6911   // If all Altivec parameters fit in registers, as they usually do,
6912   // they get stack space following the non-Altivec parameters.  We
6913   // don't track this here because nobody below needs it.
6914   // If there are more Altivec parameters than fit in registers emit
6915   // the stores here.
6916   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6917     unsigned j = 0;
6918     // Offset is aligned; skip 1st 12 params which go in V registers.
6919     ArgOffset = ((ArgOffset+15)/16)*16;
6920     ArgOffset += 12*16;
6921     for (unsigned i = 0; i != NumOps; ++i) {
6922       SDValue Arg = OutVals[i];
6923       EVT ArgType = Outs[i].VT;
6924       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6925           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6926         if (++j > NumVRs) {
6927           SDValue PtrOff;
6928           // We are emitting Altivec params in order.
6929           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6930                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6931                            TailCallArguments, dl);
6932           ArgOffset += 16;
6933         }
6934       }
6935     }
6936   }
6937 
6938   if (!MemOpChains.empty())
6939     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6940 
6941   // On Darwin, R12 must contain the address of an indirect callee.  This does
6942   // not mean the MTCTR instruction must use R12; it's easier to model this as
6943   // an extra parameter, so do that.
6944   if (CFlags.IsIndirect) {
6945     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6946     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6947                                                    PPC::R12), Callee));
6948   }
6949 
6950   // Build a sequence of copy-to-reg nodes chained together with token chain
6951   // and flag operands which copy the outgoing args into the appropriate regs.
6952   SDValue InFlag;
6953   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6954     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6955                              RegsToPass[i].second, InFlag);
6956     InFlag = Chain.getValue(1);
6957   }
6958 
6959   if (CFlags.IsTailCall)
6960     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6961                     TailCallArguments);
6962 
6963   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6964                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6965 }
6966 
6967 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6968                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6969                    CCState &State) {
6970 
6971   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6972       State.getMachineFunction().getSubtarget());
6973   const bool IsPPC64 = Subtarget.isPPC64();
6974   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6975   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6976 
6977   assert((!ValVT.isInteger() ||
6978           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6979          "Integer argument exceeds register size: should have been legalized");
6980 
6981   if (ValVT == MVT::f128)
6982     report_fatal_error("f128 is unimplemented on AIX.");
6983 
6984   if (ArgFlags.isNest())
6985     report_fatal_error("Nest arguments are unimplemented.");
6986 
6987   if (ValVT.isVector() || LocVT.isVector())
6988     report_fatal_error("Vector arguments are unimplemented on AIX.");
6989 
6990   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6991                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6992                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6993   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6994                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6995                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6996 
6997   if (ArgFlags.isByVal()) {
6998     if (ArgFlags.getNonZeroByValAlign() > PtrByteSize)
6999       report_fatal_error("Pass-by-value arguments with alignment greater than "
7000                          "register width are not supported.");
7001 
7002     const unsigned ByValSize = ArgFlags.getByValSize();
7003 
7004     // An empty aggregate parameter takes up no storage and no registers,
7005     // but needs a MemLoc for a stack slot for the formal arguments side.
7006     if (ByValSize == 0) {
7007       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7008                                        State.getNextStackOffset(), RegVT,
7009                                        LocInfo));
7010       return false;
7011     }
7012 
7013     const unsigned StackSize = alignTo(ByValSize, PtrByteSize);
7014     unsigned Offset = State.AllocateStack(StackSize, PtrByteSize);
7015     for (const unsigned E = Offset + StackSize; Offset < E;
7016          Offset += PtrByteSize) {
7017       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7018         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7019       else {
7020         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7021                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7022                                          LocInfo));
7023         break;
7024       }
7025     }
7026     return false;
7027   }
7028 
7029   // Arguments always reserve parameter save area.
7030   switch (ValVT.SimpleTy) {
7031   default:
7032     report_fatal_error("Unhandled value type for argument.");
7033   case MVT::i64:
7034     // i64 arguments should have been split to i32 for PPC32.
7035     assert(IsPPC64 && "PPC32 should have split i64 values.");
7036     LLVM_FALLTHROUGH;
7037   case MVT::i1:
7038   case MVT::i32: {
7039     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
7040     // AIX integer arguments are always passed in register width.
7041     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
7042       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7043                                   : CCValAssign::LocInfo::ZExt;
7044     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7045       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7046     else
7047       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7048 
7049     return false;
7050   }
7051   case MVT::f32:
7052   case MVT::f64: {
7053     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7054     const unsigned StoreSize = LocVT.getStoreSize();
7055     // Floats are always 4-byte aligned in the PSA on AIX.
7056     // This includes f64 in 64-bit mode for ABI compatibility.
7057     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
7058     unsigned FReg = State.AllocateReg(FPR);
7059     if (FReg)
7060       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7061 
7062     // Reserve and initialize GPRs or initialize the PSA as required.
7063     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
7064       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7065         assert(FReg && "An FPR should be available when a GPR is reserved.");
7066         if (State.isVarArg()) {
7067           // Successfully reserved GPRs are only initialized for vararg calls.
7068           // Custom handling is required for:
7069           //   f64 in PPC32 needs to be split into 2 GPRs.
7070           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7071           State.addLoc(
7072               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7073         }
7074       } else {
7075         // If there are insufficient GPRs, the PSA needs to be initialized.
7076         // Initialization occurs even if an FPR was initialized for
7077         // compatibility with the AIX XL compiler. The full memory for the
7078         // argument will be initialized even if a prior word is saved in GPR.
7079         // A custom memLoc is used when the argument also passes in FPR so
7080         // that the callee handling can skip over it easily.
7081         State.addLoc(
7082             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7083                                              LocInfo)
7084                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7085         break;
7086       }
7087     }
7088 
7089     return false;
7090   }
7091   }
7092   return true;
7093 }
7094 
7095 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7096                                                     bool IsPPC64) {
7097   assert((IsPPC64 || SVT != MVT::i64) &&
7098          "i64 should have been split for 32-bit codegen.");
7099 
7100   switch (SVT) {
7101   default:
7102     report_fatal_error("Unexpected value type for formal argument");
7103   case MVT::i1:
7104   case MVT::i32:
7105   case MVT::i64:
7106     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7107   case MVT::f32:
7108     return &PPC::F4RCRegClass;
7109   case MVT::f64:
7110     return &PPC::F8RCRegClass;
7111   }
7112 }
7113 
7114 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7115                                         SelectionDAG &DAG, SDValue ArgValue,
7116                                         MVT LocVT, const SDLoc &dl) {
7117   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7118   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7119 
7120   if (Flags.isSExt())
7121     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7122                            DAG.getValueType(ValVT));
7123   else if (Flags.isZExt())
7124     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7125                            DAG.getValueType(ValVT));
7126 
7127   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7128 }
7129 
7130 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7131   const unsigned LASize = FL->getLinkageSize();
7132 
7133   if (PPC::GPRCRegClass.contains(Reg)) {
7134     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7135            "Reg must be a valid argument register!");
7136     return LASize + 4 * (Reg - PPC::R3);
7137   }
7138 
7139   if (PPC::G8RCRegClass.contains(Reg)) {
7140     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7141            "Reg must be a valid argument register!");
7142     return LASize + 8 * (Reg - PPC::X3);
7143   }
7144 
7145   llvm_unreachable("Only general purpose registers expected.");
7146 }
7147 
7148 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7149     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7150     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7151     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7152 
7153   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7154           CallConv == CallingConv::Fast) &&
7155          "Unexpected calling convention!");
7156 
7157   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7158     report_fatal_error("Tail call support is unimplemented on AIX.");
7159 
7160   if (useSoftFloat())
7161     report_fatal_error("Soft float support is unimplemented on AIX.");
7162 
7163   const PPCSubtarget &Subtarget =
7164       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7165   if (Subtarget.hasQPX())
7166     report_fatal_error("QPX support is not supported on AIX.");
7167 
7168   const bool IsPPC64 = Subtarget.isPPC64();
7169   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7170 
7171   // Assign locations to all of the incoming arguments.
7172   SmallVector<CCValAssign, 16> ArgLocs;
7173   MachineFunction &MF = DAG.getMachineFunction();
7174   MachineFrameInfo &MFI = MF.getFrameInfo();
7175   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7176 
7177   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7178   // Reserve space for the linkage area on the stack.
7179   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7180   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7181   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7182 
7183   SmallVector<SDValue, 8> MemOps;
7184 
7185   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7186     CCValAssign &VA = ArgLocs[I++];
7187     MVT LocVT = VA.getLocVT();
7188     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7189 
7190     // For compatibility with the AIX XL compiler, the float args in the
7191     // parameter save area are initialized even if the argument is available
7192     // in register.  The caller is required to initialize both the register
7193     // and memory, however, the callee can choose to expect it in either.
7194     // The memloc is dismissed here because the argument is retrieved from
7195     // the register.
7196     if (VA.isMemLoc() && VA.needsCustom())
7197       continue;
7198 
7199     if (Flags.isByVal() && VA.isMemLoc()) {
7200       const unsigned Size =
7201           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7202                   PtrByteSize);
7203       const int FI = MF.getFrameInfo().CreateFixedObject(
7204           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7205           /* IsAliased */ true);
7206       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7207       InVals.push_back(FIN);
7208 
7209       continue;
7210     }
7211 
7212     if (Flags.isByVal()) {
7213       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7214 
7215       const MCPhysReg ArgReg = VA.getLocReg();
7216       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7217 
7218       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7219         report_fatal_error("Over aligned byvals not supported yet.");
7220 
7221       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7222       const int FI = MF.getFrameInfo().CreateFixedObject(
7223           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7224           /* IsAliased */ true);
7225       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7226       InVals.push_back(FIN);
7227 
7228       // Add live ins for all the RegLocs for the same ByVal.
7229       const TargetRegisterClass *RegClass =
7230           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7231 
7232       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7233                                                unsigned Offset) {
7234         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7235         // Since the callers side has left justified the aggregate in the
7236         // register, we can simply store the entire register into the stack
7237         // slot.
7238         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7239         // The store to the fixedstack object is needed becuase accessing a
7240         // field of the ByVal will use a gep and load. Ideally we will optimize
7241         // to extracting the value from the register directly, and elide the
7242         // stores when the arguments address is not taken, but that will need to
7243         // be future work.
7244         SDValue Store =
7245             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7246                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7247                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7248 
7249         MemOps.push_back(Store);
7250       };
7251 
7252       unsigned Offset = 0;
7253       HandleRegLoc(VA.getLocReg(), Offset);
7254       Offset += PtrByteSize;
7255       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7256            Offset += PtrByteSize) {
7257         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7258                "RegLocs should be for ByVal argument.");
7259 
7260         const CCValAssign RL = ArgLocs[I++];
7261         HandleRegLoc(RL.getLocReg(), Offset);
7262       }
7263 
7264       if (Offset != StackSize) {
7265         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7266                "Expected MemLoc for remaining bytes.");
7267         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7268         // Consume the MemLoc.The InVal has already been emitted, so nothing
7269         // more needs to be done.
7270         ++I;
7271       }
7272 
7273       continue;
7274     }
7275 
7276     EVT ValVT = VA.getValVT();
7277     if (VA.isRegLoc() && !VA.needsCustom()) {
7278       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7279       unsigned VReg =
7280           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7281       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7282       if (ValVT.isScalarInteger() &&
7283           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7284         ArgValue =
7285             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7286       }
7287       InVals.push_back(ArgValue);
7288       continue;
7289     }
7290     if (VA.isMemLoc()) {
7291       const unsigned LocSize = LocVT.getStoreSize();
7292       const unsigned ValSize = ValVT.getStoreSize();
7293       assert((ValSize <= LocSize) &&
7294              "Object size is larger than size of MemLoc");
7295       int CurArgOffset = VA.getLocMemOffset();
7296       // Objects are right-justified because AIX is big-endian.
7297       if (LocSize > ValSize)
7298         CurArgOffset += LocSize - ValSize;
7299       // Potential tail calls could cause overwriting of argument stack slots.
7300       const bool IsImmutable =
7301           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7302             (CallConv == CallingConv::Fast));
7303       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7304       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7305       SDValue ArgValue =
7306           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7307       InVals.push_back(ArgValue);
7308       continue;
7309     }
7310   }
7311 
7312   // On AIX a minimum of 8 words is saved to the parameter save area.
7313   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7314   // Area that is at least reserved in the caller of this function.
7315   unsigned CallerReservedArea =
7316       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7317 
7318   // Set the size that is at least reserved in caller of this function. Tail
7319   // call optimized function's reserved stack space needs to be aligned so
7320   // that taking the difference between two stack areas will result in an
7321   // aligned stack.
7322   CallerReservedArea =
7323       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7324   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7325   FuncInfo->setMinReservedArea(CallerReservedArea);
7326 
7327   if (isVarArg) {
7328     FuncInfo->setVarArgsFrameIndex(
7329         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7330     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7331 
7332     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7333                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7334 
7335     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7336                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7337     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7338 
7339     // The fixed integer arguments of a variadic function are stored to the
7340     // VarArgsFrameIndex on the stack so that they may be loaded by
7341     // dereferencing the result of va_next.
7342     for (unsigned GPRIndex =
7343              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7344          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7345 
7346       const unsigned VReg =
7347           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7348                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7349 
7350       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7351       SDValue Store =
7352           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7353       MemOps.push_back(Store);
7354       // Increment the address for the next argument to store.
7355       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7356       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7357     }
7358   }
7359 
7360   if (!MemOps.empty())
7361     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7362 
7363   return Chain;
7364 }
7365 
7366 SDValue PPCTargetLowering::LowerCall_AIX(
7367     SDValue Chain, SDValue Callee, CallFlags CFlags,
7368     const SmallVectorImpl<ISD::OutputArg> &Outs,
7369     const SmallVectorImpl<SDValue> &OutVals,
7370     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7371     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7372     const CallBase *CB) const {
7373 
7374   assert((CFlags.CallConv == CallingConv::C ||
7375           CFlags.CallConv == CallingConv::Cold ||
7376           CFlags.CallConv == CallingConv::Fast) &&
7377          "Unexpected calling convention!");
7378 
7379   if (CFlags.IsPatchPoint)
7380     report_fatal_error("This call type is unimplemented on AIX.");
7381 
7382   const PPCSubtarget& Subtarget =
7383       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7384   if (Subtarget.hasQPX())
7385     report_fatal_error("QPX is not supported on AIX.");
7386   if (Subtarget.hasAltivec())
7387     report_fatal_error("Altivec support is unimplemented on AIX.");
7388 
7389   MachineFunction &MF = DAG.getMachineFunction();
7390   SmallVector<CCValAssign, 16> ArgLocs;
7391   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7392                  *DAG.getContext());
7393 
7394   // Reserve space for the linkage save area (LSA) on the stack.
7395   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7396   //   [SP][CR][LR][2 x reserved][TOC].
7397   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7398   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7399   const bool IsPPC64 = Subtarget.isPPC64();
7400   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7401   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7402   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7403   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7404 
7405   // The prolog code of the callee may store up to 8 GPR argument registers to
7406   // the stack, allowing va_start to index over them in memory if the callee
7407   // is variadic.
7408   // Because we cannot tell if this is needed on the caller side, we have to
7409   // conservatively assume that it is needed.  As such, make sure we have at
7410   // least enough stack space for the caller to store the 8 GPRs.
7411   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7412   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7413                                      CCInfo.getNextStackOffset());
7414 
7415   // Adjust the stack pointer for the new arguments...
7416   // These operations are automatically eliminated by the prolog/epilog pass.
7417   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7418   SDValue CallSeqStart = Chain;
7419 
7420   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7421   SmallVector<SDValue, 8> MemOpChains;
7422 
7423   // Set up a copy of the stack pointer for loading and storing any
7424   // arguments that may not fit in the registers available for argument
7425   // passing.
7426   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7427                                    : DAG.getRegister(PPC::R1, MVT::i32);
7428 
7429   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7430     const unsigned ValNo = ArgLocs[I].getValNo();
7431     SDValue Arg = OutVals[ValNo];
7432     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7433 
7434     if (Flags.isByVal()) {
7435       const unsigned ByValSize = Flags.getByValSize();
7436 
7437       // Nothing to do for zero-sized ByVals on the caller side.
7438       if (!ByValSize) {
7439         ++I;
7440         continue;
7441       }
7442 
7443       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7444         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7445                               (LoadOffset != 0)
7446                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7447                                   : Arg,
7448                               MachinePointerInfo(), VT);
7449       };
7450 
7451       unsigned LoadOffset = 0;
7452 
7453       // Initialize registers, which are fully occupied by the by-val argument.
7454       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7455         SDValue Load = GetLoad(PtrVT, LoadOffset);
7456         MemOpChains.push_back(Load.getValue(1));
7457         LoadOffset += PtrByteSize;
7458         const CCValAssign &ByValVA = ArgLocs[I++];
7459         assert(ByValVA.getValNo() == ValNo &&
7460                "Unexpected location for pass-by-value argument.");
7461         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7462       }
7463 
7464       if (LoadOffset == ByValSize)
7465         continue;
7466 
7467       // There must be one more loc to handle the remainder.
7468       assert(ArgLocs[I].getValNo() == ValNo &&
7469              "Expected additional location for by-value argument.");
7470 
7471       if (ArgLocs[I].isMemLoc()) {
7472         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7473         const CCValAssign &ByValVA = ArgLocs[I++];
7474         ISD::ArgFlagsTy MemcpyFlags = Flags;
7475         // Only memcpy the bytes that don't pass in register.
7476         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7477         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7478             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7479                               : Arg,
7480             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7481             CallSeqStart, MemcpyFlags, DAG, dl);
7482         continue;
7483       }
7484 
7485       // Initialize the final register residue.
7486       // Any residue that occupies the final by-val arg register must be
7487       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7488       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7489       // 2 and 1 byte loads.
7490       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7491       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7492              "Unexpected register residue for by-value argument.");
7493       SDValue ResidueVal;
7494       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7495         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7496         const MVT VT =
7497             N == 1 ? MVT::i8
7498                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7499         SDValue Load = GetLoad(VT, LoadOffset);
7500         MemOpChains.push_back(Load.getValue(1));
7501         LoadOffset += N;
7502         Bytes += N;
7503 
7504         // By-val arguments are passed left-justfied in register.
7505         // Every load here needs to be shifted, otherwise a full register load
7506         // should have been used.
7507         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7508                "Unexpected load emitted during handling of pass-by-value "
7509                "argument.");
7510         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7511         EVT ShiftAmountTy =
7512             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7513         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7514         SDValue ShiftedLoad =
7515             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7516         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7517                                               ShiftedLoad)
7518                                 : ShiftedLoad;
7519       }
7520 
7521       const CCValAssign &ByValVA = ArgLocs[I++];
7522       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7523       continue;
7524     }
7525 
7526     CCValAssign &VA = ArgLocs[I++];
7527     const MVT LocVT = VA.getLocVT();
7528     const MVT ValVT = VA.getValVT();
7529 
7530     switch (VA.getLocInfo()) {
7531     default:
7532       report_fatal_error("Unexpected argument extension type.");
7533     case CCValAssign::Full:
7534       break;
7535     case CCValAssign::ZExt:
7536       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7537       break;
7538     case CCValAssign::SExt:
7539       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7540       break;
7541     }
7542 
7543     if (VA.isRegLoc() && !VA.needsCustom()) {
7544       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7545       continue;
7546     }
7547 
7548     if (VA.isMemLoc()) {
7549       SDValue PtrOff =
7550           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7551       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7552       MemOpChains.push_back(
7553           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7554 
7555       continue;
7556     }
7557 
7558     // Custom handling is used for GPR initializations for vararg float
7559     // arguments.
7560     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7561            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7562            "Unexpected register handling for calling convention.");
7563 
7564     SDValue ArgAsInt =
7565         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7566 
7567     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7568       // f32 in 32-bit GPR
7569       // f64 in 64-bit GPR
7570       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7571     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7572       // f32 in 64-bit GPR.
7573       RegsToPass.push_back(std::make_pair(
7574           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7575     else {
7576       // f64 in two 32-bit GPRs
7577       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7578       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7579              "Unexpected custom register for argument!");
7580       CCValAssign &GPR1 = VA;
7581       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7582                                      DAG.getConstant(32, dl, MVT::i8));
7583       RegsToPass.push_back(std::make_pair(
7584           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7585 
7586       if (I != E) {
7587         // If only 1 GPR was available, there will only be one custom GPR and
7588         // the argument will also pass in memory.
7589         CCValAssign &PeekArg = ArgLocs[I];
7590         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7591           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7592           CCValAssign &GPR2 = ArgLocs[I++];
7593           RegsToPass.push_back(std::make_pair(
7594               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7595         }
7596       }
7597     }
7598   }
7599 
7600   if (!MemOpChains.empty())
7601     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7602 
7603   // For indirect calls, we need to save the TOC base to the stack for
7604   // restoration after the call.
7605   if (CFlags.IsIndirect) {
7606     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7607     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7608     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7609     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7610     const unsigned TOCSaveOffset =
7611         Subtarget.getFrameLowering()->getTOCSaveOffset();
7612 
7613     setUsesTOCBasePtr(DAG);
7614     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7615     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7616     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7617     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7618     Chain = DAG.getStore(
7619         Val.getValue(1), dl, Val, AddPtr,
7620         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7621   }
7622 
7623   // Build a sequence of copy-to-reg nodes chained together with token chain
7624   // and flag operands which copy the outgoing args into the appropriate regs.
7625   SDValue InFlag;
7626   for (auto Reg : RegsToPass) {
7627     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7628     InFlag = Chain.getValue(1);
7629   }
7630 
7631   const int SPDiff = 0;
7632   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7633                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7634 }
7635 
7636 bool
7637 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7638                                   MachineFunction &MF, bool isVarArg,
7639                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7640                                   LLVMContext &Context) const {
7641   SmallVector<CCValAssign, 16> RVLocs;
7642   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7643   return CCInfo.CheckReturn(
7644       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7645                 ? RetCC_PPC_Cold
7646                 : RetCC_PPC);
7647 }
7648 
7649 SDValue
7650 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7651                                bool isVarArg,
7652                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7653                                const SmallVectorImpl<SDValue> &OutVals,
7654                                const SDLoc &dl, SelectionDAG &DAG) const {
7655   SmallVector<CCValAssign, 16> RVLocs;
7656   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7657                  *DAG.getContext());
7658   CCInfo.AnalyzeReturn(Outs,
7659                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7660                            ? RetCC_PPC_Cold
7661                            : RetCC_PPC);
7662 
7663   SDValue Flag;
7664   SmallVector<SDValue, 4> RetOps(1, Chain);
7665 
7666   // Copy the result values into the output registers.
7667   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7668     CCValAssign &VA = RVLocs[i];
7669     assert(VA.isRegLoc() && "Can only return in registers!");
7670 
7671     SDValue Arg = OutVals[RealResIdx];
7672 
7673     switch (VA.getLocInfo()) {
7674     default: llvm_unreachable("Unknown loc info!");
7675     case CCValAssign::Full: break;
7676     case CCValAssign::AExt:
7677       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7678       break;
7679     case CCValAssign::ZExt:
7680       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7681       break;
7682     case CCValAssign::SExt:
7683       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7684       break;
7685     }
7686     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7687       bool isLittleEndian = Subtarget.isLittleEndian();
7688       // Legalize ret f64 -> ret 2 x i32.
7689       SDValue SVal =
7690           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7691                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7692       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7693       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7694       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7695                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7696       Flag = Chain.getValue(1);
7697       VA = RVLocs[++i]; // skip ahead to next loc
7698       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7699     } else
7700       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7701     Flag = Chain.getValue(1);
7702     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7703   }
7704 
7705   RetOps[0] = Chain;  // Update chain.
7706 
7707   // Add the flag if we have it.
7708   if (Flag.getNode())
7709     RetOps.push_back(Flag);
7710 
7711   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7712 }
7713 
7714 SDValue
7715 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7716                                                 SelectionDAG &DAG) const {
7717   SDLoc dl(Op);
7718 
7719   // Get the correct type for integers.
7720   EVT IntVT = Op.getValueType();
7721 
7722   // Get the inputs.
7723   SDValue Chain = Op.getOperand(0);
7724   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7725   // Build a DYNAREAOFFSET node.
7726   SDValue Ops[2] = {Chain, FPSIdx};
7727   SDVTList VTs = DAG.getVTList(IntVT);
7728   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7729 }
7730 
7731 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7732                                              SelectionDAG &DAG) const {
7733   // When we pop the dynamic allocation we need to restore the SP link.
7734   SDLoc dl(Op);
7735 
7736   // Get the correct type for pointers.
7737   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7738 
7739   // Construct the stack pointer operand.
7740   bool isPPC64 = Subtarget.isPPC64();
7741   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7742   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7743 
7744   // Get the operands for the STACKRESTORE.
7745   SDValue Chain = Op.getOperand(0);
7746   SDValue SaveSP = Op.getOperand(1);
7747 
7748   // Load the old link SP.
7749   SDValue LoadLinkSP =
7750       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7751 
7752   // Restore the stack pointer.
7753   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7754 
7755   // Store the old link SP.
7756   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7757 }
7758 
7759 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7760   MachineFunction &MF = DAG.getMachineFunction();
7761   bool isPPC64 = Subtarget.isPPC64();
7762   EVT PtrVT = getPointerTy(MF.getDataLayout());
7763 
7764   // Get current frame pointer save index.  The users of this index will be
7765   // primarily DYNALLOC instructions.
7766   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7767   int RASI = FI->getReturnAddrSaveIndex();
7768 
7769   // If the frame pointer save index hasn't been defined yet.
7770   if (!RASI) {
7771     // Find out what the fix offset of the frame pointer save area.
7772     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7773     // Allocate the frame index for frame pointer save area.
7774     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7775     // Save the result.
7776     FI->setReturnAddrSaveIndex(RASI);
7777   }
7778   return DAG.getFrameIndex(RASI, PtrVT);
7779 }
7780 
7781 SDValue
7782 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7783   MachineFunction &MF = DAG.getMachineFunction();
7784   bool isPPC64 = Subtarget.isPPC64();
7785   EVT PtrVT = getPointerTy(MF.getDataLayout());
7786 
7787   // Get current frame pointer save index.  The users of this index will be
7788   // primarily DYNALLOC instructions.
7789   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7790   int FPSI = FI->getFramePointerSaveIndex();
7791 
7792   // If the frame pointer save index hasn't been defined yet.
7793   if (!FPSI) {
7794     // Find out what the fix offset of the frame pointer save area.
7795     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7796     // Allocate the frame index for frame pointer save area.
7797     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7798     // Save the result.
7799     FI->setFramePointerSaveIndex(FPSI);
7800   }
7801   return DAG.getFrameIndex(FPSI, PtrVT);
7802 }
7803 
7804 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7805                                                    SelectionDAG &DAG) const {
7806   // Get the inputs.
7807   SDValue Chain = Op.getOperand(0);
7808   SDValue Size  = Op.getOperand(1);
7809   SDLoc dl(Op);
7810 
7811   // Get the correct type for pointers.
7812   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7813   // Negate the size.
7814   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7815                                 DAG.getConstant(0, dl, PtrVT), Size);
7816   // Construct a node for the frame pointer save index.
7817   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7818   // Build a DYNALLOC node.
7819   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7820   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7821   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7822 }
7823 
7824 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7825                                                      SelectionDAG &DAG) const {
7826   MachineFunction &MF = DAG.getMachineFunction();
7827 
7828   bool isPPC64 = Subtarget.isPPC64();
7829   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7830 
7831   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7832   return DAG.getFrameIndex(FI, PtrVT);
7833 }
7834 
7835 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7836                                                SelectionDAG &DAG) const {
7837   SDLoc DL(Op);
7838   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7839                      DAG.getVTList(MVT::i32, MVT::Other),
7840                      Op.getOperand(0), Op.getOperand(1));
7841 }
7842 
7843 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7844                                                 SelectionDAG &DAG) const {
7845   SDLoc DL(Op);
7846   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7847                      Op.getOperand(0), Op.getOperand(1));
7848 }
7849 
7850 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7851   if (Op.getValueType().isVector())
7852     return LowerVectorLoad(Op, DAG);
7853 
7854   assert(Op.getValueType() == MVT::i1 &&
7855          "Custom lowering only for i1 loads");
7856 
7857   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7858 
7859   SDLoc dl(Op);
7860   LoadSDNode *LD = cast<LoadSDNode>(Op);
7861 
7862   SDValue Chain = LD->getChain();
7863   SDValue BasePtr = LD->getBasePtr();
7864   MachineMemOperand *MMO = LD->getMemOperand();
7865 
7866   SDValue NewLD =
7867       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7868                      BasePtr, MVT::i8, MMO);
7869   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7870 
7871   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7872   return DAG.getMergeValues(Ops, dl);
7873 }
7874 
7875 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7876   if (Op.getOperand(1).getValueType().isVector())
7877     return LowerVectorStore(Op, DAG);
7878 
7879   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7880          "Custom lowering only for i1 stores");
7881 
7882   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7883 
7884   SDLoc dl(Op);
7885   StoreSDNode *ST = cast<StoreSDNode>(Op);
7886 
7887   SDValue Chain = ST->getChain();
7888   SDValue BasePtr = ST->getBasePtr();
7889   SDValue Value = ST->getValue();
7890   MachineMemOperand *MMO = ST->getMemOperand();
7891 
7892   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7893                       Value);
7894   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7895 }
7896 
7897 // FIXME: Remove this once the ANDI glue bug is fixed:
7898 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7899   assert(Op.getValueType() == MVT::i1 &&
7900          "Custom lowering only for i1 results");
7901 
7902   SDLoc DL(Op);
7903   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7904 }
7905 
7906 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7907                                                SelectionDAG &DAG) const {
7908 
7909   // Implements a vector truncate that fits in a vector register as a shuffle.
7910   // We want to legalize vector truncates down to where the source fits in
7911   // a vector register (and target is therefore smaller than vector register
7912   // size).  At that point legalization will try to custom lower the sub-legal
7913   // result and get here - where we can contain the truncate as a single target
7914   // operation.
7915 
7916   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7917   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7918   //
7919   // We will implement it for big-endian ordering as this (where x denotes
7920   // undefined):
7921   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7922   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7923   //
7924   // The same operation in little-endian ordering will be:
7925   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7926   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7927 
7928   assert(Op.getValueType().isVector() && "Vector type expected.");
7929 
7930   SDLoc DL(Op);
7931   SDValue N1 = Op.getOperand(0);
7932   unsigned SrcSize = N1.getValueType().getSizeInBits();
7933   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7934   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7935 
7936   EVT TrgVT = Op.getValueType();
7937   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7938   EVT EltVT = TrgVT.getVectorElementType();
7939   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7940   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7941 
7942   // First list the elements we want to keep.
7943   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7944   SmallVector<int, 16> ShuffV;
7945   if (Subtarget.isLittleEndian())
7946     for (unsigned i = 0; i < TrgNumElts; ++i)
7947       ShuffV.push_back(i * SizeMult);
7948   else
7949     for (unsigned i = 1; i <= TrgNumElts; ++i)
7950       ShuffV.push_back(i * SizeMult - 1);
7951 
7952   // Populate the remaining elements with undefs.
7953   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7954     // ShuffV.push_back(i + WideNumElts);
7955     ShuffV.push_back(WideNumElts + 1);
7956 
7957   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7958   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7959 }
7960 
7961 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7962 /// possible.
7963 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7964   // Not FP? Not a fsel.
7965   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7966       !Op.getOperand(2).getValueType().isFloatingPoint())
7967     return Op;
7968 
7969   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7970 
7971   EVT ResVT = Op.getValueType();
7972   EVT CmpVT = Op.getOperand(0).getValueType();
7973   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7974   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7975   SDLoc dl(Op);
7976   SDNodeFlags Flags = Op.getNode()->getFlags();
7977 
7978   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7979   // presence of infinities.
7980   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7981     switch (CC) {
7982     default:
7983       break;
7984     case ISD::SETOGT:
7985     case ISD::SETGT:
7986       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7987     case ISD::SETOLT:
7988     case ISD::SETLT:
7989       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7990     }
7991   }
7992 
7993   // We might be able to do better than this under some circumstances, but in
7994   // general, fsel-based lowering of select is a finite-math-only optimization.
7995   // For more information, see section F.3 of the 2.06 ISA specification.
7996   // With ISA 3.0
7997   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7998       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7999     return Op;
8000 
8001   // If the RHS of the comparison is a 0.0, we don't need to do the
8002   // subtraction at all.
8003   SDValue Sel1;
8004   if (isFloatingPointZero(RHS))
8005     switch (CC) {
8006     default: break;       // SETUO etc aren't handled by fsel.
8007     case ISD::SETNE:
8008       std::swap(TV, FV);
8009       LLVM_FALLTHROUGH;
8010     case ISD::SETEQ:
8011       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8012         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8013       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8014       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8015         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8016       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8017                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8018     case ISD::SETULT:
8019     case ISD::SETLT:
8020       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8021       LLVM_FALLTHROUGH;
8022     case ISD::SETOGE:
8023     case ISD::SETGE:
8024       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8025         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8026       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8027     case ISD::SETUGT:
8028     case ISD::SETGT:
8029       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8030       LLVM_FALLTHROUGH;
8031     case ISD::SETOLE:
8032     case ISD::SETLE:
8033       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8034         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8035       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8036                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8037     }
8038 
8039   SDValue Cmp;
8040   switch (CC) {
8041   default: break;       // SETUO etc aren't handled by fsel.
8042   case ISD::SETNE:
8043     std::swap(TV, FV);
8044     LLVM_FALLTHROUGH;
8045   case ISD::SETEQ:
8046     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8047     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8048       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8049     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8050     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8051       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8052     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8053                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8054   case ISD::SETULT:
8055   case ISD::SETLT:
8056     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8057     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8058       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8059     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8060   case ISD::SETOGE:
8061   case ISD::SETGE:
8062     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8063     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8064       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8065     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8066   case ISD::SETUGT:
8067   case ISD::SETGT:
8068     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8069     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8070       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8071     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8072   case ISD::SETOLE:
8073   case ISD::SETLE:
8074     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8075     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8076       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8077     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8078   }
8079   return Op;
8080 }
8081 
8082 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8083                                                SelectionDAG &DAG,
8084                                                const SDLoc &dl) const {
8085   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8086   SDValue Src = Op.getOperand(0);
8087   if (Src.getValueType() == MVT::f32)
8088     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8089 
8090   SDValue Tmp;
8091   switch (Op.getSimpleValueType().SimpleTy) {
8092   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8093   case MVT::i32:
8094     Tmp = DAG.getNode(
8095         Op.getOpcode() == ISD::FP_TO_SINT
8096             ? PPCISD::FCTIWZ
8097             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8098         dl, MVT::f64, Src);
8099     break;
8100   case MVT::i64:
8101     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8102            "i64 FP_TO_UINT is supported only with FPCVT");
8103     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8104                                                         PPCISD::FCTIDUZ,
8105                       dl, MVT::f64, Src);
8106     break;
8107   }
8108 
8109   // Convert the FP value to an int value through memory.
8110   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8111     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8112   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8113   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8114   MachinePointerInfo MPI =
8115       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8116 
8117   // Emit a store to the stack slot.
8118   SDValue Chain;
8119   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8120   if (i32Stack) {
8121     MachineFunction &MF = DAG.getMachineFunction();
8122     Alignment = Align(4);
8123     MachineMemOperand *MMO =
8124         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8125     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8126     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8127               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8128   } else
8129     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8130 
8131   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8132   // add in a bias on big endian.
8133   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8134     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8135                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8136     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8137   }
8138 
8139   RLI.Chain = Chain;
8140   RLI.Ptr = FIPtr;
8141   RLI.MPI = MPI;
8142   RLI.Alignment = Alignment;
8143 }
8144 
8145 /// Custom lowers floating point to integer conversions to use
8146 /// the direct move instructions available in ISA 2.07 to avoid the
8147 /// need for load/store combinations.
8148 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8149                                                     SelectionDAG &DAG,
8150                                                     const SDLoc &dl) const {
8151   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8152   SDValue Src = Op.getOperand(0);
8153 
8154   if (Src.getValueType() == MVT::f32)
8155     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8156 
8157   SDValue Tmp;
8158   switch (Op.getSimpleValueType().SimpleTy) {
8159   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8160   case MVT::i32:
8161     Tmp = DAG.getNode(
8162         Op.getOpcode() == ISD::FP_TO_SINT
8163             ? PPCISD::FCTIWZ
8164             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8165         dl, MVT::f64, Src);
8166     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8167     break;
8168   case MVT::i64:
8169     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8170            "i64 FP_TO_UINT is supported only with FPCVT");
8171     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8172                                                         PPCISD::FCTIDUZ,
8173                       dl, MVT::f64, Src);
8174     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8175     break;
8176   }
8177   return Tmp;
8178 }
8179 
8180 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8181                                           const SDLoc &dl) const {
8182 
8183   // FP to INT conversions are legal for f128.
8184   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8185     return Op;
8186 
8187   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8188   // PPC (the libcall is not available).
8189   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8190     if (Op.getValueType() == MVT::i32) {
8191       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8192         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8193                                  MVT::f64, Op.getOperand(0),
8194                                  DAG.getIntPtrConstant(0, dl));
8195         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8196                                  MVT::f64, Op.getOperand(0),
8197                                  DAG.getIntPtrConstant(1, dl));
8198 
8199         // Add the two halves of the long double in round-to-zero mode.
8200         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8201 
8202         // Now use a smaller FP_TO_SINT.
8203         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8204       }
8205       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8206         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8207         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8208         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8209         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8210         // FIXME: generated code sucks.
8211         // TODO: Are there fast-math-flags to propagate to this FSUB?
8212         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8213                                    Op.getOperand(0), Tmp);
8214         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8215         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8216                            DAG.getConstant(0x80000000, dl, MVT::i32));
8217         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8218                                     Op.getOperand(0));
8219         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8220                                ISD::SETGE);
8221       }
8222     }
8223 
8224     return SDValue();
8225   }
8226 
8227   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8228     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8229 
8230   ReuseLoadInfo RLI;
8231   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8232 
8233   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8234                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8235 }
8236 
8237 // We're trying to insert a regular store, S, and then a load, L. If the
8238 // incoming value, O, is a load, we might just be able to have our load use the
8239 // address used by O. However, we don't know if anything else will store to
8240 // that address before we can load from it. To prevent this situation, we need
8241 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8242 // the same chain operand as O, we create a token factor from the chain results
8243 // of O and L, and we replace all uses of O's chain result with that token
8244 // factor (see spliceIntoChain below for this last part).
8245 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8246                                             ReuseLoadInfo &RLI,
8247                                             SelectionDAG &DAG,
8248                                             ISD::LoadExtType ET) const {
8249   SDLoc dl(Op);
8250   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8251                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8252   if (ET == ISD::NON_EXTLOAD &&
8253       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8254       isOperationLegalOrCustom(Op.getOpcode(),
8255                                Op.getOperand(0).getValueType())) {
8256 
8257     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8258     return true;
8259   }
8260 
8261   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8262   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8263       LD->isNonTemporal())
8264     return false;
8265   if (LD->getMemoryVT() != MemVT)
8266     return false;
8267 
8268   RLI.Ptr = LD->getBasePtr();
8269   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8270     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8271            "Non-pre-inc AM on PPC?");
8272     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8273                           LD->getOffset());
8274   }
8275 
8276   RLI.Chain = LD->getChain();
8277   RLI.MPI = LD->getPointerInfo();
8278   RLI.IsDereferenceable = LD->isDereferenceable();
8279   RLI.IsInvariant = LD->isInvariant();
8280   RLI.Alignment = LD->getAlign();
8281   RLI.AAInfo = LD->getAAInfo();
8282   RLI.Ranges = LD->getRanges();
8283 
8284   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8285   return true;
8286 }
8287 
8288 // Given the head of the old chain, ResChain, insert a token factor containing
8289 // it and NewResChain, and make users of ResChain now be users of that token
8290 // factor.
8291 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8292 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8293                                         SDValue NewResChain,
8294                                         SelectionDAG &DAG) const {
8295   if (!ResChain)
8296     return;
8297 
8298   SDLoc dl(NewResChain);
8299 
8300   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8301                            NewResChain, DAG.getUNDEF(MVT::Other));
8302   assert(TF.getNode() != NewResChain.getNode() &&
8303          "A new TF really is required here");
8304 
8305   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8306   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8307 }
8308 
8309 /// Analyze profitability of direct move
8310 /// prefer float load to int load plus direct move
8311 /// when there is no integer use of int load
8312 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8313   SDNode *Origin = Op.getOperand(0).getNode();
8314   if (Origin->getOpcode() != ISD::LOAD)
8315     return true;
8316 
8317   // If there is no LXSIBZX/LXSIHZX, like Power8,
8318   // prefer direct move if the memory size is 1 or 2 bytes.
8319   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8320   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8321     return true;
8322 
8323   for (SDNode::use_iterator UI = Origin->use_begin(),
8324                             UE = Origin->use_end();
8325        UI != UE; ++UI) {
8326 
8327     // Only look at the users of the loaded value.
8328     if (UI.getUse().get().getResNo() != 0)
8329       continue;
8330 
8331     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8332         UI->getOpcode() != ISD::UINT_TO_FP)
8333       return true;
8334   }
8335 
8336   return false;
8337 }
8338 
8339 /// Custom lowers integer to floating point conversions to use
8340 /// the direct move instructions available in ISA 2.07 to avoid the
8341 /// need for load/store combinations.
8342 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8343                                                     SelectionDAG &DAG,
8344                                                     const SDLoc &dl) const {
8345   assert((Op.getValueType() == MVT::f32 ||
8346           Op.getValueType() == MVT::f64) &&
8347          "Invalid floating point type as target of conversion");
8348   assert(Subtarget.hasFPCVT() &&
8349          "Int to FP conversions with direct moves require FPCVT");
8350   SDValue FP;
8351   SDValue Src = Op.getOperand(0);
8352   bool SinglePrec = Op.getValueType() == MVT::f32;
8353   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8354   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8355   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8356                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8357 
8358   if (WordInt) {
8359     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8360                      dl, MVT::f64, Src);
8361     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8362   }
8363   else {
8364     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8365     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8366   }
8367 
8368   return FP;
8369 }
8370 
8371 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8372 
8373   EVT VecVT = Vec.getValueType();
8374   assert(VecVT.isVector() && "Expected a vector type.");
8375   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8376 
8377   EVT EltVT = VecVT.getVectorElementType();
8378   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8379   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8380 
8381   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8382   SmallVector<SDValue, 16> Ops(NumConcat);
8383   Ops[0] = Vec;
8384   SDValue UndefVec = DAG.getUNDEF(VecVT);
8385   for (unsigned i = 1; i < NumConcat; ++i)
8386     Ops[i] = UndefVec;
8387 
8388   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8389 }
8390 
8391 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8392                                                 const SDLoc &dl) const {
8393 
8394   unsigned Opc = Op.getOpcode();
8395   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8396          "Unexpected conversion type");
8397   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8398          "Supports conversions to v2f64/v4f32 only.");
8399 
8400   bool SignedConv = Opc == ISD::SINT_TO_FP;
8401   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8402 
8403   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8404   EVT WideVT = Wide.getValueType();
8405   unsigned WideNumElts = WideVT.getVectorNumElements();
8406   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8407 
8408   SmallVector<int, 16> ShuffV;
8409   for (unsigned i = 0; i < WideNumElts; ++i)
8410     ShuffV.push_back(i + WideNumElts);
8411 
8412   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8413   int SaveElts = FourEltRes ? 4 : 2;
8414   if (Subtarget.isLittleEndian())
8415     for (int i = 0; i < SaveElts; i++)
8416       ShuffV[i * Stride] = i;
8417   else
8418     for (int i = 1; i <= SaveElts; i++)
8419       ShuffV[i * Stride - 1] = i - 1;
8420 
8421   SDValue ShuffleSrc2 =
8422       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8423   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8424 
8425   SDValue Extend;
8426   if (SignedConv) {
8427     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8428     EVT ExtVT = Op.getOperand(0).getValueType();
8429     if (Subtarget.hasP9Altivec())
8430       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8431                                IntermediateVT.getVectorNumElements());
8432 
8433     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8434                          DAG.getValueType(ExtVT));
8435   } else
8436     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8437 
8438   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8439 }
8440 
8441 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8442                                           SelectionDAG &DAG) const {
8443   SDLoc dl(Op);
8444 
8445   EVT InVT = Op.getOperand(0).getValueType();
8446   EVT OutVT = Op.getValueType();
8447   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8448       isOperationCustom(Op.getOpcode(), InVT))
8449     return LowerINT_TO_FPVector(Op, DAG, dl);
8450 
8451   // Conversions to f128 are legal.
8452   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8453     return Op;
8454 
8455   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8456     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8457       return SDValue();
8458 
8459     SDValue Value = Op.getOperand(0);
8460     // The values are now known to be -1 (false) or 1 (true). To convert this
8461     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8462     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8463     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8464 
8465     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8466 
8467     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8468 
8469     if (Op.getValueType() != MVT::v4f64)
8470       Value = DAG.getNode(ISD::FP_ROUND, dl,
8471                           Op.getValueType(), Value,
8472                           DAG.getIntPtrConstant(1, dl));
8473     return Value;
8474   }
8475 
8476   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8477   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8478     return SDValue();
8479 
8480   if (Op.getOperand(0).getValueType() == MVT::i1)
8481     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8482                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8483                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8484 
8485   // If we have direct moves, we can do all the conversion, skip the store/load
8486   // however, without FPCVT we can't do most conversions.
8487   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8488       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8489     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8490 
8491   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8492          "UINT_TO_FP is supported only with FPCVT");
8493 
8494   // If we have FCFIDS, then use it when converting to single-precision.
8495   // Otherwise, convert to double-precision and then round.
8496   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8497                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8498                                                             : PPCISD::FCFIDS)
8499                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8500                                                             : PPCISD::FCFID);
8501   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8502                   ? MVT::f32
8503                   : MVT::f64;
8504 
8505   if (Op.getOperand(0).getValueType() == MVT::i64) {
8506     SDValue SINT = Op.getOperand(0);
8507     // When converting to single-precision, we actually need to convert
8508     // to double-precision first and then round to single-precision.
8509     // To avoid double-rounding effects during that operation, we have
8510     // to prepare the input operand.  Bits that might be truncated when
8511     // converting to double-precision are replaced by a bit that won't
8512     // be lost at this stage, but is below the single-precision rounding
8513     // position.
8514     //
8515     // However, if -enable-unsafe-fp-math is in effect, accept double
8516     // rounding to avoid the extra overhead.
8517     if (Op.getValueType() == MVT::f32 &&
8518         !Subtarget.hasFPCVT() &&
8519         !DAG.getTarget().Options.UnsafeFPMath) {
8520 
8521       // Twiddle input to make sure the low 11 bits are zero.  (If this
8522       // is the case, we are guaranteed the value will fit into the 53 bit
8523       // mantissa of an IEEE double-precision value without rounding.)
8524       // If any of those low 11 bits were not zero originally, make sure
8525       // bit 12 (value 2048) is set instead, so that the final rounding
8526       // to single-precision gets the correct result.
8527       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8528                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8529       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8530                           Round, DAG.getConstant(2047, dl, MVT::i64));
8531       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8532       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8533                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8534 
8535       // However, we cannot use that value unconditionally: if the magnitude
8536       // of the input value is small, the bit-twiddling we did above might
8537       // end up visibly changing the output.  Fortunately, in that case, we
8538       // don't need to twiddle bits since the original input will convert
8539       // exactly to double-precision floating-point already.  Therefore,
8540       // construct a conditional to use the original value if the top 11
8541       // bits are all sign-bit copies, and use the rounded value computed
8542       // above otherwise.
8543       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8544                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8545       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8546                          Cond, DAG.getConstant(1, dl, MVT::i64));
8547       Cond = DAG.getSetCC(
8548           dl,
8549           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8550           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8551 
8552       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8553     }
8554 
8555     ReuseLoadInfo RLI;
8556     SDValue Bits;
8557 
8558     MachineFunction &MF = DAG.getMachineFunction();
8559     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8560       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8561                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8562       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8563     } else if (Subtarget.hasLFIWAX() &&
8564                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8565       MachineMemOperand *MMO =
8566         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8567                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8568       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8569       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8570                                      DAG.getVTList(MVT::f64, MVT::Other),
8571                                      Ops, MVT::i32, MMO);
8572       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8573     } else if (Subtarget.hasFPCVT() &&
8574                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8575       MachineMemOperand *MMO =
8576         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8577                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8578       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8579       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8580                                      DAG.getVTList(MVT::f64, MVT::Other),
8581                                      Ops, MVT::i32, MMO);
8582       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8583     } else if (((Subtarget.hasLFIWAX() &&
8584                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8585                 (Subtarget.hasFPCVT() &&
8586                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8587                SINT.getOperand(0).getValueType() == MVT::i32) {
8588       MachineFrameInfo &MFI = MF.getFrameInfo();
8589       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8590 
8591       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8592       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8593 
8594       SDValue Store =
8595           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8596                        MachinePointerInfo::getFixedStack(
8597                            DAG.getMachineFunction(), FrameIdx));
8598 
8599       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8600              "Expected an i32 store");
8601 
8602       RLI.Ptr = FIdx;
8603       RLI.Chain = Store;
8604       RLI.MPI =
8605           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8606       RLI.Alignment = Align(4);
8607 
8608       MachineMemOperand *MMO =
8609         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8610                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8611       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8612       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8613                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8614                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8615                                      Ops, MVT::i32, MMO);
8616     } else
8617       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8618 
8619     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8620 
8621     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8622       FP = DAG.getNode(ISD::FP_ROUND, dl,
8623                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8624     return FP;
8625   }
8626 
8627   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8628          "Unhandled INT_TO_FP type in custom expander!");
8629   // Since we only generate this in 64-bit mode, we can take advantage of
8630   // 64-bit registers.  In particular, sign extend the input value into the
8631   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8632   // then lfd it and fcfid it.
8633   MachineFunction &MF = DAG.getMachineFunction();
8634   MachineFrameInfo &MFI = MF.getFrameInfo();
8635   EVT PtrVT = getPointerTy(MF.getDataLayout());
8636 
8637   SDValue Ld;
8638   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8639     ReuseLoadInfo RLI;
8640     bool ReusingLoad;
8641     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8642                                             DAG))) {
8643       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8644       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8645 
8646       SDValue Store =
8647           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8648                        MachinePointerInfo::getFixedStack(
8649                            DAG.getMachineFunction(), FrameIdx));
8650 
8651       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8652              "Expected an i32 store");
8653 
8654       RLI.Ptr = FIdx;
8655       RLI.Chain = Store;
8656       RLI.MPI =
8657           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8658       RLI.Alignment = Align(4);
8659     }
8660 
8661     MachineMemOperand *MMO =
8662       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8663                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8664     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8665     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8666                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8667                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8668                                  Ops, MVT::i32, MMO);
8669     if (ReusingLoad)
8670       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8671   } else {
8672     assert(Subtarget.isPPC64() &&
8673            "i32->FP without LFIWAX supported only on PPC64");
8674 
8675     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8676     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8677 
8678     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8679                                 Op.getOperand(0));
8680 
8681     // STD the extended value into the stack slot.
8682     SDValue Store = DAG.getStore(
8683         DAG.getEntryNode(), dl, Ext64, FIdx,
8684         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8685 
8686     // Load the value as a double.
8687     Ld = DAG.getLoad(
8688         MVT::f64, dl, Store, FIdx,
8689         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8690   }
8691 
8692   // FCFID it and return it.
8693   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8694   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8695     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8696                      DAG.getIntPtrConstant(0, dl));
8697   return FP;
8698 }
8699 
8700 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8701                                             SelectionDAG &DAG) const {
8702   SDLoc dl(Op);
8703   /*
8704    The rounding mode is in bits 30:31 of FPSR, and has the following
8705    settings:
8706      00 Round to nearest
8707      01 Round to 0
8708      10 Round to +inf
8709      11 Round to -inf
8710 
8711   FLT_ROUNDS, on the other hand, expects the following:
8712     -1 Undefined
8713      0 Round to 0
8714      1 Round to nearest
8715      2 Round to +inf
8716      3 Round to -inf
8717 
8718   To perform the conversion, we do:
8719     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8720   */
8721 
8722   MachineFunction &MF = DAG.getMachineFunction();
8723   EVT VT = Op.getValueType();
8724   EVT PtrVT = getPointerTy(MF.getDataLayout());
8725 
8726   // Save FP Control Word to register
8727   SDValue Chain = Op.getOperand(0);
8728   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8729   Chain = MFFS.getValue(1);
8730 
8731   // Save FP register to stack slot
8732   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8733   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8734   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8735 
8736   // Load FP Control Word from low 32 bits of stack slot.
8737   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8738   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8739   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8740   Chain = CWD.getValue(1);
8741 
8742   // Transform as necessary
8743   SDValue CWD1 =
8744     DAG.getNode(ISD::AND, dl, MVT::i32,
8745                 CWD, DAG.getConstant(3, dl, MVT::i32));
8746   SDValue CWD2 =
8747     DAG.getNode(ISD::SRL, dl, MVT::i32,
8748                 DAG.getNode(ISD::AND, dl, MVT::i32,
8749                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8750                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8751                             DAG.getConstant(3, dl, MVT::i32)),
8752                 DAG.getConstant(1, dl, MVT::i32));
8753 
8754   SDValue RetVal =
8755     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8756 
8757   RetVal =
8758       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8759                   dl, VT, RetVal);
8760 
8761   return DAG.getMergeValues({RetVal, Chain}, dl);
8762 }
8763 
8764 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8765   EVT VT = Op.getValueType();
8766   unsigned BitWidth = VT.getSizeInBits();
8767   SDLoc dl(Op);
8768   assert(Op.getNumOperands() == 3 &&
8769          VT == Op.getOperand(1).getValueType() &&
8770          "Unexpected SHL!");
8771 
8772   // Expand into a bunch of logical ops.  Note that these ops
8773   // depend on the PPC behavior for oversized shift amounts.
8774   SDValue Lo = Op.getOperand(0);
8775   SDValue Hi = Op.getOperand(1);
8776   SDValue Amt = Op.getOperand(2);
8777   EVT AmtVT = Amt.getValueType();
8778 
8779   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8780                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8781   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8782   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8783   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8784   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8785                              DAG.getConstant(-BitWidth, dl, AmtVT));
8786   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8787   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8788   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8789   SDValue OutOps[] = { OutLo, OutHi };
8790   return DAG.getMergeValues(OutOps, dl);
8791 }
8792 
8793 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8794   EVT VT = Op.getValueType();
8795   SDLoc dl(Op);
8796   unsigned BitWidth = VT.getSizeInBits();
8797   assert(Op.getNumOperands() == 3 &&
8798          VT == Op.getOperand(1).getValueType() &&
8799          "Unexpected SRL!");
8800 
8801   // Expand into a bunch of logical ops.  Note that these ops
8802   // depend on the PPC behavior for oversized shift amounts.
8803   SDValue Lo = Op.getOperand(0);
8804   SDValue Hi = Op.getOperand(1);
8805   SDValue Amt = Op.getOperand(2);
8806   EVT AmtVT = Amt.getValueType();
8807 
8808   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8809                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8810   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8811   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8812   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8813   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8814                              DAG.getConstant(-BitWidth, dl, AmtVT));
8815   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8816   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8817   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8818   SDValue OutOps[] = { OutLo, OutHi };
8819   return DAG.getMergeValues(OutOps, dl);
8820 }
8821 
8822 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8823   SDLoc dl(Op);
8824   EVT VT = Op.getValueType();
8825   unsigned BitWidth = VT.getSizeInBits();
8826   assert(Op.getNumOperands() == 3 &&
8827          VT == Op.getOperand(1).getValueType() &&
8828          "Unexpected SRA!");
8829 
8830   // Expand into a bunch of logical ops, followed by a select_cc.
8831   SDValue Lo = Op.getOperand(0);
8832   SDValue Hi = Op.getOperand(1);
8833   SDValue Amt = Op.getOperand(2);
8834   EVT AmtVT = Amt.getValueType();
8835 
8836   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8837                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8838   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8839   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8840   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8841   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8842                              DAG.getConstant(-BitWidth, dl, AmtVT));
8843   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8844   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8845   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8846                                   Tmp4, Tmp6, ISD::SETLE);
8847   SDValue OutOps[] = { OutLo, OutHi };
8848   return DAG.getMergeValues(OutOps, dl);
8849 }
8850 
8851 //===----------------------------------------------------------------------===//
8852 // Vector related lowering.
8853 //
8854 
8855 /// BuildSplatI - Build a canonical splati of Val with an element size of
8856 /// SplatSize.  Cast the result to VT.
8857 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8858                            SelectionDAG &DAG, const SDLoc &dl) {
8859   static const MVT VTys[] = { // canonical VT to use for each size.
8860     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8861   };
8862 
8863   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8864 
8865   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8866   if (Val == -1)
8867     SplatSize = 1;
8868 
8869   EVT CanonicalVT = VTys[SplatSize-1];
8870 
8871   // Build a canonical splat for this value.
8872   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8873 }
8874 
8875 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8876 /// specified intrinsic ID.
8877 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8878                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8879   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8880   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8881                      DAG.getConstant(IID, dl, MVT::i32), Op);
8882 }
8883 
8884 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8885 /// specified intrinsic ID.
8886 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8887                                 SelectionDAG &DAG, const SDLoc &dl,
8888                                 EVT DestVT = MVT::Other) {
8889   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8890   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8891                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8892 }
8893 
8894 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8895 /// specified intrinsic ID.
8896 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8897                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8898                                 EVT DestVT = MVT::Other) {
8899   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8900   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8901                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8902 }
8903 
8904 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8905 /// amount.  The result has the specified value type.
8906 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8907                            SelectionDAG &DAG, const SDLoc &dl) {
8908   // Force LHS/RHS to be the right type.
8909   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8910   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8911 
8912   int Ops[16];
8913   for (unsigned i = 0; i != 16; ++i)
8914     Ops[i] = i + Amt;
8915   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8916   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8917 }
8918 
8919 /// Do we have an efficient pattern in a .td file for this node?
8920 ///
8921 /// \param V - pointer to the BuildVectorSDNode being matched
8922 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8923 ///
8924 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8925 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8926 /// the opposite is true (expansion is beneficial) are:
8927 /// - The node builds a vector out of integers that are not 32 or 64-bits
8928 /// - The node builds a vector out of constants
8929 /// - The node is a "load-and-splat"
8930 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8931 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8932                                             bool HasDirectMove,
8933                                             bool HasP8Vector) {
8934   EVT VecVT = V->getValueType(0);
8935   bool RightType = VecVT == MVT::v2f64 ||
8936     (HasP8Vector && VecVT == MVT::v4f32) ||
8937     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8938   if (!RightType)
8939     return false;
8940 
8941   bool IsSplat = true;
8942   bool IsLoad = false;
8943   SDValue Op0 = V->getOperand(0);
8944 
8945   // This function is called in a block that confirms the node is not a constant
8946   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8947   // different constants.
8948   if (V->isConstant())
8949     return false;
8950   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8951     if (V->getOperand(i).isUndef())
8952       return false;
8953     // We want to expand nodes that represent load-and-splat even if the
8954     // loaded value is a floating point truncation or conversion to int.
8955     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8956         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8957          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8958         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8959          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8960         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8961          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8962       IsLoad = true;
8963     // If the operands are different or the input is not a load and has more
8964     // uses than just this BV node, then it isn't a splat.
8965     if (V->getOperand(i) != Op0 ||
8966         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8967       IsSplat = false;
8968   }
8969   return !(IsSplat && IsLoad);
8970 }
8971 
8972 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8973 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8974 
8975   SDLoc dl(Op);
8976   SDValue Op0 = Op->getOperand(0);
8977 
8978   if (!EnableQuadPrecision ||
8979       (Op.getValueType() != MVT::f128 ) ||
8980       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8981       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8982       (Op0.getOperand(1).getValueType() != MVT::i64))
8983     return SDValue();
8984 
8985   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8986                      Op0.getOperand(1));
8987 }
8988 
8989 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8990   const SDValue *InputLoad = &Op;
8991   if (InputLoad->getOpcode() == ISD::BITCAST)
8992     InputLoad = &InputLoad->getOperand(0);
8993   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8994     InputLoad = &InputLoad->getOperand(0);
8995   if (InputLoad->getOpcode() != ISD::LOAD)
8996     return nullptr;
8997   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8998   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8999 }
9000 
9001 // If this is a case we can't handle, return null and let the default
9002 // expansion code take care of it.  If we CAN select this case, and if it
9003 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9004 // this case more efficiently than a constant pool load, lower it to the
9005 // sequence of ops that should be used.
9006 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9007                                              SelectionDAG &DAG) const {
9008   SDLoc dl(Op);
9009   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9010   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9011 
9012   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
9013     // We first build an i32 vector, load it into a QPX register,
9014     // then convert it to a floating-point vector and compare it
9015     // to a zero vector to get the boolean result.
9016     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9017     int FrameIdx = MFI.CreateStackObject(16, 16, false);
9018     MachinePointerInfo PtrInfo =
9019         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9020     EVT PtrVT = getPointerTy(DAG.getDataLayout());
9021     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9022 
9023     assert(BVN->getNumOperands() == 4 &&
9024       "BUILD_VECTOR for v4i1 does not have 4 operands");
9025 
9026     bool IsConst = true;
9027     for (unsigned i = 0; i < 4; ++i) {
9028       if (BVN->getOperand(i).isUndef()) continue;
9029       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
9030         IsConst = false;
9031         break;
9032       }
9033     }
9034 
9035     if (IsConst) {
9036       Constant *One =
9037         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9038       Constant *NegOne =
9039         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9040 
9041       Constant *CV[4];
9042       for (unsigned i = 0; i < 4; ++i) {
9043         if (BVN->getOperand(i).isUndef())
9044           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9045         else if (isNullConstant(BVN->getOperand(i)))
9046           CV[i] = NegOne;
9047         else
9048           CV[i] = One;
9049       }
9050 
9051       Constant *CP = ConstantVector::get(CV);
9052       SDValue CPIdx =
9053           DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16));
9054 
9055       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9056       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9057       return DAG.getMemIntrinsicNode(
9058           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9059           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9060     }
9061 
9062     SmallVector<SDValue, 4> Stores;
9063     for (unsigned i = 0; i < 4; ++i) {
9064       if (BVN->getOperand(i).isUndef()) continue;
9065 
9066       unsigned Offset = 4*i;
9067       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9068       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9069 
9070       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9071       if (StoreSize > 4) {
9072         Stores.push_back(
9073             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9074                               PtrInfo.getWithOffset(Offset), MVT::i32));
9075       } else {
9076         SDValue StoreValue = BVN->getOperand(i);
9077         if (StoreSize < 4)
9078           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9079 
9080         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9081                                       PtrInfo.getWithOffset(Offset)));
9082       }
9083     }
9084 
9085     SDValue StoreChain;
9086     if (!Stores.empty())
9087       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9088     else
9089       StoreChain = DAG.getEntryNode();
9090 
9091     // Now load from v4i32 into the QPX register; this will extend it to
9092     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9093     // is typed as v4f64 because the QPX register integer states are not
9094     // explicitly represented.
9095 
9096     SDValue Ops[] = {StoreChain,
9097                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9098                      FIdx};
9099     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9100 
9101     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9102       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9103     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9104       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9105       LoadedVect);
9106 
9107     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9108 
9109     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9110   }
9111 
9112   // All other QPX vectors are handled by generic code.
9113   if (Subtarget.hasQPX())
9114     return SDValue();
9115 
9116   // Check if this is a splat of a constant value.
9117   APInt APSplatBits, APSplatUndef;
9118   unsigned SplatBitSize;
9119   bool HasAnyUndefs;
9120   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9121                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9122       SplatBitSize > 32) {
9123 
9124     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9125     // Handle load-and-splat patterns as we have instructions that will do this
9126     // in one go.
9127     if (InputLoad && DAG.isSplatValue(Op, true)) {
9128       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9129 
9130       // We have handling for 4 and 8 byte elements.
9131       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9132 
9133       // Checking for a single use of this load, we have to check for vector
9134       // width (128 bits) / ElementSize uses (since each operand of the
9135       // BUILD_VECTOR is a separate use of the value.
9136       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9137           ((Subtarget.hasVSX() && ElementSize == 64) ||
9138            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9139         SDValue Ops[] = {
9140           LD->getChain(),    // Chain
9141           LD->getBasePtr(),  // Ptr
9142           DAG.getValueType(Op.getValueType()) // VT
9143         };
9144         return
9145           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9146                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9147                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9148       }
9149     }
9150 
9151     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9152     // lowered to VSX instructions under certain conditions.
9153     // Without VSX, there is no pattern more efficient than expanding the node.
9154     if (Subtarget.hasVSX() &&
9155         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9156                                         Subtarget.hasP8Vector()))
9157       return Op;
9158     return SDValue();
9159   }
9160 
9161   unsigned SplatBits = APSplatBits.getZExtValue();
9162   unsigned SplatUndef = APSplatUndef.getZExtValue();
9163   unsigned SplatSize = SplatBitSize / 8;
9164 
9165   // First, handle single instruction cases.
9166 
9167   // All zeros?
9168   if (SplatBits == 0) {
9169     // Canonicalize all zero vectors to be v4i32.
9170     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9171       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9172       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9173     }
9174     return Op;
9175   }
9176 
9177   // We have XXSPLTIB for constant splats one byte wide
9178   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9179   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9180   if (Subtarget.hasP9Vector() && SplatSize == 1)
9181     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9182 
9183   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9184   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9185                     (32-SplatBitSize));
9186   if (SextVal >= -16 && SextVal <= 15)
9187     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9188 
9189   // Two instruction sequences.
9190 
9191   // If this value is in the range [-32,30] and is even, use:
9192   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9193   // If this value is in the range [17,31] and is odd, use:
9194   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9195   // If this value is in the range [-31,-17] and is odd, use:
9196   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9197   // Note the last two are three-instruction sequences.
9198   if (SextVal >= -32 && SextVal <= 31) {
9199     // To avoid having these optimizations undone by constant folding,
9200     // we convert to a pseudo that will be expanded later into one of
9201     // the above forms.
9202     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9203     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9204               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9205     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9206     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9207     if (VT == Op.getValueType())
9208       return RetVal;
9209     else
9210       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9211   }
9212 
9213   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9214   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9215   // for fneg/fabs.
9216   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9217     // Make -1 and vspltisw -1:
9218     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9219 
9220     // Make the VSLW intrinsic, computing 0x8000_0000.
9221     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9222                                    OnesV, DAG, dl);
9223 
9224     // xor by OnesV to invert it.
9225     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9226     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9227   }
9228 
9229   // Check to see if this is a wide variety of vsplti*, binop self cases.
9230   static const signed char SplatCsts[] = {
9231     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9232     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9233   };
9234 
9235   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9236     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9237     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9238     int i = SplatCsts[idx];
9239 
9240     // Figure out what shift amount will be used by altivec if shifted by i in
9241     // this splat size.
9242     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9243 
9244     // vsplti + shl self.
9245     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9246       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9247       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9248         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9249         Intrinsic::ppc_altivec_vslw
9250       };
9251       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9252       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9253     }
9254 
9255     // vsplti + srl self.
9256     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9257       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9258       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9259         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9260         Intrinsic::ppc_altivec_vsrw
9261       };
9262       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9263       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9264     }
9265 
9266     // vsplti + sra self.
9267     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9268       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9269       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9270         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9271         Intrinsic::ppc_altivec_vsraw
9272       };
9273       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9274       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9275     }
9276 
9277     // vsplti + rol self.
9278     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9279                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9280       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9281       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9282         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9283         Intrinsic::ppc_altivec_vrlw
9284       };
9285       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9286       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9287     }
9288 
9289     // t = vsplti c, result = vsldoi t, t, 1
9290     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9291       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9292       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9293       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9294     }
9295     // t = vsplti c, result = vsldoi t, t, 2
9296     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9297       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9298       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9299       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9300     }
9301     // t = vsplti c, result = vsldoi t, t, 3
9302     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9303       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9304       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9305       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9306     }
9307   }
9308 
9309   return SDValue();
9310 }
9311 
9312 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9313 /// the specified operations to build the shuffle.
9314 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9315                                       SDValue RHS, SelectionDAG &DAG,
9316                                       const SDLoc &dl) {
9317   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9318   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9319   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9320 
9321   enum {
9322     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9323     OP_VMRGHW,
9324     OP_VMRGLW,
9325     OP_VSPLTISW0,
9326     OP_VSPLTISW1,
9327     OP_VSPLTISW2,
9328     OP_VSPLTISW3,
9329     OP_VSLDOI4,
9330     OP_VSLDOI8,
9331     OP_VSLDOI12
9332   };
9333 
9334   if (OpNum == OP_COPY) {
9335     if (LHSID == (1*9+2)*9+3) return LHS;
9336     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9337     return RHS;
9338   }
9339 
9340   SDValue OpLHS, OpRHS;
9341   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9342   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9343 
9344   int ShufIdxs[16];
9345   switch (OpNum) {
9346   default: llvm_unreachable("Unknown i32 permute!");
9347   case OP_VMRGHW:
9348     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9349     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9350     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9351     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9352     break;
9353   case OP_VMRGLW:
9354     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9355     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9356     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9357     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9358     break;
9359   case OP_VSPLTISW0:
9360     for (unsigned i = 0; i != 16; ++i)
9361       ShufIdxs[i] = (i&3)+0;
9362     break;
9363   case OP_VSPLTISW1:
9364     for (unsigned i = 0; i != 16; ++i)
9365       ShufIdxs[i] = (i&3)+4;
9366     break;
9367   case OP_VSPLTISW2:
9368     for (unsigned i = 0; i != 16; ++i)
9369       ShufIdxs[i] = (i&3)+8;
9370     break;
9371   case OP_VSPLTISW3:
9372     for (unsigned i = 0; i != 16; ++i)
9373       ShufIdxs[i] = (i&3)+12;
9374     break;
9375   case OP_VSLDOI4:
9376     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9377   case OP_VSLDOI8:
9378     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9379   case OP_VSLDOI12:
9380     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9381   }
9382   EVT VT = OpLHS.getValueType();
9383   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9384   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9385   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9386   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9387 }
9388 
9389 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9390 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9391 /// SDValue.
9392 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9393                                            SelectionDAG &DAG) const {
9394   const unsigned BytesInVector = 16;
9395   bool IsLE = Subtarget.isLittleEndian();
9396   SDLoc dl(N);
9397   SDValue V1 = N->getOperand(0);
9398   SDValue V2 = N->getOperand(1);
9399   unsigned ShiftElts = 0, InsertAtByte = 0;
9400   bool Swap = false;
9401 
9402   // Shifts required to get the byte we want at element 7.
9403   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9404                                    0, 15, 14, 13, 12, 11, 10, 9};
9405   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9406                                 1, 2,  3,  4,  5,  6,  7,  8};
9407 
9408   ArrayRef<int> Mask = N->getMask();
9409   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9410 
9411   // For each mask element, find out if we're just inserting something
9412   // from V2 into V1 or vice versa.
9413   // Possible permutations inserting an element from V2 into V1:
9414   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9415   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9416   //   ...
9417   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9418   // Inserting from V1 into V2 will be similar, except mask range will be
9419   // [16,31].
9420 
9421   bool FoundCandidate = false;
9422   // If both vector operands for the shuffle are the same vector, the mask
9423   // will contain only elements from the first one and the second one will be
9424   // undef.
9425   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9426   // Go through the mask of half-words to find an element that's being moved
9427   // from one vector to the other.
9428   for (unsigned i = 0; i < BytesInVector; ++i) {
9429     unsigned CurrentElement = Mask[i];
9430     // If 2nd operand is undefined, we should only look for element 7 in the
9431     // Mask.
9432     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9433       continue;
9434 
9435     bool OtherElementsInOrder = true;
9436     // Examine the other elements in the Mask to see if they're in original
9437     // order.
9438     for (unsigned j = 0; j < BytesInVector; ++j) {
9439       if (j == i)
9440         continue;
9441       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9442       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9443       // in which we always assume we're always picking from the 1st operand.
9444       int MaskOffset =
9445           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9446       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9447         OtherElementsInOrder = false;
9448         break;
9449       }
9450     }
9451     // If other elements are in original order, we record the number of shifts
9452     // we need to get the element we want into element 7. Also record which byte
9453     // in the vector we should insert into.
9454     if (OtherElementsInOrder) {
9455       // If 2nd operand is undefined, we assume no shifts and no swapping.
9456       if (V2.isUndef()) {
9457         ShiftElts = 0;
9458         Swap = false;
9459       } else {
9460         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9461         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9462                          : BigEndianShifts[CurrentElement & 0xF];
9463         Swap = CurrentElement < BytesInVector;
9464       }
9465       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9466       FoundCandidate = true;
9467       break;
9468     }
9469   }
9470 
9471   if (!FoundCandidate)
9472     return SDValue();
9473 
9474   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9475   // optionally with VECSHL if shift is required.
9476   if (Swap)
9477     std::swap(V1, V2);
9478   if (V2.isUndef())
9479     V2 = V1;
9480   if (ShiftElts) {
9481     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9482                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9483     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9484                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9485   }
9486   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9487                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9488 }
9489 
9490 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9491 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9492 /// SDValue.
9493 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9494                                            SelectionDAG &DAG) const {
9495   const unsigned NumHalfWords = 8;
9496   const unsigned BytesInVector = NumHalfWords * 2;
9497   // Check that the shuffle is on half-words.
9498   if (!isNByteElemShuffleMask(N, 2, 1))
9499     return SDValue();
9500 
9501   bool IsLE = Subtarget.isLittleEndian();
9502   SDLoc dl(N);
9503   SDValue V1 = N->getOperand(0);
9504   SDValue V2 = N->getOperand(1);
9505   unsigned ShiftElts = 0, InsertAtByte = 0;
9506   bool Swap = false;
9507 
9508   // Shifts required to get the half-word we want at element 3.
9509   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9510   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9511 
9512   uint32_t Mask = 0;
9513   uint32_t OriginalOrderLow = 0x1234567;
9514   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9515   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9516   // 32-bit space, only need 4-bit nibbles per element.
9517   for (unsigned i = 0; i < NumHalfWords; ++i) {
9518     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9519     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9520   }
9521 
9522   // For each mask element, find out if we're just inserting something
9523   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9524   // from V2 into V1:
9525   //   X, 1, 2, 3, 4, 5, 6, 7
9526   //   0, X, 2, 3, 4, 5, 6, 7
9527   //   0, 1, X, 3, 4, 5, 6, 7
9528   //   0, 1, 2, X, 4, 5, 6, 7
9529   //   0, 1, 2, 3, X, 5, 6, 7
9530   //   0, 1, 2, 3, 4, X, 6, 7
9531   //   0, 1, 2, 3, 4, 5, X, 7
9532   //   0, 1, 2, 3, 4, 5, 6, X
9533   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9534 
9535   bool FoundCandidate = false;
9536   // Go through the mask of half-words to find an element that's being moved
9537   // from one vector to the other.
9538   for (unsigned i = 0; i < NumHalfWords; ++i) {
9539     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9540     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9541     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9542     uint32_t TargetOrder = 0x0;
9543 
9544     // If both vector operands for the shuffle are the same vector, the mask
9545     // will contain only elements from the first one and the second one will be
9546     // undef.
9547     if (V2.isUndef()) {
9548       ShiftElts = 0;
9549       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9550       TargetOrder = OriginalOrderLow;
9551       Swap = false;
9552       // Skip if not the correct element or mask of other elements don't equal
9553       // to our expected order.
9554       if (MaskOneElt == VINSERTHSrcElem &&
9555           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9556         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9557         FoundCandidate = true;
9558         break;
9559       }
9560     } else { // If both operands are defined.
9561       // Target order is [8,15] if the current mask is between [0,7].
9562       TargetOrder =
9563           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9564       // Skip if mask of other elements don't equal our expected order.
9565       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9566         // We only need the last 3 bits for the number of shifts.
9567         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9568                          : BigEndianShifts[MaskOneElt & 0x7];
9569         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9570         Swap = MaskOneElt < NumHalfWords;
9571         FoundCandidate = true;
9572         break;
9573       }
9574     }
9575   }
9576 
9577   if (!FoundCandidate)
9578     return SDValue();
9579 
9580   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9581   // optionally with VECSHL if shift is required.
9582   if (Swap)
9583     std::swap(V1, V2);
9584   if (V2.isUndef())
9585     V2 = V1;
9586   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9587   if (ShiftElts) {
9588     // Double ShiftElts because we're left shifting on v16i8 type.
9589     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9590                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9591     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9592     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9593                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9594     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9595   }
9596   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9597   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9598                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9599   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9600 }
9601 
9602 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9603 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9604 /// return the code it can be lowered into.  Worst case, it can always be
9605 /// lowered into a vperm.
9606 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9607                                                SelectionDAG &DAG) const {
9608   SDLoc dl(Op);
9609   SDValue V1 = Op.getOperand(0);
9610   SDValue V2 = Op.getOperand(1);
9611   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9612   EVT VT = Op.getValueType();
9613   bool isLittleEndian = Subtarget.isLittleEndian();
9614 
9615   unsigned ShiftElts, InsertAtByte;
9616   bool Swap = false;
9617 
9618   // If this is a load-and-splat, we can do that with a single instruction
9619   // in some cases. However if the load has multiple uses, we don't want to
9620   // combine it because that will just produce multiple loads.
9621   const SDValue *InputLoad = getNormalLoadInput(V1);
9622   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9623       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9624       InputLoad->hasOneUse()) {
9625     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9626     int SplatIdx =
9627       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9628 
9629     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9630     // For 4-byte load-and-splat, we need Power9.
9631     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9632       uint64_t Offset = 0;
9633       if (IsFourByte)
9634         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9635       else
9636         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9637       SDValue BasePtr = LD->getBasePtr();
9638       if (Offset != 0)
9639         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9640                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9641       SDValue Ops[] = {
9642         LD->getChain(),    // Chain
9643         BasePtr,           // BasePtr
9644         DAG.getValueType(Op.getValueType()) // VT
9645       };
9646       SDVTList VTL =
9647         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9648       SDValue LdSplt =
9649         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9650                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9651       if (LdSplt.getValueType() != SVOp->getValueType(0))
9652         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9653       return LdSplt;
9654     }
9655   }
9656   if (Subtarget.hasP9Vector() &&
9657       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9658                            isLittleEndian)) {
9659     if (Swap)
9660       std::swap(V1, V2);
9661     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9662     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9663     if (ShiftElts) {
9664       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9665                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9666       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9667                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9668       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9669     }
9670     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9671                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9672     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9673   }
9674 
9675   if (Subtarget.hasP9Altivec()) {
9676     SDValue NewISDNode;
9677     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9678       return NewISDNode;
9679 
9680     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9681       return NewISDNode;
9682   }
9683 
9684   if (Subtarget.hasVSX() &&
9685       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9686     if (Swap)
9687       std::swap(V1, V2);
9688     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9689     SDValue Conv2 =
9690         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9691 
9692     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9693                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9694     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9695   }
9696 
9697   if (Subtarget.hasVSX() &&
9698     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9699     if (Swap)
9700       std::swap(V1, V2);
9701     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9702     SDValue Conv2 =
9703         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9704 
9705     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9706                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9707     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9708   }
9709 
9710   if (Subtarget.hasP9Vector()) {
9711      if (PPC::isXXBRHShuffleMask(SVOp)) {
9712       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9713       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9714       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9715     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9716       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9717       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9718       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9719     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9720       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9721       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9722       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9723     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9724       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9725       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9726       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9727     }
9728   }
9729 
9730   if (Subtarget.hasVSX()) {
9731     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9732       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9733 
9734       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9735       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9736                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9737       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9738     }
9739 
9740     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9741     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9742       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9743       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9744       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9745     }
9746   }
9747 
9748   if (Subtarget.hasQPX()) {
9749     if (VT.getVectorNumElements() != 4)
9750       return SDValue();
9751 
9752     if (V2.isUndef()) V2 = V1;
9753 
9754     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9755     if (AlignIdx != -1) {
9756       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9757                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9758     } else if (SVOp->isSplat()) {
9759       int SplatIdx = SVOp->getSplatIndex();
9760       if (SplatIdx >= 4) {
9761         std::swap(V1, V2);
9762         SplatIdx -= 4;
9763       }
9764 
9765       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9766                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9767     }
9768 
9769     // Lower this into a qvgpci/qvfperm pair.
9770 
9771     // Compute the qvgpci literal
9772     unsigned idx = 0;
9773     for (unsigned i = 0; i < 4; ++i) {
9774       int m = SVOp->getMaskElt(i);
9775       unsigned mm = m >= 0 ? (unsigned) m : i;
9776       idx |= mm << (3-i)*3;
9777     }
9778 
9779     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9780                              DAG.getConstant(idx, dl, MVT::i32));
9781     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9782   }
9783 
9784   // Cases that are handled by instructions that take permute immediates
9785   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9786   // selected by the instruction selector.
9787   if (V2.isUndef()) {
9788     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9789         PPC::isSplatShuffleMask(SVOp, 2) ||
9790         PPC::isSplatShuffleMask(SVOp, 4) ||
9791         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9792         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9793         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9794         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9795         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9796         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9797         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9798         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9799         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9800         (Subtarget.hasP8Altivec() && (
9801          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9802          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9803          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9804       return Op;
9805     }
9806   }
9807 
9808   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9809   // and produce a fixed permutation.  If any of these match, do not lower to
9810   // VPERM.
9811   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9812   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9813       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9814       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9815       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9816       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9817       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9818       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9819       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9820       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9821       (Subtarget.hasP8Altivec() && (
9822        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9823        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9824        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9825     return Op;
9826 
9827   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9828   // perfect shuffle table to emit an optimal matching sequence.
9829   ArrayRef<int> PermMask = SVOp->getMask();
9830 
9831   unsigned PFIndexes[4];
9832   bool isFourElementShuffle = true;
9833   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9834     unsigned EltNo = 8;   // Start out undef.
9835     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9836       if (PermMask[i*4+j] < 0)
9837         continue;   // Undef, ignore it.
9838 
9839       unsigned ByteSource = PermMask[i*4+j];
9840       if ((ByteSource & 3) != j) {
9841         isFourElementShuffle = false;
9842         break;
9843       }
9844 
9845       if (EltNo == 8) {
9846         EltNo = ByteSource/4;
9847       } else if (EltNo != ByteSource/4) {
9848         isFourElementShuffle = false;
9849         break;
9850       }
9851     }
9852     PFIndexes[i] = EltNo;
9853   }
9854 
9855   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9856   // perfect shuffle vector to determine if it is cost effective to do this as
9857   // discrete instructions, or whether we should use a vperm.
9858   // For now, we skip this for little endian until such time as we have a
9859   // little-endian perfect shuffle table.
9860   if (isFourElementShuffle && !isLittleEndian) {
9861     // Compute the index in the perfect shuffle table.
9862     unsigned PFTableIndex =
9863       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9864 
9865     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9866     unsigned Cost  = (PFEntry >> 30);
9867 
9868     // Determining when to avoid vperm is tricky.  Many things affect the cost
9869     // of vperm, particularly how many times the perm mask needs to be computed.
9870     // For example, if the perm mask can be hoisted out of a loop or is already
9871     // used (perhaps because there are multiple permutes with the same shuffle
9872     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9873     // the loop requires an extra register.
9874     //
9875     // As a compromise, we only emit discrete instructions if the shuffle can be
9876     // generated in 3 or fewer operations.  When we have loop information
9877     // available, if this block is within a loop, we should avoid using vperm
9878     // for 3-operation perms and use a constant pool load instead.
9879     if (Cost < 3)
9880       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9881   }
9882 
9883   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9884   // vector that will get spilled to the constant pool.
9885   if (V2.isUndef()) V2 = V1;
9886 
9887   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9888   // that it is in input element units, not in bytes.  Convert now.
9889 
9890   // For little endian, the order of the input vectors is reversed, and
9891   // the permutation mask is complemented with respect to 31.  This is
9892   // necessary to produce proper semantics with the big-endian-biased vperm
9893   // instruction.
9894   EVT EltVT = V1.getValueType().getVectorElementType();
9895   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9896 
9897   SmallVector<SDValue, 16> ResultMask;
9898   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9899     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9900 
9901     for (unsigned j = 0; j != BytesPerElement; ++j)
9902       if (isLittleEndian)
9903         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9904                                              dl, MVT::i32));
9905       else
9906         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9907                                              MVT::i32));
9908   }
9909 
9910   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9911   if (isLittleEndian)
9912     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9913                        V2, V1, VPermMask);
9914   else
9915     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9916                        V1, V2, VPermMask);
9917 }
9918 
9919 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9920 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9921 /// information about the intrinsic.
9922 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9923                                  bool &isDot, const PPCSubtarget &Subtarget) {
9924   unsigned IntrinsicID =
9925       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9926   CompareOpc = -1;
9927   isDot = false;
9928   switch (IntrinsicID) {
9929   default:
9930     return false;
9931   // Comparison predicates.
9932   case Intrinsic::ppc_altivec_vcmpbfp_p:
9933     CompareOpc = 966;
9934     isDot = true;
9935     break;
9936   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9937     CompareOpc = 198;
9938     isDot = true;
9939     break;
9940   case Intrinsic::ppc_altivec_vcmpequb_p:
9941     CompareOpc = 6;
9942     isDot = true;
9943     break;
9944   case Intrinsic::ppc_altivec_vcmpequh_p:
9945     CompareOpc = 70;
9946     isDot = true;
9947     break;
9948   case Intrinsic::ppc_altivec_vcmpequw_p:
9949     CompareOpc = 134;
9950     isDot = true;
9951     break;
9952   case Intrinsic::ppc_altivec_vcmpequd_p:
9953     if (Subtarget.hasP8Altivec()) {
9954       CompareOpc = 199;
9955       isDot = true;
9956     } else
9957       return false;
9958     break;
9959   case Intrinsic::ppc_altivec_vcmpneb_p:
9960   case Intrinsic::ppc_altivec_vcmpneh_p:
9961   case Intrinsic::ppc_altivec_vcmpnew_p:
9962   case Intrinsic::ppc_altivec_vcmpnezb_p:
9963   case Intrinsic::ppc_altivec_vcmpnezh_p:
9964   case Intrinsic::ppc_altivec_vcmpnezw_p:
9965     if (Subtarget.hasP9Altivec()) {
9966       switch (IntrinsicID) {
9967       default:
9968         llvm_unreachable("Unknown comparison intrinsic.");
9969       case Intrinsic::ppc_altivec_vcmpneb_p:
9970         CompareOpc = 7;
9971         break;
9972       case Intrinsic::ppc_altivec_vcmpneh_p:
9973         CompareOpc = 71;
9974         break;
9975       case Intrinsic::ppc_altivec_vcmpnew_p:
9976         CompareOpc = 135;
9977         break;
9978       case Intrinsic::ppc_altivec_vcmpnezb_p:
9979         CompareOpc = 263;
9980         break;
9981       case Intrinsic::ppc_altivec_vcmpnezh_p:
9982         CompareOpc = 327;
9983         break;
9984       case Intrinsic::ppc_altivec_vcmpnezw_p:
9985         CompareOpc = 391;
9986         break;
9987       }
9988       isDot = true;
9989     } else
9990       return false;
9991     break;
9992   case Intrinsic::ppc_altivec_vcmpgefp_p:
9993     CompareOpc = 454;
9994     isDot = true;
9995     break;
9996   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9997     CompareOpc = 710;
9998     isDot = true;
9999     break;
10000   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10001     CompareOpc = 774;
10002     isDot = true;
10003     break;
10004   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10005     CompareOpc = 838;
10006     isDot = true;
10007     break;
10008   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10009     CompareOpc = 902;
10010     isDot = true;
10011     break;
10012   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10013     if (Subtarget.hasP8Altivec()) {
10014       CompareOpc = 967;
10015       isDot = true;
10016     } else
10017       return false;
10018     break;
10019   case Intrinsic::ppc_altivec_vcmpgtub_p:
10020     CompareOpc = 518;
10021     isDot = true;
10022     break;
10023   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10024     CompareOpc = 582;
10025     isDot = true;
10026     break;
10027   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10028     CompareOpc = 646;
10029     isDot = true;
10030     break;
10031   case Intrinsic::ppc_altivec_vcmpgtud_p:
10032     if (Subtarget.hasP8Altivec()) {
10033       CompareOpc = 711;
10034       isDot = true;
10035     } else
10036       return false;
10037     break;
10038 
10039   // VSX predicate comparisons use the same infrastructure
10040   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10041   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10042   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10043   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10044   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10045   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10046     if (Subtarget.hasVSX()) {
10047       switch (IntrinsicID) {
10048       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10049         CompareOpc = 99;
10050         break;
10051       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10052         CompareOpc = 115;
10053         break;
10054       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10055         CompareOpc = 107;
10056         break;
10057       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10058         CompareOpc = 67;
10059         break;
10060       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10061         CompareOpc = 83;
10062         break;
10063       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10064         CompareOpc = 75;
10065         break;
10066       }
10067       isDot = true;
10068     } else
10069       return false;
10070     break;
10071 
10072   // Normal Comparisons.
10073   case Intrinsic::ppc_altivec_vcmpbfp:
10074     CompareOpc = 966;
10075     break;
10076   case Intrinsic::ppc_altivec_vcmpeqfp:
10077     CompareOpc = 198;
10078     break;
10079   case Intrinsic::ppc_altivec_vcmpequb:
10080     CompareOpc = 6;
10081     break;
10082   case Intrinsic::ppc_altivec_vcmpequh:
10083     CompareOpc = 70;
10084     break;
10085   case Intrinsic::ppc_altivec_vcmpequw:
10086     CompareOpc = 134;
10087     break;
10088   case Intrinsic::ppc_altivec_vcmpequd:
10089     if (Subtarget.hasP8Altivec())
10090       CompareOpc = 199;
10091     else
10092       return false;
10093     break;
10094   case Intrinsic::ppc_altivec_vcmpneb:
10095   case Intrinsic::ppc_altivec_vcmpneh:
10096   case Intrinsic::ppc_altivec_vcmpnew:
10097   case Intrinsic::ppc_altivec_vcmpnezb:
10098   case Intrinsic::ppc_altivec_vcmpnezh:
10099   case Intrinsic::ppc_altivec_vcmpnezw:
10100     if (Subtarget.hasP9Altivec())
10101       switch (IntrinsicID) {
10102       default:
10103         llvm_unreachable("Unknown comparison intrinsic.");
10104       case Intrinsic::ppc_altivec_vcmpneb:
10105         CompareOpc = 7;
10106         break;
10107       case Intrinsic::ppc_altivec_vcmpneh:
10108         CompareOpc = 71;
10109         break;
10110       case Intrinsic::ppc_altivec_vcmpnew:
10111         CompareOpc = 135;
10112         break;
10113       case Intrinsic::ppc_altivec_vcmpnezb:
10114         CompareOpc = 263;
10115         break;
10116       case Intrinsic::ppc_altivec_vcmpnezh:
10117         CompareOpc = 327;
10118         break;
10119       case Intrinsic::ppc_altivec_vcmpnezw:
10120         CompareOpc = 391;
10121         break;
10122       }
10123     else
10124       return false;
10125     break;
10126   case Intrinsic::ppc_altivec_vcmpgefp:
10127     CompareOpc = 454;
10128     break;
10129   case Intrinsic::ppc_altivec_vcmpgtfp:
10130     CompareOpc = 710;
10131     break;
10132   case Intrinsic::ppc_altivec_vcmpgtsb:
10133     CompareOpc = 774;
10134     break;
10135   case Intrinsic::ppc_altivec_vcmpgtsh:
10136     CompareOpc = 838;
10137     break;
10138   case Intrinsic::ppc_altivec_vcmpgtsw:
10139     CompareOpc = 902;
10140     break;
10141   case Intrinsic::ppc_altivec_vcmpgtsd:
10142     if (Subtarget.hasP8Altivec())
10143       CompareOpc = 967;
10144     else
10145       return false;
10146     break;
10147   case Intrinsic::ppc_altivec_vcmpgtub:
10148     CompareOpc = 518;
10149     break;
10150   case Intrinsic::ppc_altivec_vcmpgtuh:
10151     CompareOpc = 582;
10152     break;
10153   case Intrinsic::ppc_altivec_vcmpgtuw:
10154     CompareOpc = 646;
10155     break;
10156   case Intrinsic::ppc_altivec_vcmpgtud:
10157     if (Subtarget.hasP8Altivec())
10158       CompareOpc = 711;
10159     else
10160       return false;
10161     break;
10162   }
10163   return true;
10164 }
10165 
10166 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10167 /// lower, do it, otherwise return null.
10168 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10169                                                    SelectionDAG &DAG) const {
10170   unsigned IntrinsicID =
10171     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10172 
10173   SDLoc dl(Op);
10174 
10175   if (IntrinsicID == Intrinsic::thread_pointer) {
10176     // Reads the thread pointer register, used for __builtin_thread_pointer.
10177     if (Subtarget.isPPC64())
10178       return DAG.getRegister(PPC::X13, MVT::i64);
10179     return DAG.getRegister(PPC::R2, MVT::i32);
10180   }
10181 
10182   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10183   // opcode number of the comparison.
10184   int CompareOpc;
10185   bool isDot;
10186   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10187     return SDValue();    // Don't custom lower most intrinsics.
10188 
10189   // If this is a non-dot comparison, make the VCMP node and we are done.
10190   if (!isDot) {
10191     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10192                               Op.getOperand(1), Op.getOperand(2),
10193                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10194     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10195   }
10196 
10197   // Create the PPCISD altivec 'dot' comparison node.
10198   SDValue Ops[] = {
10199     Op.getOperand(2),  // LHS
10200     Op.getOperand(3),  // RHS
10201     DAG.getConstant(CompareOpc, dl, MVT::i32)
10202   };
10203   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10204   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10205 
10206   // Now that we have the comparison, emit a copy from the CR to a GPR.
10207   // This is flagged to the above dot comparison.
10208   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10209                                 DAG.getRegister(PPC::CR6, MVT::i32),
10210                                 CompNode.getValue(1));
10211 
10212   // Unpack the result based on how the target uses it.
10213   unsigned BitNo;   // Bit # of CR6.
10214   bool InvertBit;   // Invert result?
10215   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10216   default:  // Can't happen, don't crash on invalid number though.
10217   case 0:   // Return the value of the EQ bit of CR6.
10218     BitNo = 0; InvertBit = false;
10219     break;
10220   case 1:   // Return the inverted value of the EQ bit of CR6.
10221     BitNo = 0; InvertBit = true;
10222     break;
10223   case 2:   // Return the value of the LT bit of CR6.
10224     BitNo = 2; InvertBit = false;
10225     break;
10226   case 3:   // Return the inverted value of the LT bit of CR6.
10227     BitNo = 2; InvertBit = true;
10228     break;
10229   }
10230 
10231   // Shift the bit into the low position.
10232   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10233                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10234   // Isolate the bit.
10235   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10236                       DAG.getConstant(1, dl, MVT::i32));
10237 
10238   // If we are supposed to, toggle the bit.
10239   if (InvertBit)
10240     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10241                         DAG.getConstant(1, dl, MVT::i32));
10242   return Flags;
10243 }
10244 
10245 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10246                                                SelectionDAG &DAG) const {
10247   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10248   // the beginning of the argument list.
10249   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10250   SDLoc DL(Op);
10251   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10252   case Intrinsic::ppc_cfence: {
10253     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10254     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10255     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10256                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10257                                                   Op.getOperand(ArgStart + 1)),
10258                                       Op.getOperand(0)),
10259                    0);
10260   }
10261   default:
10262     break;
10263   }
10264   return SDValue();
10265 }
10266 
10267 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10268   // Check for a DIV with the same operands as this REM.
10269   for (auto UI : Op.getOperand(1)->uses()) {
10270     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10271         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10272       if (UI->getOperand(0) == Op.getOperand(0) &&
10273           UI->getOperand(1) == Op.getOperand(1))
10274         return SDValue();
10275   }
10276   return Op;
10277 }
10278 
10279 // Lower scalar BSWAP64 to xxbrd.
10280 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10281   SDLoc dl(Op);
10282   // MTVSRDD
10283   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10284                    Op.getOperand(0));
10285   // XXBRD
10286   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10287   // MFVSRD
10288   int VectorIndex = 0;
10289   if (Subtarget.isLittleEndian())
10290     VectorIndex = 1;
10291   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10292                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10293   return Op;
10294 }
10295 
10296 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10297 // compared to a value that is atomically loaded (atomic loads zero-extend).
10298 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10299                                                 SelectionDAG &DAG) const {
10300   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10301          "Expecting an atomic compare-and-swap here.");
10302   SDLoc dl(Op);
10303   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10304   EVT MemVT = AtomicNode->getMemoryVT();
10305   if (MemVT.getSizeInBits() >= 32)
10306     return Op;
10307 
10308   SDValue CmpOp = Op.getOperand(2);
10309   // If this is already correctly zero-extended, leave it alone.
10310   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10311   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10312     return Op;
10313 
10314   // Clear the high bits of the compare operand.
10315   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10316   SDValue NewCmpOp =
10317     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10318                 DAG.getConstant(MaskVal, dl, MVT::i32));
10319 
10320   // Replace the existing compare operand with the properly zero-extended one.
10321   SmallVector<SDValue, 4> Ops;
10322   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10323     Ops.push_back(AtomicNode->getOperand(i));
10324   Ops[2] = NewCmpOp;
10325   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10326   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10327   auto NodeTy =
10328     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10329   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10330 }
10331 
10332 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10333                                                  SelectionDAG &DAG) const {
10334   SDLoc dl(Op);
10335   // Create a stack slot that is 16-byte aligned.
10336   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10337   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10338   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10339   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10340 
10341   // Store the input value into Value#0 of the stack slot.
10342   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10343                                MachinePointerInfo());
10344   // Load it out.
10345   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10346 }
10347 
10348 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10349                                                   SelectionDAG &DAG) const {
10350   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10351          "Should only be called for ISD::INSERT_VECTOR_ELT");
10352 
10353   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10354   // We have legal lowering for constant indices but not for variable ones.
10355   if (!C)
10356     return SDValue();
10357 
10358   EVT VT = Op.getValueType();
10359   SDLoc dl(Op);
10360   SDValue V1 = Op.getOperand(0);
10361   SDValue V2 = Op.getOperand(1);
10362   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10363   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10364     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10365     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10366     unsigned InsertAtElement = C->getZExtValue();
10367     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10368     if (Subtarget.isLittleEndian()) {
10369       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10370     }
10371     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10372                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10373   }
10374   return Op;
10375 }
10376 
10377 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10378                                                    SelectionDAG &DAG) const {
10379   SDLoc dl(Op);
10380   SDNode *N = Op.getNode();
10381 
10382   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10383          "Unknown extract_vector_elt type");
10384 
10385   SDValue Value = N->getOperand(0);
10386 
10387   // The first part of this is like the store lowering except that we don't
10388   // need to track the chain.
10389 
10390   // The values are now known to be -1 (false) or 1 (true). To convert this
10391   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10392   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10393   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10394 
10395   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10396   // understand how to form the extending load.
10397   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10398 
10399   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10400 
10401   // Now convert to an integer and store.
10402   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10403     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10404     Value);
10405 
10406   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10407   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10408   MachinePointerInfo PtrInfo =
10409       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10410   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10411   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10412 
10413   SDValue StoreChain = DAG.getEntryNode();
10414   SDValue Ops[] = {StoreChain,
10415                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10416                    Value, FIdx};
10417   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10418 
10419   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10420     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10421 
10422   // Extract the value requested.
10423   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10424   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10425   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10426 
10427   SDValue IntVal =
10428       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10429 
10430   if (!Subtarget.useCRBits())
10431     return IntVal;
10432 
10433   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10434 }
10435 
10436 /// Lowering for QPX v4i1 loads
10437 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10438                                            SelectionDAG &DAG) const {
10439   SDLoc dl(Op);
10440   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10441   SDValue LoadChain = LN->getChain();
10442   SDValue BasePtr = LN->getBasePtr();
10443 
10444   if (Op.getValueType() == MVT::v4f64 ||
10445       Op.getValueType() == MVT::v4f32) {
10446     EVT MemVT = LN->getMemoryVT();
10447     unsigned Alignment = LN->getAlignment();
10448 
10449     // If this load is properly aligned, then it is legal.
10450     if (Alignment >= MemVT.getStoreSize())
10451       return Op;
10452 
10453     EVT ScalarVT = Op.getValueType().getScalarType(),
10454         ScalarMemVT = MemVT.getScalarType();
10455     unsigned Stride = ScalarMemVT.getStoreSize();
10456 
10457     SDValue Vals[4], LoadChains[4];
10458     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10459       SDValue Load;
10460       if (ScalarVT != ScalarMemVT)
10461         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10462                               BasePtr,
10463                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10464                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10465                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10466       else
10467         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10468                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10469                            MinAlign(Alignment, Idx * Stride),
10470                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10471 
10472       if (Idx == 0 && LN->isIndexed()) {
10473         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10474                "Unknown addressing mode on vector load");
10475         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10476                                   LN->getAddressingMode());
10477       }
10478 
10479       Vals[Idx] = Load;
10480       LoadChains[Idx] = Load.getValue(1);
10481 
10482       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10483                             DAG.getConstant(Stride, dl,
10484                                             BasePtr.getValueType()));
10485     }
10486 
10487     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10488     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10489 
10490     if (LN->isIndexed()) {
10491       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10492       return DAG.getMergeValues(RetOps, dl);
10493     }
10494 
10495     SDValue RetOps[] = { Value, TF };
10496     return DAG.getMergeValues(RetOps, dl);
10497   }
10498 
10499   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10500   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10501 
10502   // To lower v4i1 from a byte array, we load the byte elements of the
10503   // vector and then reuse the BUILD_VECTOR logic.
10504 
10505   SDValue VectElmts[4], VectElmtChains[4];
10506   for (unsigned i = 0; i < 4; ++i) {
10507     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10508     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10509 
10510     VectElmts[i] = DAG.getExtLoad(
10511         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10512         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10513         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10514     VectElmtChains[i] = VectElmts[i].getValue(1);
10515   }
10516 
10517   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10518   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10519 
10520   SDValue RVals[] = { Value, LoadChain };
10521   return DAG.getMergeValues(RVals, dl);
10522 }
10523 
10524 /// Lowering for QPX v4i1 stores
10525 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10526                                             SelectionDAG &DAG) const {
10527   SDLoc dl(Op);
10528   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10529   SDValue StoreChain = SN->getChain();
10530   SDValue BasePtr = SN->getBasePtr();
10531   SDValue Value = SN->getValue();
10532 
10533   if (Value.getValueType() == MVT::v4f64 ||
10534       Value.getValueType() == MVT::v4f32) {
10535     EVT MemVT = SN->getMemoryVT();
10536     unsigned Alignment = SN->getAlignment();
10537 
10538     // If this store is properly aligned, then it is legal.
10539     if (Alignment >= MemVT.getStoreSize())
10540       return Op;
10541 
10542     EVT ScalarVT = Value.getValueType().getScalarType(),
10543         ScalarMemVT = MemVT.getScalarType();
10544     unsigned Stride = ScalarMemVT.getStoreSize();
10545 
10546     SDValue Stores[4];
10547     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10548       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10549                                DAG.getVectorIdxConstant(Idx, dl));
10550       SDValue Store;
10551       if (ScalarVT != ScalarMemVT)
10552         Store =
10553             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10554                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10555                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10556                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10557       else
10558         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10559                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10560                              MinAlign(Alignment, Idx * Stride),
10561                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10562 
10563       if (Idx == 0 && SN->isIndexed()) {
10564         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10565                "Unknown addressing mode on vector store");
10566         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10567                                     SN->getAddressingMode());
10568       }
10569 
10570       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10571                             DAG.getConstant(Stride, dl,
10572                                             BasePtr.getValueType()));
10573       Stores[Idx] = Store;
10574     }
10575 
10576     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10577 
10578     if (SN->isIndexed()) {
10579       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10580       return DAG.getMergeValues(RetOps, dl);
10581     }
10582 
10583     return TF;
10584   }
10585 
10586   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10587   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10588 
10589   // The values are now known to be -1 (false) or 1 (true). To convert this
10590   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10591   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10592   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10593 
10594   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10595   // understand how to form the extending load.
10596   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10597 
10598   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10599 
10600   // Now convert to an integer and store.
10601   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10602     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10603     Value);
10604 
10605   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10606   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10607   MachinePointerInfo PtrInfo =
10608       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10609   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10610   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10611 
10612   SDValue Ops[] = {StoreChain,
10613                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10614                    Value, FIdx};
10615   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10616 
10617   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10618     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10619 
10620   // Move data into the byte array.
10621   SDValue Loads[4], LoadChains[4];
10622   for (unsigned i = 0; i < 4; ++i) {
10623     unsigned Offset = 4*i;
10624     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10625     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10626 
10627     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10628                            PtrInfo.getWithOffset(Offset));
10629     LoadChains[i] = Loads[i].getValue(1);
10630   }
10631 
10632   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10633 
10634   SDValue Stores[4];
10635   for (unsigned i = 0; i < 4; ++i) {
10636     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10637     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10638 
10639     Stores[i] = DAG.getTruncStore(
10640         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10641         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10642         SN->getAAInfo());
10643   }
10644 
10645   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10646 
10647   return StoreChain;
10648 }
10649 
10650 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10651   SDLoc dl(Op);
10652   if (Op.getValueType() == MVT::v4i32) {
10653     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10654 
10655     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10656     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10657 
10658     SDValue RHSSwap =   // = vrlw RHS, 16
10659       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10660 
10661     // Shrinkify inputs to v8i16.
10662     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10663     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10664     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10665 
10666     // Low parts multiplied together, generating 32-bit results (we ignore the
10667     // top parts).
10668     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10669                                         LHS, RHS, DAG, dl, MVT::v4i32);
10670 
10671     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10672                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10673     // Shift the high parts up 16 bits.
10674     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10675                               Neg16, DAG, dl);
10676     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10677   } else if (Op.getValueType() == MVT::v16i8) {
10678     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10679     bool isLittleEndian = Subtarget.isLittleEndian();
10680 
10681     // Multiply the even 8-bit parts, producing 16-bit sums.
10682     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10683                                            LHS, RHS, DAG, dl, MVT::v8i16);
10684     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10685 
10686     // Multiply the odd 8-bit parts, producing 16-bit sums.
10687     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10688                                           LHS, RHS, DAG, dl, MVT::v8i16);
10689     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10690 
10691     // Merge the results together.  Because vmuleub and vmuloub are
10692     // instructions with a big-endian bias, we must reverse the
10693     // element numbering and reverse the meaning of "odd" and "even"
10694     // when generating little endian code.
10695     int Ops[16];
10696     for (unsigned i = 0; i != 8; ++i) {
10697       if (isLittleEndian) {
10698         Ops[i*2  ] = 2*i;
10699         Ops[i*2+1] = 2*i+16;
10700       } else {
10701         Ops[i*2  ] = 2*i+1;
10702         Ops[i*2+1] = 2*i+1+16;
10703       }
10704     }
10705     if (isLittleEndian)
10706       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10707     else
10708       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10709   } else {
10710     llvm_unreachable("Unknown mul to lower!");
10711   }
10712 }
10713 
10714 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10715 
10716   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10717 
10718   EVT VT = Op.getValueType();
10719   assert(VT.isVector() &&
10720          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10721   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10722           VT == MVT::v16i8) &&
10723          "Unexpected vector element type!");
10724   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10725          "Current subtarget doesn't support smax v2i64!");
10726 
10727   // For vector abs, it can be lowered to:
10728   // abs x
10729   // ==>
10730   // y = -x
10731   // smax(x, y)
10732 
10733   SDLoc dl(Op);
10734   SDValue X = Op.getOperand(0);
10735   SDValue Zero = DAG.getConstant(0, dl, VT);
10736   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10737 
10738   // SMAX patch https://reviews.llvm.org/D47332
10739   // hasn't landed yet, so use intrinsic first here.
10740   // TODO: Should use SMAX directly once SMAX patch landed
10741   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10742   if (VT == MVT::v2i64)
10743     BifID = Intrinsic::ppc_altivec_vmaxsd;
10744   else if (VT == MVT::v8i16)
10745     BifID = Intrinsic::ppc_altivec_vmaxsh;
10746   else if (VT == MVT::v16i8)
10747     BifID = Intrinsic::ppc_altivec_vmaxsb;
10748 
10749   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10750 }
10751 
10752 // Custom lowering for fpext vf32 to v2f64
10753 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10754 
10755   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10756          "Should only be called for ISD::FP_EXTEND");
10757 
10758   // We only want to custom lower an extend from v2f32 to v2f64.
10759   if (Op.getValueType() != MVT::v2f64 ||
10760       Op.getOperand(0).getValueType() != MVT::v2f32)
10761     return SDValue();
10762 
10763   SDLoc dl(Op);
10764   SDValue Op0 = Op.getOperand(0);
10765 
10766   switch (Op0.getOpcode()) {
10767   default:
10768     return SDValue();
10769   case ISD::EXTRACT_SUBVECTOR: {
10770     assert(Op0.getNumOperands() == 2 &&
10771            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10772            "Node should have 2 operands with second one being a constant!");
10773 
10774     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10775       return SDValue();
10776 
10777     // Custom lower is only done for high or low doubleword.
10778     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10779     if (Idx % 2 != 0)
10780       return SDValue();
10781 
10782     // Since input is v4f32, at this point Idx is either 0 or 2.
10783     // Shift to get the doubleword position we want.
10784     int DWord = Idx >> 1;
10785 
10786     // High and low word positions are different on little endian.
10787     if (Subtarget.isLittleEndian())
10788       DWord ^= 0x1;
10789 
10790     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10791                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10792   }
10793   case ISD::FADD:
10794   case ISD::FMUL:
10795   case ISD::FSUB: {
10796     SDValue NewLoad[2];
10797     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10798       // Ensure both input are loads.
10799       SDValue LdOp = Op0.getOperand(i);
10800       if (LdOp.getOpcode() != ISD::LOAD)
10801         return SDValue();
10802       // Generate new load node.
10803       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10804       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10805       NewLoad[i] = DAG.getMemIntrinsicNode(
10806           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10807           LD->getMemoryVT(), LD->getMemOperand());
10808     }
10809     SDValue NewOp =
10810         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10811                     NewLoad[1], Op0.getNode()->getFlags());
10812     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10813                        DAG.getConstant(0, dl, MVT::i32));
10814   }
10815   case ISD::LOAD: {
10816     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10817     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10818     SDValue NewLd = DAG.getMemIntrinsicNode(
10819         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10820         LD->getMemoryVT(), LD->getMemOperand());
10821     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10822                        DAG.getConstant(0, dl, MVT::i32));
10823   }
10824   }
10825   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10826 }
10827 
10828 /// LowerOperation - Provide custom lowering hooks for some operations.
10829 ///
10830 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10831   switch (Op.getOpcode()) {
10832   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10833   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10834   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10835   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10836   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10837   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10838   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10839   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10840   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10841 
10842   // Variable argument lowering.
10843   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10844   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10845   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10846 
10847   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10848   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10849   case ISD::GET_DYNAMIC_AREA_OFFSET:
10850     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10851 
10852   // Exception handling lowering.
10853   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10854   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10855   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10856 
10857   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10858   case ISD::STORE:              return LowerSTORE(Op, DAG);
10859   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10860   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10861   case ISD::FP_TO_UINT:
10862   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10863   case ISD::UINT_TO_FP:
10864   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10865   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10866 
10867   // Lower 64-bit shifts.
10868   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10869   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10870   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10871 
10872   // Vector-related lowering.
10873   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10874   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10875   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10876   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10877   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10878   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10879   case ISD::MUL:                return LowerMUL(Op, DAG);
10880   case ISD::ABS:                return LowerABS(Op, DAG);
10881   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10882 
10883   // For counter-based loop handling.
10884   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10885 
10886   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10887 
10888   // Frame & Return address.
10889   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10890   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10891 
10892   case ISD::INTRINSIC_VOID:
10893     return LowerINTRINSIC_VOID(Op, DAG);
10894   case ISD::SREM:
10895   case ISD::UREM:
10896     return LowerREM(Op, DAG);
10897   case ISD::BSWAP:
10898     return LowerBSWAP(Op, DAG);
10899   case ISD::ATOMIC_CMP_SWAP:
10900     return LowerATOMIC_CMP_SWAP(Op, DAG);
10901   }
10902 }
10903 
10904 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10905                                            SmallVectorImpl<SDValue>&Results,
10906                                            SelectionDAG &DAG) const {
10907   SDLoc dl(N);
10908   switch (N->getOpcode()) {
10909   default:
10910     llvm_unreachable("Do not know how to custom type legalize this operation!");
10911   case ISD::READCYCLECOUNTER: {
10912     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10913     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10914 
10915     Results.push_back(
10916         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10917     Results.push_back(RTB.getValue(2));
10918     break;
10919   }
10920   case ISD::INTRINSIC_W_CHAIN: {
10921     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10922         Intrinsic::loop_decrement)
10923       break;
10924 
10925     assert(N->getValueType(0) == MVT::i1 &&
10926            "Unexpected result type for CTR decrement intrinsic");
10927     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10928                                  N->getValueType(0));
10929     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10930     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10931                                  N->getOperand(1));
10932 
10933     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10934     Results.push_back(NewInt.getValue(1));
10935     break;
10936   }
10937   case ISD::VAARG: {
10938     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10939       return;
10940 
10941     EVT VT = N->getValueType(0);
10942 
10943     if (VT == MVT::i64) {
10944       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10945 
10946       Results.push_back(NewNode);
10947       Results.push_back(NewNode.getValue(1));
10948     }
10949     return;
10950   }
10951   case ISD::FP_TO_SINT:
10952   case ISD::FP_TO_UINT:
10953     // LowerFP_TO_INT() can only handle f32 and f64.
10954     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10955       return;
10956     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10957     return;
10958   case ISD::TRUNCATE: {
10959     EVT TrgVT = N->getValueType(0);
10960     EVT OpVT = N->getOperand(0).getValueType();
10961     if (TrgVT.isVector() &&
10962         isOperationCustom(N->getOpcode(), TrgVT) &&
10963         OpVT.getSizeInBits() <= 128 &&
10964         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10965       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10966     return;
10967   }
10968   case ISD::BITCAST:
10969     // Don't handle bitcast here.
10970     return;
10971   }
10972 }
10973 
10974 //===----------------------------------------------------------------------===//
10975 //  Other Lowering Code
10976 //===----------------------------------------------------------------------===//
10977 
10978 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10979   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10980   Function *Func = Intrinsic::getDeclaration(M, Id);
10981   return Builder.CreateCall(Func, {});
10982 }
10983 
10984 // The mappings for emitLeading/TrailingFence is taken from
10985 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10986 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10987                                                  Instruction *Inst,
10988                                                  AtomicOrdering Ord) const {
10989   if (Ord == AtomicOrdering::SequentiallyConsistent)
10990     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10991   if (isReleaseOrStronger(Ord))
10992     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10993   return nullptr;
10994 }
10995 
10996 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10997                                                   Instruction *Inst,
10998                                                   AtomicOrdering Ord) const {
10999   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11000     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11001     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11002     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11003     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11004       return Builder.CreateCall(
11005           Intrinsic::getDeclaration(
11006               Builder.GetInsertBlock()->getParent()->getParent(),
11007               Intrinsic::ppc_cfence, {Inst->getType()}),
11008           {Inst});
11009     // FIXME: Can use isync for rmw operation.
11010     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11011   }
11012   return nullptr;
11013 }
11014 
11015 MachineBasicBlock *
11016 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11017                                     unsigned AtomicSize,
11018                                     unsigned BinOpcode,
11019                                     unsigned CmpOpcode,
11020                                     unsigned CmpPred) const {
11021   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11022   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11023 
11024   auto LoadMnemonic = PPC::LDARX;
11025   auto StoreMnemonic = PPC::STDCX;
11026   switch (AtomicSize) {
11027   default:
11028     llvm_unreachable("Unexpected size of atomic entity");
11029   case 1:
11030     LoadMnemonic = PPC::LBARX;
11031     StoreMnemonic = PPC::STBCX;
11032     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11033     break;
11034   case 2:
11035     LoadMnemonic = PPC::LHARX;
11036     StoreMnemonic = PPC::STHCX;
11037     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11038     break;
11039   case 4:
11040     LoadMnemonic = PPC::LWARX;
11041     StoreMnemonic = PPC::STWCX;
11042     break;
11043   case 8:
11044     LoadMnemonic = PPC::LDARX;
11045     StoreMnemonic = PPC::STDCX;
11046     break;
11047   }
11048 
11049   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11050   MachineFunction *F = BB->getParent();
11051   MachineFunction::iterator It = ++BB->getIterator();
11052 
11053   Register dest = MI.getOperand(0).getReg();
11054   Register ptrA = MI.getOperand(1).getReg();
11055   Register ptrB = MI.getOperand(2).getReg();
11056   Register incr = MI.getOperand(3).getReg();
11057   DebugLoc dl = MI.getDebugLoc();
11058 
11059   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11060   MachineBasicBlock *loop2MBB =
11061     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11062   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11063   F->insert(It, loopMBB);
11064   if (CmpOpcode)
11065     F->insert(It, loop2MBB);
11066   F->insert(It, exitMBB);
11067   exitMBB->splice(exitMBB->begin(), BB,
11068                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11069   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11070 
11071   MachineRegisterInfo &RegInfo = F->getRegInfo();
11072   Register TmpReg = (!BinOpcode) ? incr :
11073     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11074                                            : &PPC::GPRCRegClass);
11075 
11076   //  thisMBB:
11077   //   ...
11078   //   fallthrough --> loopMBB
11079   BB->addSuccessor(loopMBB);
11080 
11081   //  loopMBB:
11082   //   l[wd]arx dest, ptr
11083   //   add r0, dest, incr
11084   //   st[wd]cx. r0, ptr
11085   //   bne- loopMBB
11086   //   fallthrough --> exitMBB
11087 
11088   // For max/min...
11089   //  loopMBB:
11090   //   l[wd]arx dest, ptr
11091   //   cmpl?[wd] incr, dest
11092   //   bgt exitMBB
11093   //  loop2MBB:
11094   //   st[wd]cx. dest, ptr
11095   //   bne- loopMBB
11096   //   fallthrough --> exitMBB
11097 
11098   BB = loopMBB;
11099   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11100     .addReg(ptrA).addReg(ptrB);
11101   if (BinOpcode)
11102     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11103   if (CmpOpcode) {
11104     // Signed comparisons of byte or halfword values must be sign-extended.
11105     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11106       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11107       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11108               ExtReg).addReg(dest);
11109       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11110         .addReg(incr).addReg(ExtReg);
11111     } else
11112       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11113         .addReg(incr).addReg(dest);
11114 
11115     BuildMI(BB, dl, TII->get(PPC::BCC))
11116       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11117     BB->addSuccessor(loop2MBB);
11118     BB->addSuccessor(exitMBB);
11119     BB = loop2MBB;
11120   }
11121   BuildMI(BB, dl, TII->get(StoreMnemonic))
11122     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11123   BuildMI(BB, dl, TII->get(PPC::BCC))
11124     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11125   BB->addSuccessor(loopMBB);
11126   BB->addSuccessor(exitMBB);
11127 
11128   //  exitMBB:
11129   //   ...
11130   BB = exitMBB;
11131   return BB;
11132 }
11133 
11134 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11135     MachineInstr &MI, MachineBasicBlock *BB,
11136     bool is8bit, // operation
11137     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11138   // If we support part-word atomic mnemonics, just use them
11139   if (Subtarget.hasPartwordAtomics())
11140     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11141                             CmpPred);
11142 
11143   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11144   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11145   // In 64 bit mode we have to use 64 bits for addresses, even though the
11146   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11147   // registers without caring whether they're 32 or 64, but here we're
11148   // doing actual arithmetic on the addresses.
11149   bool is64bit = Subtarget.isPPC64();
11150   bool isLittleEndian = Subtarget.isLittleEndian();
11151   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11152 
11153   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11154   MachineFunction *F = BB->getParent();
11155   MachineFunction::iterator It = ++BB->getIterator();
11156 
11157   Register dest = MI.getOperand(0).getReg();
11158   Register ptrA = MI.getOperand(1).getReg();
11159   Register ptrB = MI.getOperand(2).getReg();
11160   Register incr = MI.getOperand(3).getReg();
11161   DebugLoc dl = MI.getDebugLoc();
11162 
11163   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11164   MachineBasicBlock *loop2MBB =
11165       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11166   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11167   F->insert(It, loopMBB);
11168   if (CmpOpcode)
11169     F->insert(It, loop2MBB);
11170   F->insert(It, exitMBB);
11171   exitMBB->splice(exitMBB->begin(), BB,
11172                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11173   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11174 
11175   MachineRegisterInfo &RegInfo = F->getRegInfo();
11176   const TargetRegisterClass *RC =
11177       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11178   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11179 
11180   Register PtrReg = RegInfo.createVirtualRegister(RC);
11181   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11182   Register ShiftReg =
11183       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11184   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11185   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11186   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11187   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11188   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11189   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11190   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11191   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11192   Register Ptr1Reg;
11193   Register TmpReg =
11194       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11195 
11196   //  thisMBB:
11197   //   ...
11198   //   fallthrough --> loopMBB
11199   BB->addSuccessor(loopMBB);
11200 
11201   // The 4-byte load must be aligned, while a char or short may be
11202   // anywhere in the word.  Hence all this nasty bookkeeping code.
11203   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11204   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11205   //   xori shift, shift1, 24 [16]
11206   //   rlwinm ptr, ptr1, 0, 0, 29
11207   //   slw incr2, incr, shift
11208   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11209   //   slw mask, mask2, shift
11210   //  loopMBB:
11211   //   lwarx tmpDest, ptr
11212   //   add tmp, tmpDest, incr2
11213   //   andc tmp2, tmpDest, mask
11214   //   and tmp3, tmp, mask
11215   //   or tmp4, tmp3, tmp2
11216   //   stwcx. tmp4, ptr
11217   //   bne- loopMBB
11218   //   fallthrough --> exitMBB
11219   //   srw dest, tmpDest, shift
11220   if (ptrA != ZeroReg) {
11221     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11222     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11223         .addReg(ptrA)
11224         .addReg(ptrB);
11225   } else {
11226     Ptr1Reg = ptrB;
11227   }
11228   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11229   // mode.
11230   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11231       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11232       .addImm(3)
11233       .addImm(27)
11234       .addImm(is8bit ? 28 : 27);
11235   if (!isLittleEndian)
11236     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11237         .addReg(Shift1Reg)
11238         .addImm(is8bit ? 24 : 16);
11239   if (is64bit)
11240     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11241         .addReg(Ptr1Reg)
11242         .addImm(0)
11243         .addImm(61);
11244   else
11245     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11246         .addReg(Ptr1Reg)
11247         .addImm(0)
11248         .addImm(0)
11249         .addImm(29);
11250   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11251   if (is8bit)
11252     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11253   else {
11254     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11255     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11256         .addReg(Mask3Reg)
11257         .addImm(65535);
11258   }
11259   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11260       .addReg(Mask2Reg)
11261       .addReg(ShiftReg);
11262 
11263   BB = loopMBB;
11264   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11265       .addReg(ZeroReg)
11266       .addReg(PtrReg);
11267   if (BinOpcode)
11268     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11269         .addReg(Incr2Reg)
11270         .addReg(TmpDestReg);
11271   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11272       .addReg(TmpDestReg)
11273       .addReg(MaskReg);
11274   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11275   if (CmpOpcode) {
11276     // For unsigned comparisons, we can directly compare the shifted values.
11277     // For signed comparisons we shift and sign extend.
11278     Register SReg = RegInfo.createVirtualRegister(GPRC);
11279     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11280         .addReg(TmpDestReg)
11281         .addReg(MaskReg);
11282     unsigned ValueReg = SReg;
11283     unsigned CmpReg = Incr2Reg;
11284     if (CmpOpcode == PPC::CMPW) {
11285       ValueReg = RegInfo.createVirtualRegister(GPRC);
11286       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11287           .addReg(SReg)
11288           .addReg(ShiftReg);
11289       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11290       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11291           .addReg(ValueReg);
11292       ValueReg = ValueSReg;
11293       CmpReg = incr;
11294     }
11295     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11296         .addReg(CmpReg)
11297         .addReg(ValueReg);
11298     BuildMI(BB, dl, TII->get(PPC::BCC))
11299         .addImm(CmpPred)
11300         .addReg(PPC::CR0)
11301         .addMBB(exitMBB);
11302     BB->addSuccessor(loop2MBB);
11303     BB->addSuccessor(exitMBB);
11304     BB = loop2MBB;
11305   }
11306   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11307   BuildMI(BB, dl, TII->get(PPC::STWCX))
11308       .addReg(Tmp4Reg)
11309       .addReg(ZeroReg)
11310       .addReg(PtrReg);
11311   BuildMI(BB, dl, TII->get(PPC::BCC))
11312       .addImm(PPC::PRED_NE)
11313       .addReg(PPC::CR0)
11314       .addMBB(loopMBB);
11315   BB->addSuccessor(loopMBB);
11316   BB->addSuccessor(exitMBB);
11317 
11318   //  exitMBB:
11319   //   ...
11320   BB = exitMBB;
11321   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11322       .addReg(TmpDestReg)
11323       .addReg(ShiftReg);
11324   return BB;
11325 }
11326 
11327 llvm::MachineBasicBlock *
11328 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11329                                     MachineBasicBlock *MBB) const {
11330   DebugLoc DL = MI.getDebugLoc();
11331   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11332   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11333 
11334   MachineFunction *MF = MBB->getParent();
11335   MachineRegisterInfo &MRI = MF->getRegInfo();
11336 
11337   const BasicBlock *BB = MBB->getBasicBlock();
11338   MachineFunction::iterator I = ++MBB->getIterator();
11339 
11340   Register DstReg = MI.getOperand(0).getReg();
11341   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11342   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11343   Register mainDstReg = MRI.createVirtualRegister(RC);
11344   Register restoreDstReg = MRI.createVirtualRegister(RC);
11345 
11346   MVT PVT = getPointerTy(MF->getDataLayout());
11347   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11348          "Invalid Pointer Size!");
11349   // For v = setjmp(buf), we generate
11350   //
11351   // thisMBB:
11352   //  SjLjSetup mainMBB
11353   //  bl mainMBB
11354   //  v_restore = 1
11355   //  b sinkMBB
11356   //
11357   // mainMBB:
11358   //  buf[LabelOffset] = LR
11359   //  v_main = 0
11360   //
11361   // sinkMBB:
11362   //  v = phi(main, restore)
11363   //
11364 
11365   MachineBasicBlock *thisMBB = MBB;
11366   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11367   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11368   MF->insert(I, mainMBB);
11369   MF->insert(I, sinkMBB);
11370 
11371   MachineInstrBuilder MIB;
11372 
11373   // Transfer the remainder of BB and its successor edges to sinkMBB.
11374   sinkMBB->splice(sinkMBB->begin(), MBB,
11375                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11376   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11377 
11378   // Note that the structure of the jmp_buf used here is not compatible
11379   // with that used by libc, and is not designed to be. Specifically, it
11380   // stores only those 'reserved' registers that LLVM does not otherwise
11381   // understand how to spill. Also, by convention, by the time this
11382   // intrinsic is called, Clang has already stored the frame address in the
11383   // first slot of the buffer and stack address in the third. Following the
11384   // X86 target code, we'll store the jump address in the second slot. We also
11385   // need to save the TOC pointer (R2) to handle jumps between shared
11386   // libraries, and that will be stored in the fourth slot. The thread
11387   // identifier (R13) is not affected.
11388 
11389   // thisMBB:
11390   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11391   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11392   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11393 
11394   // Prepare IP either in reg.
11395   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11396   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11397   Register BufReg = MI.getOperand(1).getReg();
11398 
11399   if (Subtarget.is64BitELFABI()) {
11400     setUsesTOCBasePtr(*MBB->getParent());
11401     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11402               .addReg(PPC::X2)
11403               .addImm(TOCOffset)
11404               .addReg(BufReg)
11405               .cloneMemRefs(MI);
11406   }
11407 
11408   // Naked functions never have a base pointer, and so we use r1. For all
11409   // other functions, this decision must be delayed until during PEI.
11410   unsigned BaseReg;
11411   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11412     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11413   else
11414     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11415 
11416   MIB = BuildMI(*thisMBB, MI, DL,
11417                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11418             .addReg(BaseReg)
11419             .addImm(BPOffset)
11420             .addReg(BufReg)
11421             .cloneMemRefs(MI);
11422 
11423   // Setup
11424   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11425   MIB.addRegMask(TRI->getNoPreservedMask());
11426 
11427   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11428 
11429   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11430           .addMBB(mainMBB);
11431   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11432 
11433   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11434   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11435 
11436   // mainMBB:
11437   //  mainDstReg = 0
11438   MIB =
11439       BuildMI(mainMBB, DL,
11440               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11441 
11442   // Store IP
11443   if (Subtarget.isPPC64()) {
11444     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11445             .addReg(LabelReg)
11446             .addImm(LabelOffset)
11447             .addReg(BufReg);
11448   } else {
11449     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11450             .addReg(LabelReg)
11451             .addImm(LabelOffset)
11452             .addReg(BufReg);
11453   }
11454   MIB.cloneMemRefs(MI);
11455 
11456   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11457   mainMBB->addSuccessor(sinkMBB);
11458 
11459   // sinkMBB:
11460   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11461           TII->get(PPC::PHI), DstReg)
11462     .addReg(mainDstReg).addMBB(mainMBB)
11463     .addReg(restoreDstReg).addMBB(thisMBB);
11464 
11465   MI.eraseFromParent();
11466   return sinkMBB;
11467 }
11468 
11469 MachineBasicBlock *
11470 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11471                                      MachineBasicBlock *MBB) const {
11472   DebugLoc DL = MI.getDebugLoc();
11473   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11474 
11475   MachineFunction *MF = MBB->getParent();
11476   MachineRegisterInfo &MRI = MF->getRegInfo();
11477 
11478   MVT PVT = getPointerTy(MF->getDataLayout());
11479   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11480          "Invalid Pointer Size!");
11481 
11482   const TargetRegisterClass *RC =
11483     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11484   Register Tmp = MRI.createVirtualRegister(RC);
11485   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11486   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11487   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11488   unsigned BP =
11489       (PVT == MVT::i64)
11490           ? PPC::X30
11491           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11492                                                               : PPC::R30);
11493 
11494   MachineInstrBuilder MIB;
11495 
11496   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11497   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11498   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11499   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11500 
11501   Register BufReg = MI.getOperand(0).getReg();
11502 
11503   // Reload FP (the jumped-to function may not have had a
11504   // frame pointer, and if so, then its r31 will be restored
11505   // as necessary).
11506   if (PVT == MVT::i64) {
11507     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11508             .addImm(0)
11509             .addReg(BufReg);
11510   } else {
11511     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11512             .addImm(0)
11513             .addReg(BufReg);
11514   }
11515   MIB.cloneMemRefs(MI);
11516 
11517   // Reload IP
11518   if (PVT == MVT::i64) {
11519     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11520             .addImm(LabelOffset)
11521             .addReg(BufReg);
11522   } else {
11523     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11524             .addImm(LabelOffset)
11525             .addReg(BufReg);
11526   }
11527   MIB.cloneMemRefs(MI);
11528 
11529   // Reload SP
11530   if (PVT == MVT::i64) {
11531     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11532             .addImm(SPOffset)
11533             .addReg(BufReg);
11534   } else {
11535     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11536             .addImm(SPOffset)
11537             .addReg(BufReg);
11538   }
11539   MIB.cloneMemRefs(MI);
11540 
11541   // Reload BP
11542   if (PVT == MVT::i64) {
11543     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11544             .addImm(BPOffset)
11545             .addReg(BufReg);
11546   } else {
11547     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11548             .addImm(BPOffset)
11549             .addReg(BufReg);
11550   }
11551   MIB.cloneMemRefs(MI);
11552 
11553   // Reload TOC
11554   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11555     setUsesTOCBasePtr(*MBB->getParent());
11556     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11557               .addImm(TOCOffset)
11558               .addReg(BufReg)
11559               .cloneMemRefs(MI);
11560   }
11561 
11562   // Jump
11563   BuildMI(*MBB, MI, DL,
11564           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11565   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11566 
11567   MI.eraseFromParent();
11568   return MBB;
11569 }
11570 
11571 MachineBasicBlock *
11572 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11573                                                MachineBasicBlock *BB) const {
11574   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11575       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11576     if (Subtarget.is64BitELFABI() &&
11577         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11578         !Subtarget.isUsingPCRelativeCalls()) {
11579       // Call lowering should have added an r2 operand to indicate a dependence
11580       // on the TOC base pointer value. It can't however, because there is no
11581       // way to mark the dependence as implicit there, and so the stackmap code
11582       // will confuse it with a regular operand. Instead, add the dependence
11583       // here.
11584       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11585     }
11586 
11587     return emitPatchPoint(MI, BB);
11588   }
11589 
11590   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11591       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11592     return emitEHSjLjSetJmp(MI, BB);
11593   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11594              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11595     return emitEHSjLjLongJmp(MI, BB);
11596   }
11597 
11598   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11599 
11600   // To "insert" these instructions we actually have to insert their
11601   // control-flow patterns.
11602   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11603   MachineFunction::iterator It = ++BB->getIterator();
11604 
11605   MachineFunction *F = BB->getParent();
11606 
11607   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11608       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11609       MI.getOpcode() == PPC::SELECT_I8) {
11610     SmallVector<MachineOperand, 2> Cond;
11611     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11612         MI.getOpcode() == PPC::SELECT_CC_I8)
11613       Cond.push_back(MI.getOperand(4));
11614     else
11615       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11616     Cond.push_back(MI.getOperand(1));
11617 
11618     DebugLoc dl = MI.getDebugLoc();
11619     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11620                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11621   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11622              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11623              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11624              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11625              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11626              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11627              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11628              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11629              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11630              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11631              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11632              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11633              MI.getOpcode() == PPC::SELECT_F4 ||
11634              MI.getOpcode() == PPC::SELECT_F8 ||
11635              MI.getOpcode() == PPC::SELECT_F16 ||
11636              MI.getOpcode() == PPC::SELECT_QFRC ||
11637              MI.getOpcode() == PPC::SELECT_QSRC ||
11638              MI.getOpcode() == PPC::SELECT_QBRC ||
11639              MI.getOpcode() == PPC::SELECT_SPE ||
11640              MI.getOpcode() == PPC::SELECT_SPE4 ||
11641              MI.getOpcode() == PPC::SELECT_VRRC ||
11642              MI.getOpcode() == PPC::SELECT_VSFRC ||
11643              MI.getOpcode() == PPC::SELECT_VSSRC ||
11644              MI.getOpcode() == PPC::SELECT_VSRC) {
11645     // The incoming instruction knows the destination vreg to set, the
11646     // condition code register to branch on, the true/false values to
11647     // select between, and a branch opcode to use.
11648 
11649     //  thisMBB:
11650     //  ...
11651     //   TrueVal = ...
11652     //   cmpTY ccX, r1, r2
11653     //   bCC copy1MBB
11654     //   fallthrough --> copy0MBB
11655     MachineBasicBlock *thisMBB = BB;
11656     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11657     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11658     DebugLoc dl = MI.getDebugLoc();
11659     F->insert(It, copy0MBB);
11660     F->insert(It, sinkMBB);
11661 
11662     // Transfer the remainder of BB and its successor edges to sinkMBB.
11663     sinkMBB->splice(sinkMBB->begin(), BB,
11664                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11665     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11666 
11667     // Next, add the true and fallthrough blocks as its successors.
11668     BB->addSuccessor(copy0MBB);
11669     BB->addSuccessor(sinkMBB);
11670 
11671     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11672         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11673         MI.getOpcode() == PPC::SELECT_F16 ||
11674         MI.getOpcode() == PPC::SELECT_SPE4 ||
11675         MI.getOpcode() == PPC::SELECT_SPE ||
11676         MI.getOpcode() == PPC::SELECT_QFRC ||
11677         MI.getOpcode() == PPC::SELECT_QSRC ||
11678         MI.getOpcode() == PPC::SELECT_QBRC ||
11679         MI.getOpcode() == PPC::SELECT_VRRC ||
11680         MI.getOpcode() == PPC::SELECT_VSFRC ||
11681         MI.getOpcode() == PPC::SELECT_VSSRC ||
11682         MI.getOpcode() == PPC::SELECT_VSRC) {
11683       BuildMI(BB, dl, TII->get(PPC::BC))
11684           .addReg(MI.getOperand(1).getReg())
11685           .addMBB(sinkMBB);
11686     } else {
11687       unsigned SelectPred = MI.getOperand(4).getImm();
11688       BuildMI(BB, dl, TII->get(PPC::BCC))
11689           .addImm(SelectPred)
11690           .addReg(MI.getOperand(1).getReg())
11691           .addMBB(sinkMBB);
11692     }
11693 
11694     //  copy0MBB:
11695     //   %FalseValue = ...
11696     //   # fallthrough to sinkMBB
11697     BB = copy0MBB;
11698 
11699     // Update machine-CFG edges
11700     BB->addSuccessor(sinkMBB);
11701 
11702     //  sinkMBB:
11703     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11704     //  ...
11705     BB = sinkMBB;
11706     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11707         .addReg(MI.getOperand(3).getReg())
11708         .addMBB(copy0MBB)
11709         .addReg(MI.getOperand(2).getReg())
11710         .addMBB(thisMBB);
11711   } else if (MI.getOpcode() == PPC::ReadTB) {
11712     // To read the 64-bit time-base register on a 32-bit target, we read the
11713     // two halves. Should the counter have wrapped while it was being read, we
11714     // need to try again.
11715     // ...
11716     // readLoop:
11717     // mfspr Rx,TBU # load from TBU
11718     // mfspr Ry,TB  # load from TB
11719     // mfspr Rz,TBU # load from TBU
11720     // cmpw crX,Rx,Rz # check if 'old'='new'
11721     // bne readLoop   # branch if they're not equal
11722     // ...
11723 
11724     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11725     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11726     DebugLoc dl = MI.getDebugLoc();
11727     F->insert(It, readMBB);
11728     F->insert(It, sinkMBB);
11729 
11730     // Transfer the remainder of BB and its successor edges to sinkMBB.
11731     sinkMBB->splice(sinkMBB->begin(), BB,
11732                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11733     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11734 
11735     BB->addSuccessor(readMBB);
11736     BB = readMBB;
11737 
11738     MachineRegisterInfo &RegInfo = F->getRegInfo();
11739     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11740     Register LoReg = MI.getOperand(0).getReg();
11741     Register HiReg = MI.getOperand(1).getReg();
11742 
11743     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11744     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11745     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11746 
11747     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11748 
11749     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11750         .addReg(HiReg)
11751         .addReg(ReadAgainReg);
11752     BuildMI(BB, dl, TII->get(PPC::BCC))
11753         .addImm(PPC::PRED_NE)
11754         .addReg(CmpReg)
11755         .addMBB(readMBB);
11756 
11757     BB->addSuccessor(readMBB);
11758     BB->addSuccessor(sinkMBB);
11759   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11760     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11761   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11762     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11763   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11764     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11765   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11766     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11767 
11768   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11769     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11770   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11771     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11772   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11773     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11774   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11775     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11776 
11777   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11778     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11779   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11780     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11781   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11782     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11783   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11784     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11785 
11786   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11787     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11788   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11789     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11790   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11791     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11792   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11793     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11794 
11795   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11796     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11797   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11798     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11799   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11800     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11801   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11802     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11803 
11804   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11805     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11806   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11807     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11808   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11809     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11810   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11811     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11812 
11813   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11814     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11815   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11816     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11817   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11818     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11819   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11820     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11821 
11822   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11823     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11824   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11825     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11826   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11827     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11828   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11829     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11830 
11831   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11832     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11833   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11834     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11835   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11836     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11837   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11838     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11839 
11840   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11841     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11842   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11843     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11844   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11845     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11846   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11847     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11848 
11849   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11850     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11851   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11852     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11853   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11854     BB = EmitAtomicBinary(MI, BB, 4, 0);
11855   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11856     BB = EmitAtomicBinary(MI, BB, 8, 0);
11857   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11858            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11859            (Subtarget.hasPartwordAtomics() &&
11860             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11861            (Subtarget.hasPartwordAtomics() &&
11862             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11863     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11864 
11865     auto LoadMnemonic = PPC::LDARX;
11866     auto StoreMnemonic = PPC::STDCX;
11867     switch (MI.getOpcode()) {
11868     default:
11869       llvm_unreachable("Compare and swap of unknown size");
11870     case PPC::ATOMIC_CMP_SWAP_I8:
11871       LoadMnemonic = PPC::LBARX;
11872       StoreMnemonic = PPC::STBCX;
11873       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11874       break;
11875     case PPC::ATOMIC_CMP_SWAP_I16:
11876       LoadMnemonic = PPC::LHARX;
11877       StoreMnemonic = PPC::STHCX;
11878       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11879       break;
11880     case PPC::ATOMIC_CMP_SWAP_I32:
11881       LoadMnemonic = PPC::LWARX;
11882       StoreMnemonic = PPC::STWCX;
11883       break;
11884     case PPC::ATOMIC_CMP_SWAP_I64:
11885       LoadMnemonic = PPC::LDARX;
11886       StoreMnemonic = PPC::STDCX;
11887       break;
11888     }
11889     Register dest = MI.getOperand(0).getReg();
11890     Register ptrA = MI.getOperand(1).getReg();
11891     Register ptrB = MI.getOperand(2).getReg();
11892     Register oldval = MI.getOperand(3).getReg();
11893     Register newval = MI.getOperand(4).getReg();
11894     DebugLoc dl = MI.getDebugLoc();
11895 
11896     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11897     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11898     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11899     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11900     F->insert(It, loop1MBB);
11901     F->insert(It, loop2MBB);
11902     F->insert(It, midMBB);
11903     F->insert(It, exitMBB);
11904     exitMBB->splice(exitMBB->begin(), BB,
11905                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11906     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11907 
11908     //  thisMBB:
11909     //   ...
11910     //   fallthrough --> loopMBB
11911     BB->addSuccessor(loop1MBB);
11912 
11913     // loop1MBB:
11914     //   l[bhwd]arx dest, ptr
11915     //   cmp[wd] dest, oldval
11916     //   bne- midMBB
11917     // loop2MBB:
11918     //   st[bhwd]cx. newval, ptr
11919     //   bne- loopMBB
11920     //   b exitBB
11921     // midMBB:
11922     //   st[bhwd]cx. dest, ptr
11923     // exitBB:
11924     BB = loop1MBB;
11925     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11926     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11927         .addReg(oldval)
11928         .addReg(dest);
11929     BuildMI(BB, dl, TII->get(PPC::BCC))
11930         .addImm(PPC::PRED_NE)
11931         .addReg(PPC::CR0)
11932         .addMBB(midMBB);
11933     BB->addSuccessor(loop2MBB);
11934     BB->addSuccessor(midMBB);
11935 
11936     BB = loop2MBB;
11937     BuildMI(BB, dl, TII->get(StoreMnemonic))
11938         .addReg(newval)
11939         .addReg(ptrA)
11940         .addReg(ptrB);
11941     BuildMI(BB, dl, TII->get(PPC::BCC))
11942         .addImm(PPC::PRED_NE)
11943         .addReg(PPC::CR0)
11944         .addMBB(loop1MBB);
11945     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11946     BB->addSuccessor(loop1MBB);
11947     BB->addSuccessor(exitMBB);
11948 
11949     BB = midMBB;
11950     BuildMI(BB, dl, TII->get(StoreMnemonic))
11951         .addReg(dest)
11952         .addReg(ptrA)
11953         .addReg(ptrB);
11954     BB->addSuccessor(exitMBB);
11955 
11956     //  exitMBB:
11957     //   ...
11958     BB = exitMBB;
11959   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11960              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11961     // We must use 64-bit registers for addresses when targeting 64-bit,
11962     // since we're actually doing arithmetic on them.  Other registers
11963     // can be 32-bit.
11964     bool is64bit = Subtarget.isPPC64();
11965     bool isLittleEndian = Subtarget.isLittleEndian();
11966     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11967 
11968     Register dest = MI.getOperand(0).getReg();
11969     Register ptrA = MI.getOperand(1).getReg();
11970     Register ptrB = MI.getOperand(2).getReg();
11971     Register oldval = MI.getOperand(3).getReg();
11972     Register newval = MI.getOperand(4).getReg();
11973     DebugLoc dl = MI.getDebugLoc();
11974 
11975     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11976     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11977     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11978     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11979     F->insert(It, loop1MBB);
11980     F->insert(It, loop2MBB);
11981     F->insert(It, midMBB);
11982     F->insert(It, exitMBB);
11983     exitMBB->splice(exitMBB->begin(), BB,
11984                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11985     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11986 
11987     MachineRegisterInfo &RegInfo = F->getRegInfo();
11988     const TargetRegisterClass *RC =
11989         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11990     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11991 
11992     Register PtrReg = RegInfo.createVirtualRegister(RC);
11993     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11994     Register ShiftReg =
11995         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11996     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11997     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11998     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11999     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12000     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12001     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12002     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12003     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12004     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12005     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12006     Register Ptr1Reg;
12007     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12008     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12009     //  thisMBB:
12010     //   ...
12011     //   fallthrough --> loopMBB
12012     BB->addSuccessor(loop1MBB);
12013 
12014     // The 4-byte load must be aligned, while a char or short may be
12015     // anywhere in the word.  Hence all this nasty bookkeeping code.
12016     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12017     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12018     //   xori shift, shift1, 24 [16]
12019     //   rlwinm ptr, ptr1, 0, 0, 29
12020     //   slw newval2, newval, shift
12021     //   slw oldval2, oldval,shift
12022     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12023     //   slw mask, mask2, shift
12024     //   and newval3, newval2, mask
12025     //   and oldval3, oldval2, mask
12026     // loop1MBB:
12027     //   lwarx tmpDest, ptr
12028     //   and tmp, tmpDest, mask
12029     //   cmpw tmp, oldval3
12030     //   bne- midMBB
12031     // loop2MBB:
12032     //   andc tmp2, tmpDest, mask
12033     //   or tmp4, tmp2, newval3
12034     //   stwcx. tmp4, ptr
12035     //   bne- loop1MBB
12036     //   b exitBB
12037     // midMBB:
12038     //   stwcx. tmpDest, ptr
12039     // exitBB:
12040     //   srw dest, tmpDest, shift
12041     if (ptrA != ZeroReg) {
12042       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12043       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12044           .addReg(ptrA)
12045           .addReg(ptrB);
12046     } else {
12047       Ptr1Reg = ptrB;
12048     }
12049 
12050     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12051     // mode.
12052     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12053         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12054         .addImm(3)
12055         .addImm(27)
12056         .addImm(is8bit ? 28 : 27);
12057     if (!isLittleEndian)
12058       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12059           .addReg(Shift1Reg)
12060           .addImm(is8bit ? 24 : 16);
12061     if (is64bit)
12062       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12063           .addReg(Ptr1Reg)
12064           .addImm(0)
12065           .addImm(61);
12066     else
12067       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12068           .addReg(Ptr1Reg)
12069           .addImm(0)
12070           .addImm(0)
12071           .addImm(29);
12072     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12073         .addReg(newval)
12074         .addReg(ShiftReg);
12075     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12076         .addReg(oldval)
12077         .addReg(ShiftReg);
12078     if (is8bit)
12079       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12080     else {
12081       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12082       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12083           .addReg(Mask3Reg)
12084           .addImm(65535);
12085     }
12086     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12087         .addReg(Mask2Reg)
12088         .addReg(ShiftReg);
12089     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12090         .addReg(NewVal2Reg)
12091         .addReg(MaskReg);
12092     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12093         .addReg(OldVal2Reg)
12094         .addReg(MaskReg);
12095 
12096     BB = loop1MBB;
12097     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12098         .addReg(ZeroReg)
12099         .addReg(PtrReg);
12100     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12101         .addReg(TmpDestReg)
12102         .addReg(MaskReg);
12103     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12104         .addReg(TmpReg)
12105         .addReg(OldVal3Reg);
12106     BuildMI(BB, dl, TII->get(PPC::BCC))
12107         .addImm(PPC::PRED_NE)
12108         .addReg(PPC::CR0)
12109         .addMBB(midMBB);
12110     BB->addSuccessor(loop2MBB);
12111     BB->addSuccessor(midMBB);
12112 
12113     BB = loop2MBB;
12114     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12115         .addReg(TmpDestReg)
12116         .addReg(MaskReg);
12117     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12118         .addReg(Tmp2Reg)
12119         .addReg(NewVal3Reg);
12120     BuildMI(BB, dl, TII->get(PPC::STWCX))
12121         .addReg(Tmp4Reg)
12122         .addReg(ZeroReg)
12123         .addReg(PtrReg);
12124     BuildMI(BB, dl, TII->get(PPC::BCC))
12125         .addImm(PPC::PRED_NE)
12126         .addReg(PPC::CR0)
12127         .addMBB(loop1MBB);
12128     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12129     BB->addSuccessor(loop1MBB);
12130     BB->addSuccessor(exitMBB);
12131 
12132     BB = midMBB;
12133     BuildMI(BB, dl, TII->get(PPC::STWCX))
12134         .addReg(TmpDestReg)
12135         .addReg(ZeroReg)
12136         .addReg(PtrReg);
12137     BB->addSuccessor(exitMBB);
12138 
12139     //  exitMBB:
12140     //   ...
12141     BB = exitMBB;
12142     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12143         .addReg(TmpReg)
12144         .addReg(ShiftReg);
12145   } else if (MI.getOpcode() == PPC::FADDrtz) {
12146     // This pseudo performs an FADD with rounding mode temporarily forced
12147     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12148     // is not modeled at the SelectionDAG level.
12149     Register Dest = MI.getOperand(0).getReg();
12150     Register Src1 = MI.getOperand(1).getReg();
12151     Register Src2 = MI.getOperand(2).getReg();
12152     DebugLoc dl = MI.getDebugLoc();
12153 
12154     MachineRegisterInfo &RegInfo = F->getRegInfo();
12155     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12156 
12157     // Save FPSCR value.
12158     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12159 
12160     // Set rounding mode to round-to-zero.
12161     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12162     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12163 
12164     // Perform addition.
12165     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12166 
12167     // Restore FPSCR value.
12168     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12169   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12170              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12171              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12172              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12173     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12174                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12175                           ? PPC::ANDI8_rec
12176                           : PPC::ANDI_rec;
12177     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12178                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12179 
12180     MachineRegisterInfo &RegInfo = F->getRegInfo();
12181     Register Dest = RegInfo.createVirtualRegister(
12182         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12183 
12184     DebugLoc Dl = MI.getDebugLoc();
12185     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12186         .addReg(MI.getOperand(1).getReg())
12187         .addImm(1);
12188     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12189             MI.getOperand(0).getReg())
12190         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12191   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12192     DebugLoc Dl = MI.getDebugLoc();
12193     MachineRegisterInfo &RegInfo = F->getRegInfo();
12194     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12195     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12196     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12197             MI.getOperand(0).getReg())
12198         .addReg(CRReg);
12199   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12200     DebugLoc Dl = MI.getDebugLoc();
12201     unsigned Imm = MI.getOperand(1).getImm();
12202     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12203     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12204             MI.getOperand(0).getReg())
12205         .addReg(PPC::CR0EQ);
12206   } else if (MI.getOpcode() == PPC::SETRNDi) {
12207     DebugLoc dl = MI.getDebugLoc();
12208     Register OldFPSCRReg = MI.getOperand(0).getReg();
12209 
12210     // Save FPSCR value.
12211     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12212 
12213     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12214     // the following settings:
12215     //   00 Round to nearest
12216     //   01 Round to 0
12217     //   10 Round to +inf
12218     //   11 Round to -inf
12219 
12220     // When the operand is immediate, using the two least significant bits of
12221     // the immediate to set the bits 62:63 of FPSCR.
12222     unsigned Mode = MI.getOperand(1).getImm();
12223     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12224       .addImm(31);
12225 
12226     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12227       .addImm(30);
12228   } else if (MI.getOpcode() == PPC::SETRND) {
12229     DebugLoc dl = MI.getDebugLoc();
12230 
12231     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12232     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12233     // If the target doesn't have DirectMove, we should use stack to do the
12234     // conversion, because the target doesn't have the instructions like mtvsrd
12235     // or mfvsrd to do this conversion directly.
12236     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12237       if (Subtarget.hasDirectMove()) {
12238         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12239           .addReg(SrcReg);
12240       } else {
12241         // Use stack to do the register copy.
12242         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12243         MachineRegisterInfo &RegInfo = F->getRegInfo();
12244         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12245         if (RC == &PPC::F8RCRegClass) {
12246           // Copy register from F8RCRegClass to G8RCRegclass.
12247           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12248                  "Unsupported RegClass.");
12249 
12250           StoreOp = PPC::STFD;
12251           LoadOp = PPC::LD;
12252         } else {
12253           // Copy register from G8RCRegClass to F8RCRegclass.
12254           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12255                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12256                  "Unsupported RegClass.");
12257         }
12258 
12259         MachineFrameInfo &MFI = F->getFrameInfo();
12260         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12261 
12262         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12263             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12264             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12265             MFI.getObjectAlign(FrameIdx));
12266 
12267         // Store the SrcReg into the stack.
12268         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12269           .addReg(SrcReg)
12270           .addImm(0)
12271           .addFrameIndex(FrameIdx)
12272           .addMemOperand(MMOStore);
12273 
12274         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12275             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12276             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12277             MFI.getObjectAlign(FrameIdx));
12278 
12279         // Load from the stack where SrcReg is stored, and save to DestReg,
12280         // so we have done the RegClass conversion from RegClass::SrcReg to
12281         // RegClass::DestReg.
12282         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12283           .addImm(0)
12284           .addFrameIndex(FrameIdx)
12285           .addMemOperand(MMOLoad);
12286       }
12287     };
12288 
12289     Register OldFPSCRReg = MI.getOperand(0).getReg();
12290 
12291     // Save FPSCR value.
12292     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12293 
12294     // When the operand is gprc register, use two least significant bits of the
12295     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12296     //
12297     // copy OldFPSCRTmpReg, OldFPSCRReg
12298     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12299     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12300     // copy NewFPSCRReg, NewFPSCRTmpReg
12301     // mtfsf 255, NewFPSCRReg
12302     MachineOperand SrcOp = MI.getOperand(1);
12303     MachineRegisterInfo &RegInfo = F->getRegInfo();
12304     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12305 
12306     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12307 
12308     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12309     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12310 
12311     // The first operand of INSERT_SUBREG should be a register which has
12312     // subregisters, we only care about its RegClass, so we should use an
12313     // IMPLICIT_DEF register.
12314     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12315     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12316       .addReg(ImDefReg)
12317       .add(SrcOp)
12318       .addImm(1);
12319 
12320     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12321     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12322       .addReg(OldFPSCRTmpReg)
12323       .addReg(ExtSrcReg)
12324       .addImm(0)
12325       .addImm(62);
12326 
12327     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12328     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12329 
12330     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12331     // bits of FPSCR.
12332     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12333       .addImm(255)
12334       .addReg(NewFPSCRReg)
12335       .addImm(0)
12336       .addImm(0);
12337   } else {
12338     llvm_unreachable("Unexpected instr type to insert");
12339   }
12340 
12341   MI.eraseFromParent(); // The pseudo instruction is gone now.
12342   return BB;
12343 }
12344 
12345 //===----------------------------------------------------------------------===//
12346 // Target Optimization Hooks
12347 //===----------------------------------------------------------------------===//
12348 
12349 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12350   // For the estimates, convergence is quadratic, so we essentially double the
12351   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12352   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12353   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12354   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12355   if (VT.getScalarType() == MVT::f64)
12356     RefinementSteps++;
12357   return RefinementSteps;
12358 }
12359 
12360 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12361                                            int Enabled, int &RefinementSteps,
12362                                            bool &UseOneConstNR,
12363                                            bool Reciprocal) const {
12364   EVT VT = Operand.getValueType();
12365   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12366       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12367       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12368       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12369       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12370       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12371     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12372       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12373 
12374     // The Newton-Raphson computation with a single constant does not provide
12375     // enough accuracy on some CPUs.
12376     UseOneConstNR = !Subtarget.needsTwoConstNR();
12377     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12378   }
12379   return SDValue();
12380 }
12381 
12382 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12383                                             int Enabled,
12384                                             int &RefinementSteps) const {
12385   EVT VT = Operand.getValueType();
12386   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12387       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12388       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12389       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12390       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12391       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12392     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12393       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12394     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12395   }
12396   return SDValue();
12397 }
12398 
12399 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12400   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12401   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12402   // enabled for division), this functionality is redundant with the default
12403   // combiner logic (once the division -> reciprocal/multiply transformation
12404   // has taken place). As a result, this matters more for older cores than for
12405   // newer ones.
12406 
12407   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12408   // reciprocal if there are two or more FDIVs (for embedded cores with only
12409   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12410   switch (Subtarget.getCPUDirective()) {
12411   default:
12412     return 3;
12413   case PPC::DIR_440:
12414   case PPC::DIR_A2:
12415   case PPC::DIR_E500:
12416   case PPC::DIR_E500mc:
12417   case PPC::DIR_E5500:
12418     return 2;
12419   }
12420 }
12421 
12422 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12423 // collapsed, and so we need to look through chains of them.
12424 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12425                                      int64_t& Offset, SelectionDAG &DAG) {
12426   if (DAG.isBaseWithConstantOffset(Loc)) {
12427     Base = Loc.getOperand(0);
12428     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12429 
12430     // The base might itself be a base plus an offset, and if so, accumulate
12431     // that as well.
12432     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12433   }
12434 }
12435 
12436 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12437                             unsigned Bytes, int Dist,
12438                             SelectionDAG &DAG) {
12439   if (VT.getSizeInBits() / 8 != Bytes)
12440     return false;
12441 
12442   SDValue BaseLoc = Base->getBasePtr();
12443   if (Loc.getOpcode() == ISD::FrameIndex) {
12444     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12445       return false;
12446     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12447     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12448     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12449     int FS  = MFI.getObjectSize(FI);
12450     int BFS = MFI.getObjectSize(BFI);
12451     if (FS != BFS || FS != (int)Bytes) return false;
12452     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12453   }
12454 
12455   SDValue Base1 = Loc, Base2 = BaseLoc;
12456   int64_t Offset1 = 0, Offset2 = 0;
12457   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12458   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12459   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12460     return true;
12461 
12462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12463   const GlobalValue *GV1 = nullptr;
12464   const GlobalValue *GV2 = nullptr;
12465   Offset1 = 0;
12466   Offset2 = 0;
12467   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12468   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12469   if (isGA1 && isGA2 && GV1 == GV2)
12470     return Offset1 == (Offset2 + Dist*Bytes);
12471   return false;
12472 }
12473 
12474 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12475 // not enforce equality of the chain operands.
12476 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12477                             unsigned Bytes, int Dist,
12478                             SelectionDAG &DAG) {
12479   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12480     EVT VT = LS->getMemoryVT();
12481     SDValue Loc = LS->getBasePtr();
12482     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12483   }
12484 
12485   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12486     EVT VT;
12487     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12488     default: return false;
12489     case Intrinsic::ppc_qpx_qvlfd:
12490     case Intrinsic::ppc_qpx_qvlfda:
12491       VT = MVT::v4f64;
12492       break;
12493     case Intrinsic::ppc_qpx_qvlfs:
12494     case Intrinsic::ppc_qpx_qvlfsa:
12495       VT = MVT::v4f32;
12496       break;
12497     case Intrinsic::ppc_qpx_qvlfcd:
12498     case Intrinsic::ppc_qpx_qvlfcda:
12499       VT = MVT::v2f64;
12500       break;
12501     case Intrinsic::ppc_qpx_qvlfcs:
12502     case Intrinsic::ppc_qpx_qvlfcsa:
12503       VT = MVT::v2f32;
12504       break;
12505     case Intrinsic::ppc_qpx_qvlfiwa:
12506     case Intrinsic::ppc_qpx_qvlfiwz:
12507     case Intrinsic::ppc_altivec_lvx:
12508     case Intrinsic::ppc_altivec_lvxl:
12509     case Intrinsic::ppc_vsx_lxvw4x:
12510     case Intrinsic::ppc_vsx_lxvw4x_be:
12511       VT = MVT::v4i32;
12512       break;
12513     case Intrinsic::ppc_vsx_lxvd2x:
12514     case Intrinsic::ppc_vsx_lxvd2x_be:
12515       VT = MVT::v2f64;
12516       break;
12517     case Intrinsic::ppc_altivec_lvebx:
12518       VT = MVT::i8;
12519       break;
12520     case Intrinsic::ppc_altivec_lvehx:
12521       VT = MVT::i16;
12522       break;
12523     case Intrinsic::ppc_altivec_lvewx:
12524       VT = MVT::i32;
12525       break;
12526     }
12527 
12528     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12529   }
12530 
12531   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12532     EVT VT;
12533     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12534     default: return false;
12535     case Intrinsic::ppc_qpx_qvstfd:
12536     case Intrinsic::ppc_qpx_qvstfda:
12537       VT = MVT::v4f64;
12538       break;
12539     case Intrinsic::ppc_qpx_qvstfs:
12540     case Intrinsic::ppc_qpx_qvstfsa:
12541       VT = MVT::v4f32;
12542       break;
12543     case Intrinsic::ppc_qpx_qvstfcd:
12544     case Intrinsic::ppc_qpx_qvstfcda:
12545       VT = MVT::v2f64;
12546       break;
12547     case Intrinsic::ppc_qpx_qvstfcs:
12548     case Intrinsic::ppc_qpx_qvstfcsa:
12549       VT = MVT::v2f32;
12550       break;
12551     case Intrinsic::ppc_qpx_qvstfiw:
12552     case Intrinsic::ppc_qpx_qvstfiwa:
12553     case Intrinsic::ppc_altivec_stvx:
12554     case Intrinsic::ppc_altivec_stvxl:
12555     case Intrinsic::ppc_vsx_stxvw4x:
12556       VT = MVT::v4i32;
12557       break;
12558     case Intrinsic::ppc_vsx_stxvd2x:
12559       VT = MVT::v2f64;
12560       break;
12561     case Intrinsic::ppc_vsx_stxvw4x_be:
12562       VT = MVT::v4i32;
12563       break;
12564     case Intrinsic::ppc_vsx_stxvd2x_be:
12565       VT = MVT::v2f64;
12566       break;
12567     case Intrinsic::ppc_altivec_stvebx:
12568       VT = MVT::i8;
12569       break;
12570     case Intrinsic::ppc_altivec_stvehx:
12571       VT = MVT::i16;
12572       break;
12573     case Intrinsic::ppc_altivec_stvewx:
12574       VT = MVT::i32;
12575       break;
12576     }
12577 
12578     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12579   }
12580 
12581   return false;
12582 }
12583 
12584 // Return true is there is a nearyby consecutive load to the one provided
12585 // (regardless of alignment). We search up and down the chain, looking though
12586 // token factors and other loads (but nothing else). As a result, a true result
12587 // indicates that it is safe to create a new consecutive load adjacent to the
12588 // load provided.
12589 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12590   SDValue Chain = LD->getChain();
12591   EVT VT = LD->getMemoryVT();
12592 
12593   SmallSet<SDNode *, 16> LoadRoots;
12594   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12595   SmallSet<SDNode *, 16> Visited;
12596 
12597   // First, search up the chain, branching to follow all token-factor operands.
12598   // If we find a consecutive load, then we're done, otherwise, record all
12599   // nodes just above the top-level loads and token factors.
12600   while (!Queue.empty()) {
12601     SDNode *ChainNext = Queue.pop_back_val();
12602     if (!Visited.insert(ChainNext).second)
12603       continue;
12604 
12605     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12606       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12607         return true;
12608 
12609       if (!Visited.count(ChainLD->getChain().getNode()))
12610         Queue.push_back(ChainLD->getChain().getNode());
12611     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12612       for (const SDUse &O : ChainNext->ops())
12613         if (!Visited.count(O.getNode()))
12614           Queue.push_back(O.getNode());
12615     } else
12616       LoadRoots.insert(ChainNext);
12617   }
12618 
12619   // Second, search down the chain, starting from the top-level nodes recorded
12620   // in the first phase. These top-level nodes are the nodes just above all
12621   // loads and token factors. Starting with their uses, recursively look though
12622   // all loads (just the chain uses) and token factors to find a consecutive
12623   // load.
12624   Visited.clear();
12625   Queue.clear();
12626 
12627   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12628        IE = LoadRoots.end(); I != IE; ++I) {
12629     Queue.push_back(*I);
12630 
12631     while (!Queue.empty()) {
12632       SDNode *LoadRoot = Queue.pop_back_val();
12633       if (!Visited.insert(LoadRoot).second)
12634         continue;
12635 
12636       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12637         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12638           return true;
12639 
12640       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12641            UE = LoadRoot->use_end(); UI != UE; ++UI)
12642         if (((isa<MemSDNode>(*UI) &&
12643             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12644             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12645           Queue.push_back(*UI);
12646     }
12647   }
12648 
12649   return false;
12650 }
12651 
12652 /// This function is called when we have proved that a SETCC node can be replaced
12653 /// by subtraction (and other supporting instructions) so that the result of
12654 /// comparison is kept in a GPR instead of CR. This function is purely for
12655 /// codegen purposes and has some flags to guide the codegen process.
12656 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12657                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12658   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12659 
12660   // Zero extend the operands to the largest legal integer. Originally, they
12661   // must be of a strictly smaller size.
12662   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12663                          DAG.getConstant(Size, DL, MVT::i32));
12664   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12665                          DAG.getConstant(Size, DL, MVT::i32));
12666 
12667   // Swap if needed. Depends on the condition code.
12668   if (Swap)
12669     std::swap(Op0, Op1);
12670 
12671   // Subtract extended integers.
12672   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12673 
12674   // Move the sign bit to the least significant position and zero out the rest.
12675   // Now the least significant bit carries the result of original comparison.
12676   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12677                              DAG.getConstant(Size - 1, DL, MVT::i32));
12678   auto Final = Shifted;
12679 
12680   // Complement the result if needed. Based on the condition code.
12681   if (Complement)
12682     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12683                         DAG.getConstant(1, DL, MVT::i64));
12684 
12685   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12686 }
12687 
12688 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12689                                                   DAGCombinerInfo &DCI) const {
12690   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12691 
12692   SelectionDAG &DAG = DCI.DAG;
12693   SDLoc DL(N);
12694 
12695   // Size of integers being compared has a critical role in the following
12696   // analysis, so we prefer to do this when all types are legal.
12697   if (!DCI.isAfterLegalizeDAG())
12698     return SDValue();
12699 
12700   // If all users of SETCC extend its value to a legal integer type
12701   // then we replace SETCC with a subtraction
12702   for (SDNode::use_iterator UI = N->use_begin(),
12703        UE = N->use_end(); UI != UE; ++UI) {
12704     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12705       return SDValue();
12706   }
12707 
12708   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12709   auto OpSize = N->getOperand(0).getValueSizeInBits();
12710 
12711   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12712 
12713   if (OpSize < Size) {
12714     switch (CC) {
12715     default: break;
12716     case ISD::SETULT:
12717       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12718     case ISD::SETULE:
12719       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12720     case ISD::SETUGT:
12721       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12722     case ISD::SETUGE:
12723       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12724     }
12725   }
12726 
12727   return SDValue();
12728 }
12729 
12730 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12731                                                   DAGCombinerInfo &DCI) const {
12732   SelectionDAG &DAG = DCI.DAG;
12733   SDLoc dl(N);
12734 
12735   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12736   // If we're tracking CR bits, we need to be careful that we don't have:
12737   //   trunc(binary-ops(zext(x), zext(y)))
12738   // or
12739   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12740   // such that we're unnecessarily moving things into GPRs when it would be
12741   // better to keep them in CR bits.
12742 
12743   // Note that trunc here can be an actual i1 trunc, or can be the effective
12744   // truncation that comes from a setcc or select_cc.
12745   if (N->getOpcode() == ISD::TRUNCATE &&
12746       N->getValueType(0) != MVT::i1)
12747     return SDValue();
12748 
12749   if (N->getOperand(0).getValueType() != MVT::i32 &&
12750       N->getOperand(0).getValueType() != MVT::i64)
12751     return SDValue();
12752 
12753   if (N->getOpcode() == ISD::SETCC ||
12754       N->getOpcode() == ISD::SELECT_CC) {
12755     // If we're looking at a comparison, then we need to make sure that the
12756     // high bits (all except for the first) don't matter the result.
12757     ISD::CondCode CC =
12758       cast<CondCodeSDNode>(N->getOperand(
12759         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12760     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12761 
12762     if (ISD::isSignedIntSetCC(CC)) {
12763       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12764           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12765         return SDValue();
12766     } else if (ISD::isUnsignedIntSetCC(CC)) {
12767       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12768                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12769           !DAG.MaskedValueIsZero(N->getOperand(1),
12770                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12771         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12772                                              : SDValue());
12773     } else {
12774       // This is neither a signed nor an unsigned comparison, just make sure
12775       // that the high bits are equal.
12776       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12777       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12778 
12779       // We don't really care about what is known about the first bit (if
12780       // anything), so clear it in all masks prior to comparing them.
12781       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12782       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12783 
12784       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12785         return SDValue();
12786     }
12787   }
12788 
12789   // We now know that the higher-order bits are irrelevant, we just need to
12790   // make sure that all of the intermediate operations are bit operations, and
12791   // all inputs are extensions.
12792   if (N->getOperand(0).getOpcode() != ISD::AND &&
12793       N->getOperand(0).getOpcode() != ISD::OR  &&
12794       N->getOperand(0).getOpcode() != ISD::XOR &&
12795       N->getOperand(0).getOpcode() != ISD::SELECT &&
12796       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12797       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12798       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12799       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12800       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12801     return SDValue();
12802 
12803   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12804       N->getOperand(1).getOpcode() != ISD::AND &&
12805       N->getOperand(1).getOpcode() != ISD::OR  &&
12806       N->getOperand(1).getOpcode() != ISD::XOR &&
12807       N->getOperand(1).getOpcode() != ISD::SELECT &&
12808       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12809       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12810       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12811       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12812       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12813     return SDValue();
12814 
12815   SmallVector<SDValue, 4> Inputs;
12816   SmallVector<SDValue, 8> BinOps, PromOps;
12817   SmallPtrSet<SDNode *, 16> Visited;
12818 
12819   for (unsigned i = 0; i < 2; ++i) {
12820     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12821           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12822           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12823           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12824         isa<ConstantSDNode>(N->getOperand(i)))
12825       Inputs.push_back(N->getOperand(i));
12826     else
12827       BinOps.push_back(N->getOperand(i));
12828 
12829     if (N->getOpcode() == ISD::TRUNCATE)
12830       break;
12831   }
12832 
12833   // Visit all inputs, collect all binary operations (and, or, xor and
12834   // select) that are all fed by extensions.
12835   while (!BinOps.empty()) {
12836     SDValue BinOp = BinOps.back();
12837     BinOps.pop_back();
12838 
12839     if (!Visited.insert(BinOp.getNode()).second)
12840       continue;
12841 
12842     PromOps.push_back(BinOp);
12843 
12844     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12845       // The condition of the select is not promoted.
12846       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12847         continue;
12848       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12849         continue;
12850 
12851       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12852             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12853             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12854            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12855           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12856         Inputs.push_back(BinOp.getOperand(i));
12857       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12858                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12859                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12860                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12861                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12862                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12863                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12864                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12865                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12866         BinOps.push_back(BinOp.getOperand(i));
12867       } else {
12868         // We have an input that is not an extension or another binary
12869         // operation; we'll abort this transformation.
12870         return SDValue();
12871       }
12872     }
12873   }
12874 
12875   // Make sure that this is a self-contained cluster of operations (which
12876   // is not quite the same thing as saying that everything has only one
12877   // use).
12878   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12879     if (isa<ConstantSDNode>(Inputs[i]))
12880       continue;
12881 
12882     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12883                               UE = Inputs[i].getNode()->use_end();
12884          UI != UE; ++UI) {
12885       SDNode *User = *UI;
12886       if (User != N && !Visited.count(User))
12887         return SDValue();
12888 
12889       // Make sure that we're not going to promote the non-output-value
12890       // operand(s) or SELECT or SELECT_CC.
12891       // FIXME: Although we could sometimes handle this, and it does occur in
12892       // practice that one of the condition inputs to the select is also one of
12893       // the outputs, we currently can't deal with this.
12894       if (User->getOpcode() == ISD::SELECT) {
12895         if (User->getOperand(0) == Inputs[i])
12896           return SDValue();
12897       } else if (User->getOpcode() == ISD::SELECT_CC) {
12898         if (User->getOperand(0) == Inputs[i] ||
12899             User->getOperand(1) == Inputs[i])
12900           return SDValue();
12901       }
12902     }
12903   }
12904 
12905   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12906     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12907                               UE = PromOps[i].getNode()->use_end();
12908          UI != UE; ++UI) {
12909       SDNode *User = *UI;
12910       if (User != N && !Visited.count(User))
12911         return SDValue();
12912 
12913       // Make sure that we're not going to promote the non-output-value
12914       // operand(s) or SELECT or SELECT_CC.
12915       // FIXME: Although we could sometimes handle this, and it does occur in
12916       // practice that one of the condition inputs to the select is also one of
12917       // the outputs, we currently can't deal with this.
12918       if (User->getOpcode() == ISD::SELECT) {
12919         if (User->getOperand(0) == PromOps[i])
12920           return SDValue();
12921       } else if (User->getOpcode() == ISD::SELECT_CC) {
12922         if (User->getOperand(0) == PromOps[i] ||
12923             User->getOperand(1) == PromOps[i])
12924           return SDValue();
12925       }
12926     }
12927   }
12928 
12929   // Replace all inputs with the extension operand.
12930   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12931     // Constants may have users outside the cluster of to-be-promoted nodes,
12932     // and so we need to replace those as we do the promotions.
12933     if (isa<ConstantSDNode>(Inputs[i]))
12934       continue;
12935     else
12936       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12937   }
12938 
12939   std::list<HandleSDNode> PromOpHandles;
12940   for (auto &PromOp : PromOps)
12941     PromOpHandles.emplace_back(PromOp);
12942 
12943   // Replace all operations (these are all the same, but have a different
12944   // (i1) return type). DAG.getNode will validate that the types of
12945   // a binary operator match, so go through the list in reverse so that
12946   // we've likely promoted both operands first. Any intermediate truncations or
12947   // extensions disappear.
12948   while (!PromOpHandles.empty()) {
12949     SDValue PromOp = PromOpHandles.back().getValue();
12950     PromOpHandles.pop_back();
12951 
12952     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12953         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12954         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12955         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12956       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12957           PromOp.getOperand(0).getValueType() != MVT::i1) {
12958         // The operand is not yet ready (see comment below).
12959         PromOpHandles.emplace_front(PromOp);
12960         continue;
12961       }
12962 
12963       SDValue RepValue = PromOp.getOperand(0);
12964       if (isa<ConstantSDNode>(RepValue))
12965         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12966 
12967       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12968       continue;
12969     }
12970 
12971     unsigned C;
12972     switch (PromOp.getOpcode()) {
12973     default:             C = 0; break;
12974     case ISD::SELECT:    C = 1; break;
12975     case ISD::SELECT_CC: C = 2; break;
12976     }
12977 
12978     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12979          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12980         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12981          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12982       // The to-be-promoted operands of this node have not yet been
12983       // promoted (this should be rare because we're going through the
12984       // list backward, but if one of the operands has several users in
12985       // this cluster of to-be-promoted nodes, it is possible).
12986       PromOpHandles.emplace_front(PromOp);
12987       continue;
12988     }
12989 
12990     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12991                                 PromOp.getNode()->op_end());
12992 
12993     // If there are any constant inputs, make sure they're replaced now.
12994     for (unsigned i = 0; i < 2; ++i)
12995       if (isa<ConstantSDNode>(Ops[C+i]))
12996         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12997 
12998     DAG.ReplaceAllUsesOfValueWith(PromOp,
12999       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13000   }
13001 
13002   // Now we're left with the initial truncation itself.
13003   if (N->getOpcode() == ISD::TRUNCATE)
13004     return N->getOperand(0);
13005 
13006   // Otherwise, this is a comparison. The operands to be compared have just
13007   // changed type (to i1), but everything else is the same.
13008   return SDValue(N, 0);
13009 }
13010 
13011 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13012                                                   DAGCombinerInfo &DCI) const {
13013   SelectionDAG &DAG = DCI.DAG;
13014   SDLoc dl(N);
13015 
13016   // If we're tracking CR bits, we need to be careful that we don't have:
13017   //   zext(binary-ops(trunc(x), trunc(y)))
13018   // or
13019   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13020   // such that we're unnecessarily moving things into CR bits that can more
13021   // efficiently stay in GPRs. Note that if we're not certain that the high
13022   // bits are set as required by the final extension, we still may need to do
13023   // some masking to get the proper behavior.
13024 
13025   // This same functionality is important on PPC64 when dealing with
13026   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13027   // the return values of functions. Because it is so similar, it is handled
13028   // here as well.
13029 
13030   if (N->getValueType(0) != MVT::i32 &&
13031       N->getValueType(0) != MVT::i64)
13032     return SDValue();
13033 
13034   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13035         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13036     return SDValue();
13037 
13038   if (N->getOperand(0).getOpcode() != ISD::AND &&
13039       N->getOperand(0).getOpcode() != ISD::OR  &&
13040       N->getOperand(0).getOpcode() != ISD::XOR &&
13041       N->getOperand(0).getOpcode() != ISD::SELECT &&
13042       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13043     return SDValue();
13044 
13045   SmallVector<SDValue, 4> Inputs;
13046   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13047   SmallPtrSet<SDNode *, 16> Visited;
13048 
13049   // Visit all inputs, collect all binary operations (and, or, xor and
13050   // select) that are all fed by truncations.
13051   while (!BinOps.empty()) {
13052     SDValue BinOp = BinOps.back();
13053     BinOps.pop_back();
13054 
13055     if (!Visited.insert(BinOp.getNode()).second)
13056       continue;
13057 
13058     PromOps.push_back(BinOp);
13059 
13060     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13061       // The condition of the select is not promoted.
13062       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13063         continue;
13064       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13065         continue;
13066 
13067       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13068           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13069         Inputs.push_back(BinOp.getOperand(i));
13070       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13071                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13072                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13073                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13074                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13075         BinOps.push_back(BinOp.getOperand(i));
13076       } else {
13077         // We have an input that is not a truncation or another binary
13078         // operation; we'll abort this transformation.
13079         return SDValue();
13080       }
13081     }
13082   }
13083 
13084   // The operands of a select that must be truncated when the select is
13085   // promoted because the operand is actually part of the to-be-promoted set.
13086   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13087 
13088   // Make sure that this is a self-contained cluster of operations (which
13089   // is not quite the same thing as saying that everything has only one
13090   // use).
13091   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13092     if (isa<ConstantSDNode>(Inputs[i]))
13093       continue;
13094 
13095     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13096                               UE = Inputs[i].getNode()->use_end();
13097          UI != UE; ++UI) {
13098       SDNode *User = *UI;
13099       if (User != N && !Visited.count(User))
13100         return SDValue();
13101 
13102       // If we're going to promote the non-output-value operand(s) or SELECT or
13103       // SELECT_CC, record them for truncation.
13104       if (User->getOpcode() == ISD::SELECT) {
13105         if (User->getOperand(0) == Inputs[i])
13106           SelectTruncOp[0].insert(std::make_pair(User,
13107                                     User->getOperand(0).getValueType()));
13108       } else if (User->getOpcode() == ISD::SELECT_CC) {
13109         if (User->getOperand(0) == Inputs[i])
13110           SelectTruncOp[0].insert(std::make_pair(User,
13111                                     User->getOperand(0).getValueType()));
13112         if (User->getOperand(1) == Inputs[i])
13113           SelectTruncOp[1].insert(std::make_pair(User,
13114                                     User->getOperand(1).getValueType()));
13115       }
13116     }
13117   }
13118 
13119   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13120     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13121                               UE = PromOps[i].getNode()->use_end();
13122          UI != UE; ++UI) {
13123       SDNode *User = *UI;
13124       if (User != N && !Visited.count(User))
13125         return SDValue();
13126 
13127       // If we're going to promote the non-output-value operand(s) or SELECT or
13128       // SELECT_CC, record them for truncation.
13129       if (User->getOpcode() == ISD::SELECT) {
13130         if (User->getOperand(0) == PromOps[i])
13131           SelectTruncOp[0].insert(std::make_pair(User,
13132                                     User->getOperand(0).getValueType()));
13133       } else if (User->getOpcode() == ISD::SELECT_CC) {
13134         if (User->getOperand(0) == PromOps[i])
13135           SelectTruncOp[0].insert(std::make_pair(User,
13136                                     User->getOperand(0).getValueType()));
13137         if (User->getOperand(1) == PromOps[i])
13138           SelectTruncOp[1].insert(std::make_pair(User,
13139                                     User->getOperand(1).getValueType()));
13140       }
13141     }
13142   }
13143 
13144   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13145   bool ReallyNeedsExt = false;
13146   if (N->getOpcode() != ISD::ANY_EXTEND) {
13147     // If all of the inputs are not already sign/zero extended, then
13148     // we'll still need to do that at the end.
13149     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13150       if (isa<ConstantSDNode>(Inputs[i]))
13151         continue;
13152 
13153       unsigned OpBits =
13154         Inputs[i].getOperand(0).getValueSizeInBits();
13155       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13156 
13157       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13158            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13159                                   APInt::getHighBitsSet(OpBits,
13160                                                         OpBits-PromBits))) ||
13161           (N->getOpcode() == ISD::SIGN_EXTEND &&
13162            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13163              (OpBits-(PromBits-1)))) {
13164         ReallyNeedsExt = true;
13165         break;
13166       }
13167     }
13168   }
13169 
13170   // Replace all inputs, either with the truncation operand, or a
13171   // truncation or extension to the final output type.
13172   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13173     // Constant inputs need to be replaced with the to-be-promoted nodes that
13174     // use them because they might have users outside of the cluster of
13175     // promoted nodes.
13176     if (isa<ConstantSDNode>(Inputs[i]))
13177       continue;
13178 
13179     SDValue InSrc = Inputs[i].getOperand(0);
13180     if (Inputs[i].getValueType() == N->getValueType(0))
13181       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13182     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13183       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13184         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13185     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13186       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13187         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13188     else
13189       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13190         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13191   }
13192 
13193   std::list<HandleSDNode> PromOpHandles;
13194   for (auto &PromOp : PromOps)
13195     PromOpHandles.emplace_back(PromOp);
13196 
13197   // Replace all operations (these are all the same, but have a different
13198   // (promoted) return type). DAG.getNode will validate that the types of
13199   // a binary operator match, so go through the list in reverse so that
13200   // we've likely promoted both operands first.
13201   while (!PromOpHandles.empty()) {
13202     SDValue PromOp = PromOpHandles.back().getValue();
13203     PromOpHandles.pop_back();
13204 
13205     unsigned C;
13206     switch (PromOp.getOpcode()) {
13207     default:             C = 0; break;
13208     case ISD::SELECT:    C = 1; break;
13209     case ISD::SELECT_CC: C = 2; break;
13210     }
13211 
13212     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13213          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13214         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13215          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13216       // The to-be-promoted operands of this node have not yet been
13217       // promoted (this should be rare because we're going through the
13218       // list backward, but if one of the operands has several users in
13219       // this cluster of to-be-promoted nodes, it is possible).
13220       PromOpHandles.emplace_front(PromOp);
13221       continue;
13222     }
13223 
13224     // For SELECT and SELECT_CC nodes, we do a similar check for any
13225     // to-be-promoted comparison inputs.
13226     if (PromOp.getOpcode() == ISD::SELECT ||
13227         PromOp.getOpcode() == ISD::SELECT_CC) {
13228       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13229            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13230           (SelectTruncOp[1].count(PromOp.getNode()) &&
13231            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13232         PromOpHandles.emplace_front(PromOp);
13233         continue;
13234       }
13235     }
13236 
13237     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13238                                 PromOp.getNode()->op_end());
13239 
13240     // If this node has constant inputs, then they'll need to be promoted here.
13241     for (unsigned i = 0; i < 2; ++i) {
13242       if (!isa<ConstantSDNode>(Ops[C+i]))
13243         continue;
13244       if (Ops[C+i].getValueType() == N->getValueType(0))
13245         continue;
13246 
13247       if (N->getOpcode() == ISD::SIGN_EXTEND)
13248         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13249       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13250         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13251       else
13252         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13253     }
13254 
13255     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13256     // truncate them again to the original value type.
13257     if (PromOp.getOpcode() == ISD::SELECT ||
13258         PromOp.getOpcode() == ISD::SELECT_CC) {
13259       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13260       if (SI0 != SelectTruncOp[0].end())
13261         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13262       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13263       if (SI1 != SelectTruncOp[1].end())
13264         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13265     }
13266 
13267     DAG.ReplaceAllUsesOfValueWith(PromOp,
13268       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13269   }
13270 
13271   // Now we're left with the initial extension itself.
13272   if (!ReallyNeedsExt)
13273     return N->getOperand(0);
13274 
13275   // To zero extend, just mask off everything except for the first bit (in the
13276   // i1 case).
13277   if (N->getOpcode() == ISD::ZERO_EXTEND)
13278     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13279                        DAG.getConstant(APInt::getLowBitsSet(
13280                                          N->getValueSizeInBits(0), PromBits),
13281                                        dl, N->getValueType(0)));
13282 
13283   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13284          "Invalid extension type");
13285   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13286   SDValue ShiftCst =
13287       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13288   return DAG.getNode(
13289       ISD::SRA, dl, N->getValueType(0),
13290       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13291       ShiftCst);
13292 }
13293 
13294 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13295                                         DAGCombinerInfo &DCI) const {
13296   assert(N->getOpcode() == ISD::SETCC &&
13297          "Should be called with a SETCC node");
13298 
13299   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13300   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13301     SDValue LHS = N->getOperand(0);
13302     SDValue RHS = N->getOperand(1);
13303 
13304     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13305     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13306         LHS.hasOneUse())
13307       std::swap(LHS, RHS);
13308 
13309     // x == 0-y --> x+y == 0
13310     // x != 0-y --> x+y != 0
13311     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13312         RHS.hasOneUse()) {
13313       SDLoc DL(N);
13314       SelectionDAG &DAG = DCI.DAG;
13315       EVT VT = N->getValueType(0);
13316       EVT OpVT = LHS.getValueType();
13317       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13318       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13319     }
13320   }
13321 
13322   return DAGCombineTruncBoolExt(N, DCI);
13323 }
13324 
13325 // Is this an extending load from an f32 to an f64?
13326 static bool isFPExtLoad(SDValue Op) {
13327   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13328     return LD->getExtensionType() == ISD::EXTLOAD &&
13329       Op.getValueType() == MVT::f64;
13330   return false;
13331 }
13332 
13333 /// Reduces the number of fp-to-int conversion when building a vector.
13334 ///
13335 /// If this vector is built out of floating to integer conversions,
13336 /// transform it to a vector built out of floating point values followed by a
13337 /// single floating to integer conversion of the vector.
13338 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13339 /// becomes (fptosi (build_vector ($A, $B, ...)))
13340 SDValue PPCTargetLowering::
13341 combineElementTruncationToVectorTruncation(SDNode *N,
13342                                            DAGCombinerInfo &DCI) const {
13343   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13344          "Should be called with a BUILD_VECTOR node");
13345 
13346   SelectionDAG &DAG = DCI.DAG;
13347   SDLoc dl(N);
13348 
13349   SDValue FirstInput = N->getOperand(0);
13350   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13351          "The input operand must be an fp-to-int conversion.");
13352 
13353   // This combine happens after legalization so the fp_to_[su]i nodes are
13354   // already converted to PPCSISD nodes.
13355   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13356   if (FirstConversion == PPCISD::FCTIDZ ||
13357       FirstConversion == PPCISD::FCTIDUZ ||
13358       FirstConversion == PPCISD::FCTIWZ ||
13359       FirstConversion == PPCISD::FCTIWUZ) {
13360     bool IsSplat = true;
13361     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13362       FirstConversion == PPCISD::FCTIWUZ;
13363     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13364     SmallVector<SDValue, 4> Ops;
13365     EVT TargetVT = N->getValueType(0);
13366     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13367       SDValue NextOp = N->getOperand(i);
13368       if (NextOp.getOpcode() != PPCISD::MFVSR)
13369         return SDValue();
13370       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13371       if (NextConversion != FirstConversion)
13372         return SDValue();
13373       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13374       // This is not valid if the input was originally double precision. It is
13375       // also not profitable to do unless this is an extending load in which
13376       // case doing this combine will allow us to combine consecutive loads.
13377       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13378         return SDValue();
13379       if (N->getOperand(i) != FirstInput)
13380         IsSplat = false;
13381     }
13382 
13383     // If this is a splat, we leave it as-is since there will be only a single
13384     // fp-to-int conversion followed by a splat of the integer. This is better
13385     // for 32-bit and smaller ints and neutral for 64-bit ints.
13386     if (IsSplat)
13387       return SDValue();
13388 
13389     // Now that we know we have the right type of node, get its operands
13390     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13391       SDValue In = N->getOperand(i).getOperand(0);
13392       if (Is32Bit) {
13393         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13394         // here, we know that all inputs are extending loads so this is safe).
13395         if (In.isUndef())
13396           Ops.push_back(DAG.getUNDEF(SrcVT));
13397         else {
13398           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13399                                       MVT::f32, In.getOperand(0),
13400                                       DAG.getIntPtrConstant(1, dl));
13401           Ops.push_back(Trunc);
13402         }
13403       } else
13404         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13405     }
13406 
13407     unsigned Opcode;
13408     if (FirstConversion == PPCISD::FCTIDZ ||
13409         FirstConversion == PPCISD::FCTIWZ)
13410       Opcode = ISD::FP_TO_SINT;
13411     else
13412       Opcode = ISD::FP_TO_UINT;
13413 
13414     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13415     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13416     return DAG.getNode(Opcode, dl, TargetVT, BV);
13417   }
13418   return SDValue();
13419 }
13420 
13421 /// Reduce the number of loads when building a vector.
13422 ///
13423 /// Building a vector out of multiple loads can be converted to a load
13424 /// of the vector type if the loads are consecutive. If the loads are
13425 /// consecutive but in descending order, a shuffle is added at the end
13426 /// to reorder the vector.
13427 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13428   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13429          "Should be called with a BUILD_VECTOR node");
13430 
13431   SDLoc dl(N);
13432 
13433   // Return early for non byte-sized type, as they can't be consecutive.
13434   if (!N->getValueType(0).getVectorElementType().isByteSized())
13435     return SDValue();
13436 
13437   bool InputsAreConsecutiveLoads = true;
13438   bool InputsAreReverseConsecutive = true;
13439   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13440   SDValue FirstInput = N->getOperand(0);
13441   bool IsRoundOfExtLoad = false;
13442 
13443   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13444       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13445     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13446     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13447   }
13448   // Not a build vector of (possibly fp_rounded) loads.
13449   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13450       N->getNumOperands() == 1)
13451     return SDValue();
13452 
13453   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13454     // If any inputs are fp_round(extload), they all must be.
13455     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13456       return SDValue();
13457 
13458     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13459       N->getOperand(i);
13460     if (NextInput.getOpcode() != ISD::LOAD)
13461       return SDValue();
13462 
13463     SDValue PreviousInput =
13464       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13465     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13466     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13467 
13468     // If any inputs are fp_round(extload), they all must be.
13469     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13470       return SDValue();
13471 
13472     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13473       InputsAreConsecutiveLoads = false;
13474     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13475       InputsAreReverseConsecutive = false;
13476 
13477     // Exit early if the loads are neither consecutive nor reverse consecutive.
13478     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13479       return SDValue();
13480   }
13481 
13482   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13483          "The loads cannot be both consecutive and reverse consecutive.");
13484 
13485   SDValue FirstLoadOp =
13486     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13487   SDValue LastLoadOp =
13488     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13489                        N->getOperand(N->getNumOperands()-1);
13490 
13491   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13492   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13493   if (InputsAreConsecutiveLoads) {
13494     assert(LD1 && "Input needs to be a LoadSDNode.");
13495     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13496                        LD1->getBasePtr(), LD1->getPointerInfo(),
13497                        LD1->getAlignment());
13498   }
13499   if (InputsAreReverseConsecutive) {
13500     assert(LDL && "Input needs to be a LoadSDNode.");
13501     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13502                                LDL->getBasePtr(), LDL->getPointerInfo(),
13503                                LDL->getAlignment());
13504     SmallVector<int, 16> Ops;
13505     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13506       Ops.push_back(i);
13507 
13508     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13509                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13510   }
13511   return SDValue();
13512 }
13513 
13514 // This function adds the required vector_shuffle needed to get
13515 // the elements of the vector extract in the correct position
13516 // as specified by the CorrectElems encoding.
13517 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13518                                       SDValue Input, uint64_t Elems,
13519                                       uint64_t CorrectElems) {
13520   SDLoc dl(N);
13521 
13522   unsigned NumElems = Input.getValueType().getVectorNumElements();
13523   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13524 
13525   // Knowing the element indices being extracted from the original
13526   // vector and the order in which they're being inserted, just put
13527   // them at element indices required for the instruction.
13528   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13529     if (DAG.getDataLayout().isLittleEndian())
13530       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13531     else
13532       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13533     CorrectElems = CorrectElems >> 8;
13534     Elems = Elems >> 8;
13535   }
13536 
13537   SDValue Shuffle =
13538       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13539                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13540 
13541   EVT VT = N->getValueType(0);
13542   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13543 
13544   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13545                                Input.getValueType().getVectorElementType(),
13546                                VT.getVectorNumElements());
13547   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13548                      DAG.getValueType(ExtVT));
13549 }
13550 
13551 // Look for build vector patterns where input operands come from sign
13552 // extended vector_extract elements of specific indices. If the correct indices
13553 // aren't used, add a vector shuffle to fix up the indices and create
13554 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13555 // during instruction selection.
13556 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13557   // This array encodes the indices that the vector sign extend instructions
13558   // extract from when extending from one type to another for both BE and LE.
13559   // The right nibble of each byte corresponds to the LE incides.
13560   // and the left nibble of each byte corresponds to the BE incides.
13561   // For example: 0x3074B8FC  byte->word
13562   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13563   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13564   // For example: 0x000070F8  byte->double word
13565   // For LE: the allowed indices are: 0x0,0x8
13566   // For BE: the allowed indices are: 0x7,0xF
13567   uint64_t TargetElems[] = {
13568       0x3074B8FC, // b->w
13569       0x000070F8, // b->d
13570       0x10325476, // h->w
13571       0x00003074, // h->d
13572       0x00001032, // w->d
13573   };
13574 
13575   uint64_t Elems = 0;
13576   int Index;
13577   SDValue Input;
13578 
13579   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13580     if (!Op)
13581       return false;
13582     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13583         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13584       return false;
13585 
13586     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13587     // of the right width.
13588     SDValue Extract = Op.getOperand(0);
13589     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13590       Extract = Extract.getOperand(0);
13591     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13592       return false;
13593 
13594     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13595     if (!ExtOp)
13596       return false;
13597 
13598     Index = ExtOp->getZExtValue();
13599     if (Input && Input != Extract.getOperand(0))
13600       return false;
13601 
13602     if (!Input)
13603       Input = Extract.getOperand(0);
13604 
13605     Elems = Elems << 8;
13606     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13607     Elems |= Index;
13608 
13609     return true;
13610   };
13611 
13612   // If the build vector operands aren't sign extended vector extracts,
13613   // of the same input vector, then return.
13614   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13615     if (!isSExtOfVecExtract(N->getOperand(i))) {
13616       return SDValue();
13617     }
13618   }
13619 
13620   // If the vector extract indicies are not correct, add the appropriate
13621   // vector_shuffle.
13622   int TgtElemArrayIdx;
13623   int InputSize = Input.getValueType().getScalarSizeInBits();
13624   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13625   if (InputSize + OutputSize == 40)
13626     TgtElemArrayIdx = 0;
13627   else if (InputSize + OutputSize == 72)
13628     TgtElemArrayIdx = 1;
13629   else if (InputSize + OutputSize == 48)
13630     TgtElemArrayIdx = 2;
13631   else if (InputSize + OutputSize == 80)
13632     TgtElemArrayIdx = 3;
13633   else if (InputSize + OutputSize == 96)
13634     TgtElemArrayIdx = 4;
13635   else
13636     return SDValue();
13637 
13638   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13639   CorrectElems = DAG.getDataLayout().isLittleEndian()
13640                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13641                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13642   if (Elems != CorrectElems) {
13643     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13644   }
13645 
13646   // Regular lowering will catch cases where a shuffle is not needed.
13647   return SDValue();
13648 }
13649 
13650 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13651                                                  DAGCombinerInfo &DCI) const {
13652   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13653          "Should be called with a BUILD_VECTOR node");
13654 
13655   SelectionDAG &DAG = DCI.DAG;
13656   SDLoc dl(N);
13657 
13658   if (!Subtarget.hasVSX())
13659     return SDValue();
13660 
13661   // The target independent DAG combiner will leave a build_vector of
13662   // float-to-int conversions intact. We can generate MUCH better code for
13663   // a float-to-int conversion of a vector of floats.
13664   SDValue FirstInput = N->getOperand(0);
13665   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13666     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13667     if (Reduced)
13668       return Reduced;
13669   }
13670 
13671   // If we're building a vector out of consecutive loads, just load that
13672   // vector type.
13673   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13674   if (Reduced)
13675     return Reduced;
13676 
13677   // If we're building a vector out of extended elements from another vector
13678   // we have P9 vector integer extend instructions. The code assumes legal
13679   // input types (i.e. it can't handle things like v4i16) so do not run before
13680   // legalization.
13681   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13682     Reduced = combineBVOfVecSExt(N, DAG);
13683     if (Reduced)
13684       return Reduced;
13685   }
13686 
13687 
13688   if (N->getValueType(0) != MVT::v2f64)
13689     return SDValue();
13690 
13691   // Looking for:
13692   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13693   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13694       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13695     return SDValue();
13696   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13697       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13698     return SDValue();
13699   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13700     return SDValue();
13701 
13702   SDValue Ext1 = FirstInput.getOperand(0);
13703   SDValue Ext2 = N->getOperand(1).getOperand(0);
13704   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13705      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13706     return SDValue();
13707 
13708   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13709   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13710   if (!Ext1Op || !Ext2Op)
13711     return SDValue();
13712   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13713       Ext1.getOperand(0) != Ext2.getOperand(0))
13714     return SDValue();
13715 
13716   int FirstElem = Ext1Op->getZExtValue();
13717   int SecondElem = Ext2Op->getZExtValue();
13718   int SubvecIdx;
13719   if (FirstElem == 0 && SecondElem == 1)
13720     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13721   else if (FirstElem == 2 && SecondElem == 3)
13722     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13723   else
13724     return SDValue();
13725 
13726   SDValue SrcVec = Ext1.getOperand(0);
13727   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13728     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13729   return DAG.getNode(NodeType, dl, MVT::v2f64,
13730                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13731 }
13732 
13733 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13734                                               DAGCombinerInfo &DCI) const {
13735   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13736           N->getOpcode() == ISD::UINT_TO_FP) &&
13737          "Need an int -> FP conversion node here");
13738 
13739   if (useSoftFloat() || !Subtarget.has64BitSupport())
13740     return SDValue();
13741 
13742   SelectionDAG &DAG = DCI.DAG;
13743   SDLoc dl(N);
13744   SDValue Op(N, 0);
13745 
13746   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13747   // from the hardware.
13748   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13749     return SDValue();
13750   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13751       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13752     return SDValue();
13753 
13754   SDValue FirstOperand(Op.getOperand(0));
13755   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13756     (FirstOperand.getValueType() == MVT::i8 ||
13757      FirstOperand.getValueType() == MVT::i16);
13758   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13759     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13760     bool DstDouble = Op.getValueType() == MVT::f64;
13761     unsigned ConvOp = Signed ?
13762       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13763       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13764     SDValue WidthConst =
13765       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13766                             dl, false);
13767     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13768     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13769     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13770                                          DAG.getVTList(MVT::f64, MVT::Other),
13771                                          Ops, MVT::i8, LDN->getMemOperand());
13772 
13773     // For signed conversion, we need to sign-extend the value in the VSR
13774     if (Signed) {
13775       SDValue ExtOps[] = { Ld, WidthConst };
13776       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13777       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13778     } else
13779       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13780   }
13781 
13782 
13783   // For i32 intermediate values, unfortunately, the conversion functions
13784   // leave the upper 32 bits of the value are undefined. Within the set of
13785   // scalar instructions, we have no method for zero- or sign-extending the
13786   // value. Thus, we cannot handle i32 intermediate values here.
13787   if (Op.getOperand(0).getValueType() == MVT::i32)
13788     return SDValue();
13789 
13790   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13791          "UINT_TO_FP is supported only with FPCVT");
13792 
13793   // If we have FCFIDS, then use it when converting to single-precision.
13794   // Otherwise, convert to double-precision and then round.
13795   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13796                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13797                                                             : PPCISD::FCFIDS)
13798                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13799                                                             : PPCISD::FCFID);
13800   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13801                   ? MVT::f32
13802                   : MVT::f64;
13803 
13804   // If we're converting from a float, to an int, and back to a float again,
13805   // then we don't need the store/load pair at all.
13806   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13807        Subtarget.hasFPCVT()) ||
13808       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13809     SDValue Src = Op.getOperand(0).getOperand(0);
13810     if (Src.getValueType() == MVT::f32) {
13811       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13812       DCI.AddToWorklist(Src.getNode());
13813     } else if (Src.getValueType() != MVT::f64) {
13814       // Make sure that we don't pick up a ppc_fp128 source value.
13815       return SDValue();
13816     }
13817 
13818     unsigned FCTOp =
13819       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13820                                                         PPCISD::FCTIDUZ;
13821 
13822     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13823     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13824 
13825     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13826       FP = DAG.getNode(ISD::FP_ROUND, dl,
13827                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13828       DCI.AddToWorklist(FP.getNode());
13829     }
13830 
13831     return FP;
13832   }
13833 
13834   return SDValue();
13835 }
13836 
13837 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13838 // builtins) into loads with swaps.
13839 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13840                                               DAGCombinerInfo &DCI) const {
13841   SelectionDAG &DAG = DCI.DAG;
13842   SDLoc dl(N);
13843   SDValue Chain;
13844   SDValue Base;
13845   MachineMemOperand *MMO;
13846 
13847   switch (N->getOpcode()) {
13848   default:
13849     llvm_unreachable("Unexpected opcode for little endian VSX load");
13850   case ISD::LOAD: {
13851     LoadSDNode *LD = cast<LoadSDNode>(N);
13852     Chain = LD->getChain();
13853     Base = LD->getBasePtr();
13854     MMO = LD->getMemOperand();
13855     // If the MMO suggests this isn't a load of a full vector, leave
13856     // things alone.  For a built-in, we have to make the change for
13857     // correctness, so if there is a size problem that will be a bug.
13858     if (MMO->getSize() < 16)
13859       return SDValue();
13860     break;
13861   }
13862   case ISD::INTRINSIC_W_CHAIN: {
13863     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13864     Chain = Intrin->getChain();
13865     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13866     // us what we want. Get operand 2 instead.
13867     Base = Intrin->getOperand(2);
13868     MMO = Intrin->getMemOperand();
13869     break;
13870   }
13871   }
13872 
13873   MVT VecTy = N->getValueType(0).getSimpleVT();
13874 
13875   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13876   // aligned and the type is a vector with elements up to 4 bytes
13877   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13878       VecTy.getScalarSizeInBits() <= 32) {
13879     return SDValue();
13880   }
13881 
13882   SDValue LoadOps[] = { Chain, Base };
13883   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13884                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13885                                          LoadOps, MVT::v2f64, MMO);
13886 
13887   DCI.AddToWorklist(Load.getNode());
13888   Chain = Load.getValue(1);
13889   SDValue Swap = DAG.getNode(
13890       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13891   DCI.AddToWorklist(Swap.getNode());
13892 
13893   // Add a bitcast if the resulting load type doesn't match v2f64.
13894   if (VecTy != MVT::v2f64) {
13895     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13896     DCI.AddToWorklist(N.getNode());
13897     // Package {bitcast value, swap's chain} to match Load's shape.
13898     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13899                        N, Swap.getValue(1));
13900   }
13901 
13902   return Swap;
13903 }
13904 
13905 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13906 // builtins) into stores with swaps.
13907 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13908                                                DAGCombinerInfo &DCI) const {
13909   SelectionDAG &DAG = DCI.DAG;
13910   SDLoc dl(N);
13911   SDValue Chain;
13912   SDValue Base;
13913   unsigned SrcOpnd;
13914   MachineMemOperand *MMO;
13915 
13916   switch (N->getOpcode()) {
13917   default:
13918     llvm_unreachable("Unexpected opcode for little endian VSX store");
13919   case ISD::STORE: {
13920     StoreSDNode *ST = cast<StoreSDNode>(N);
13921     Chain = ST->getChain();
13922     Base = ST->getBasePtr();
13923     MMO = ST->getMemOperand();
13924     SrcOpnd = 1;
13925     // If the MMO suggests this isn't a store of a full vector, leave
13926     // things alone.  For a built-in, we have to make the change for
13927     // correctness, so if there is a size problem that will be a bug.
13928     if (MMO->getSize() < 16)
13929       return SDValue();
13930     break;
13931   }
13932   case ISD::INTRINSIC_VOID: {
13933     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13934     Chain = Intrin->getChain();
13935     // Intrin->getBasePtr() oddly does not get what we want.
13936     Base = Intrin->getOperand(3);
13937     MMO = Intrin->getMemOperand();
13938     SrcOpnd = 2;
13939     break;
13940   }
13941   }
13942 
13943   SDValue Src = N->getOperand(SrcOpnd);
13944   MVT VecTy = Src.getValueType().getSimpleVT();
13945 
13946   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13947   // aligned and the type is a vector with elements up to 4 bytes
13948   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13949       VecTy.getScalarSizeInBits() <= 32) {
13950     return SDValue();
13951   }
13952 
13953   // All stores are done as v2f64 and possible bit cast.
13954   if (VecTy != MVT::v2f64) {
13955     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13956     DCI.AddToWorklist(Src.getNode());
13957   }
13958 
13959   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13960                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13961   DCI.AddToWorklist(Swap.getNode());
13962   Chain = Swap.getValue(1);
13963   SDValue StoreOps[] = { Chain, Swap, Base };
13964   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13965                                           DAG.getVTList(MVT::Other),
13966                                           StoreOps, VecTy, MMO);
13967   DCI.AddToWorklist(Store.getNode());
13968   return Store;
13969 }
13970 
13971 // Handle DAG combine for STORE (FP_TO_INT F).
13972 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13973                                                DAGCombinerInfo &DCI) const {
13974 
13975   SelectionDAG &DAG = DCI.DAG;
13976   SDLoc dl(N);
13977   unsigned Opcode = N->getOperand(1).getOpcode();
13978 
13979   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13980          && "Not a FP_TO_INT Instruction!");
13981 
13982   SDValue Val = N->getOperand(1).getOperand(0);
13983   EVT Op1VT = N->getOperand(1).getValueType();
13984   EVT ResVT = Val.getValueType();
13985 
13986   // Floating point types smaller than 32 bits are not legal on Power.
13987   if (ResVT.getScalarSizeInBits() < 32)
13988     return SDValue();
13989 
13990   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13991   bool ValidTypeForStoreFltAsInt =
13992         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13993          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13994 
13995   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13996       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13997     return SDValue();
13998 
13999   // Extend f32 values to f64
14000   if (ResVT.getScalarSizeInBits() == 32) {
14001     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14002     DCI.AddToWorklist(Val.getNode());
14003   }
14004 
14005   // Set signed or unsigned conversion opcode.
14006   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14007                           PPCISD::FP_TO_SINT_IN_VSR :
14008                           PPCISD::FP_TO_UINT_IN_VSR;
14009 
14010   Val = DAG.getNode(ConvOpcode,
14011                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14012   DCI.AddToWorklist(Val.getNode());
14013 
14014   // Set number of bytes being converted.
14015   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14016   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14017                     DAG.getIntPtrConstant(ByteSize, dl, false),
14018                     DAG.getValueType(Op1VT) };
14019 
14020   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14021           DAG.getVTList(MVT::Other), Ops,
14022           cast<StoreSDNode>(N)->getMemoryVT(),
14023           cast<StoreSDNode>(N)->getMemOperand());
14024 
14025   DCI.AddToWorklist(Val.getNode());
14026   return Val;
14027 }
14028 
14029 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14030                                                 LSBaseSDNode *LSBase,
14031                                                 DAGCombinerInfo &DCI) const {
14032   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14033         "Not a reverse memop pattern!");
14034 
14035   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14036     auto Mask = SVN->getMask();
14037     int i = 0;
14038     auto I = Mask.rbegin();
14039     auto E = Mask.rend();
14040 
14041     for (; I != E; ++I) {
14042       if (*I != i)
14043         return false;
14044       i++;
14045     }
14046     return true;
14047   };
14048 
14049   SelectionDAG &DAG = DCI.DAG;
14050   EVT VT = SVN->getValueType(0);
14051 
14052   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14053     return SDValue();
14054 
14055   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14056   // See comment in PPCVSXSwapRemoval.cpp.
14057   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14058   if (!Subtarget.hasP9Vector())
14059     return SDValue();
14060 
14061   if(!IsElementReverse(SVN))
14062     return SDValue();
14063 
14064   if (LSBase->getOpcode() == ISD::LOAD) {
14065     SDLoc dl(SVN);
14066     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14067     return DAG.getMemIntrinsicNode(
14068         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14069         LSBase->getMemoryVT(), LSBase->getMemOperand());
14070   }
14071 
14072   if (LSBase->getOpcode() == ISD::STORE) {
14073     SDLoc dl(LSBase);
14074     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14075                           LSBase->getBasePtr()};
14076     return DAG.getMemIntrinsicNode(
14077         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14078         LSBase->getMemoryVT(), LSBase->getMemOperand());
14079   }
14080 
14081   llvm_unreachable("Expected a load or store node here");
14082 }
14083 
14084 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14085                                              DAGCombinerInfo &DCI) const {
14086   SelectionDAG &DAG = DCI.DAG;
14087   SDLoc dl(N);
14088   switch (N->getOpcode()) {
14089   default: break;
14090   case ISD::ADD:
14091     return combineADD(N, DCI);
14092   case ISD::SHL:
14093     return combineSHL(N, DCI);
14094   case ISD::SRA:
14095     return combineSRA(N, DCI);
14096   case ISD::SRL:
14097     return combineSRL(N, DCI);
14098   case ISD::MUL:
14099     return combineMUL(N, DCI);
14100   case PPCISD::SHL:
14101     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14102         return N->getOperand(0);
14103     break;
14104   case PPCISD::SRL:
14105     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14106         return N->getOperand(0);
14107     break;
14108   case PPCISD::SRA:
14109     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14110       if (C->isNullValue() ||   //  0 >>s V -> 0.
14111           C->isAllOnesValue())    // -1 >>s V -> -1.
14112         return N->getOperand(0);
14113     }
14114     break;
14115   case ISD::SIGN_EXTEND:
14116   case ISD::ZERO_EXTEND:
14117   case ISD::ANY_EXTEND:
14118     return DAGCombineExtBoolTrunc(N, DCI);
14119   case ISD::TRUNCATE:
14120     return combineTRUNCATE(N, DCI);
14121   case ISD::SETCC:
14122     if (SDValue CSCC = combineSetCC(N, DCI))
14123       return CSCC;
14124     LLVM_FALLTHROUGH;
14125   case ISD::SELECT_CC:
14126     return DAGCombineTruncBoolExt(N, DCI);
14127   case ISD::SINT_TO_FP:
14128   case ISD::UINT_TO_FP:
14129     return combineFPToIntToFP(N, DCI);
14130   case ISD::VECTOR_SHUFFLE:
14131     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14132       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14133       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14134     }
14135     break;
14136   case ISD::STORE: {
14137 
14138     EVT Op1VT = N->getOperand(1).getValueType();
14139     unsigned Opcode = N->getOperand(1).getOpcode();
14140 
14141     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14142       SDValue Val= combineStoreFPToInt(N, DCI);
14143       if (Val)
14144         return Val;
14145     }
14146 
14147     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14148       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14149       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14150       if (Val)
14151         return Val;
14152     }
14153 
14154     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14155     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14156         N->getOperand(1).getNode()->hasOneUse() &&
14157         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14158          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14159 
14160       // STBRX can only handle simple types and it makes no sense to store less
14161       // two bytes in byte-reversed order.
14162       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14163       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14164         break;
14165 
14166       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14167       // Do an any-extend to 32-bits if this is a half-word input.
14168       if (BSwapOp.getValueType() == MVT::i16)
14169         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14170 
14171       // If the type of BSWAP operand is wider than stored memory width
14172       // it need to be shifted to the right side before STBRX.
14173       if (Op1VT.bitsGT(mVT)) {
14174         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14175         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14176                               DAG.getConstant(Shift, dl, MVT::i32));
14177         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14178         if (Op1VT == MVT::i64)
14179           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14180       }
14181 
14182       SDValue Ops[] = {
14183         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14184       };
14185       return
14186         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14187                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14188                                 cast<StoreSDNode>(N)->getMemOperand());
14189     }
14190 
14191     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14192     // So it can increase the chance of CSE constant construction.
14193     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14194         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14195       // Need to sign-extended to 64-bits to handle negative values.
14196       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14197       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14198                                     MemVT.getSizeInBits());
14199       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14200 
14201       // DAG.getTruncStore() can't be used here because it doesn't accept
14202       // the general (base + offset) addressing mode.
14203       // So we use UpdateNodeOperands and setTruncatingStore instead.
14204       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14205                              N->getOperand(3));
14206       cast<StoreSDNode>(N)->setTruncatingStore(true);
14207       return SDValue(N, 0);
14208     }
14209 
14210     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14211     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14212     if (Op1VT.isSimple()) {
14213       MVT StoreVT = Op1VT.getSimpleVT();
14214       if (Subtarget.needsSwapsForVSXMemOps() &&
14215           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14216            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14217         return expandVSXStoreForLE(N, DCI);
14218     }
14219     break;
14220   }
14221   case ISD::LOAD: {
14222     LoadSDNode *LD = cast<LoadSDNode>(N);
14223     EVT VT = LD->getValueType(0);
14224 
14225     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14226     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14227     if (VT.isSimple()) {
14228       MVT LoadVT = VT.getSimpleVT();
14229       if (Subtarget.needsSwapsForVSXMemOps() &&
14230           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14231            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14232         return expandVSXLoadForLE(N, DCI);
14233     }
14234 
14235     // We sometimes end up with a 64-bit integer load, from which we extract
14236     // two single-precision floating-point numbers. This happens with
14237     // std::complex<float>, and other similar structures, because of the way we
14238     // canonicalize structure copies. However, if we lack direct moves,
14239     // then the final bitcasts from the extracted integer values to the
14240     // floating-point numbers turn into store/load pairs. Even with direct moves,
14241     // just loading the two floating-point numbers is likely better.
14242     auto ReplaceTwoFloatLoad = [&]() {
14243       if (VT != MVT::i64)
14244         return false;
14245 
14246       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14247           LD->isVolatile())
14248         return false;
14249 
14250       //  We're looking for a sequence like this:
14251       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14252       //      t16: i64 = srl t13, Constant:i32<32>
14253       //    t17: i32 = truncate t16
14254       //  t18: f32 = bitcast t17
14255       //    t19: i32 = truncate t13
14256       //  t20: f32 = bitcast t19
14257 
14258       if (!LD->hasNUsesOfValue(2, 0))
14259         return false;
14260 
14261       auto UI = LD->use_begin();
14262       while (UI.getUse().getResNo() != 0) ++UI;
14263       SDNode *Trunc = *UI++;
14264       while (UI.getUse().getResNo() != 0) ++UI;
14265       SDNode *RightShift = *UI;
14266       if (Trunc->getOpcode() != ISD::TRUNCATE)
14267         std::swap(Trunc, RightShift);
14268 
14269       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14270           Trunc->getValueType(0) != MVT::i32 ||
14271           !Trunc->hasOneUse())
14272         return false;
14273       if (RightShift->getOpcode() != ISD::SRL ||
14274           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14275           RightShift->getConstantOperandVal(1) != 32 ||
14276           !RightShift->hasOneUse())
14277         return false;
14278 
14279       SDNode *Trunc2 = *RightShift->use_begin();
14280       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14281           Trunc2->getValueType(0) != MVT::i32 ||
14282           !Trunc2->hasOneUse())
14283         return false;
14284 
14285       SDNode *Bitcast = *Trunc->use_begin();
14286       SDNode *Bitcast2 = *Trunc2->use_begin();
14287 
14288       if (Bitcast->getOpcode() != ISD::BITCAST ||
14289           Bitcast->getValueType(0) != MVT::f32)
14290         return false;
14291       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14292           Bitcast2->getValueType(0) != MVT::f32)
14293         return false;
14294 
14295       if (Subtarget.isLittleEndian())
14296         std::swap(Bitcast, Bitcast2);
14297 
14298       // Bitcast has the second float (in memory-layout order) and Bitcast2
14299       // has the first one.
14300 
14301       SDValue BasePtr = LD->getBasePtr();
14302       if (LD->isIndexed()) {
14303         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14304                "Non-pre-inc AM on PPC?");
14305         BasePtr =
14306           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14307                       LD->getOffset());
14308       }
14309 
14310       auto MMOFlags =
14311           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14312       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14313                                       LD->getPointerInfo(), LD->getAlignment(),
14314                                       MMOFlags, LD->getAAInfo());
14315       SDValue AddPtr =
14316         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14317                     BasePtr, DAG.getIntPtrConstant(4, dl));
14318       SDValue FloatLoad2 = DAG.getLoad(
14319           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14320           LD->getPointerInfo().getWithOffset(4),
14321           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14322 
14323       if (LD->isIndexed()) {
14324         // Note that DAGCombine should re-form any pre-increment load(s) from
14325         // what is produced here if that makes sense.
14326         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14327       }
14328 
14329       DCI.CombineTo(Bitcast2, FloatLoad);
14330       DCI.CombineTo(Bitcast, FloatLoad2);
14331 
14332       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14333                                     SDValue(FloatLoad2.getNode(), 1));
14334       return true;
14335     };
14336 
14337     if (ReplaceTwoFloatLoad())
14338       return SDValue(N, 0);
14339 
14340     EVT MemVT = LD->getMemoryVT();
14341     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14342     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14343     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14344     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14345     if (LD->isUnindexed() && VT.isVector() &&
14346         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14347           // P8 and later hardware should just use LOAD.
14348           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14349                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14350          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14351           LD->getAlignment() >= ScalarABIAlignment)) &&
14352         LD->getAlignment() < ABIAlignment) {
14353       // This is a type-legal unaligned Altivec or QPX load.
14354       SDValue Chain = LD->getChain();
14355       SDValue Ptr = LD->getBasePtr();
14356       bool isLittleEndian = Subtarget.isLittleEndian();
14357 
14358       // This implements the loading of unaligned vectors as described in
14359       // the venerable Apple Velocity Engine overview. Specifically:
14360       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14361       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14362       //
14363       // The general idea is to expand a sequence of one or more unaligned
14364       // loads into an alignment-based permutation-control instruction (lvsl
14365       // or lvsr), a series of regular vector loads (which always truncate
14366       // their input address to an aligned address), and a series of
14367       // permutations.  The results of these permutations are the requested
14368       // loaded values.  The trick is that the last "extra" load is not taken
14369       // from the address you might suspect (sizeof(vector) bytes after the
14370       // last requested load), but rather sizeof(vector) - 1 bytes after the
14371       // last requested vector. The point of this is to avoid a page fault if
14372       // the base address happened to be aligned. This works because if the
14373       // base address is aligned, then adding less than a full vector length
14374       // will cause the last vector in the sequence to be (re)loaded.
14375       // Otherwise, the next vector will be fetched as you might suspect was
14376       // necessary.
14377 
14378       // We might be able to reuse the permutation generation from
14379       // a different base address offset from this one by an aligned amount.
14380       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14381       // optimization later.
14382       Intrinsic::ID Intr, IntrLD, IntrPerm;
14383       MVT PermCntlTy, PermTy, LDTy;
14384       if (Subtarget.hasAltivec()) {
14385         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14386                                  Intrinsic::ppc_altivec_lvsl;
14387         IntrLD = Intrinsic::ppc_altivec_lvx;
14388         IntrPerm = Intrinsic::ppc_altivec_vperm;
14389         PermCntlTy = MVT::v16i8;
14390         PermTy = MVT::v4i32;
14391         LDTy = MVT::v4i32;
14392       } else {
14393         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14394                                        Intrinsic::ppc_qpx_qvlpcls;
14395         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14396                                        Intrinsic::ppc_qpx_qvlfs;
14397         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14398         PermCntlTy = MVT::v4f64;
14399         PermTy = MVT::v4f64;
14400         LDTy = MemVT.getSimpleVT();
14401       }
14402 
14403       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14404 
14405       // Create the new MMO for the new base load. It is like the original MMO,
14406       // but represents an area in memory almost twice the vector size centered
14407       // on the original address. If the address is unaligned, we might start
14408       // reading up to (sizeof(vector)-1) bytes below the address of the
14409       // original unaligned load.
14410       MachineFunction &MF = DAG.getMachineFunction();
14411       MachineMemOperand *BaseMMO =
14412         MF.getMachineMemOperand(LD->getMemOperand(),
14413                                 -(long)MemVT.getStoreSize()+1,
14414                                 2*MemVT.getStoreSize()-1);
14415 
14416       // Create the new base load.
14417       SDValue LDXIntID =
14418           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14419       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14420       SDValue BaseLoad =
14421         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14422                                 DAG.getVTList(PermTy, MVT::Other),
14423                                 BaseLoadOps, LDTy, BaseMMO);
14424 
14425       // Note that the value of IncOffset (which is provided to the next
14426       // load's pointer info offset value, and thus used to calculate the
14427       // alignment), and the value of IncValue (which is actually used to
14428       // increment the pointer value) are different! This is because we
14429       // require the next load to appear to be aligned, even though it
14430       // is actually offset from the base pointer by a lesser amount.
14431       int IncOffset = VT.getSizeInBits() / 8;
14432       int IncValue = IncOffset;
14433 
14434       // Walk (both up and down) the chain looking for another load at the real
14435       // (aligned) offset (the alignment of the other load does not matter in
14436       // this case). If found, then do not use the offset reduction trick, as
14437       // that will prevent the loads from being later combined (as they would
14438       // otherwise be duplicates).
14439       if (!findConsecutiveLoad(LD, DAG))
14440         --IncValue;
14441 
14442       SDValue Increment =
14443           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14444       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14445 
14446       MachineMemOperand *ExtraMMO =
14447         MF.getMachineMemOperand(LD->getMemOperand(),
14448                                 1, 2*MemVT.getStoreSize()-1);
14449       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14450       SDValue ExtraLoad =
14451         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14452                                 DAG.getVTList(PermTy, MVT::Other),
14453                                 ExtraLoadOps, LDTy, ExtraMMO);
14454 
14455       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14456         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14457 
14458       // Because vperm has a big-endian bias, we must reverse the order
14459       // of the input vectors and complement the permute control vector
14460       // when generating little endian code.  We have already handled the
14461       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14462       // and ExtraLoad here.
14463       SDValue Perm;
14464       if (isLittleEndian)
14465         Perm = BuildIntrinsicOp(IntrPerm,
14466                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14467       else
14468         Perm = BuildIntrinsicOp(IntrPerm,
14469                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14470 
14471       if (VT != PermTy)
14472         Perm = Subtarget.hasAltivec() ?
14473                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14474                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14475                                DAG.getTargetConstant(1, dl, MVT::i64));
14476                                // second argument is 1 because this rounding
14477                                // is always exact.
14478 
14479       // The output of the permutation is our loaded result, the TokenFactor is
14480       // our new chain.
14481       DCI.CombineTo(N, Perm, TF);
14482       return SDValue(N, 0);
14483     }
14484     }
14485     break;
14486     case ISD::INTRINSIC_WO_CHAIN: {
14487       bool isLittleEndian = Subtarget.isLittleEndian();
14488       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14489       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14490                                            : Intrinsic::ppc_altivec_lvsl);
14491       if ((IID == Intr ||
14492            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14493            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14494         N->getOperand(1)->getOpcode() == ISD::ADD) {
14495         SDValue Add = N->getOperand(1);
14496 
14497         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14498                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14499 
14500         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14501                                   APInt::getAllOnesValue(Bits /* alignment */)
14502                                       .zext(Add.getScalarValueSizeInBits()))) {
14503           SDNode *BasePtr = Add->getOperand(0).getNode();
14504           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14505                                     UE = BasePtr->use_end();
14506                UI != UE; ++UI) {
14507             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14508                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14509               // We've found another LVSL/LVSR, and this address is an aligned
14510               // multiple of that one. The results will be the same, so use the
14511               // one we've just found instead.
14512 
14513               return SDValue(*UI, 0);
14514             }
14515           }
14516         }
14517 
14518         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14519           SDNode *BasePtr = Add->getOperand(0).getNode();
14520           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14521                UE = BasePtr->use_end(); UI != UE; ++UI) {
14522             if (UI->getOpcode() == ISD::ADD &&
14523                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14524                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14525                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14526                 (1ULL << Bits) == 0) {
14527               SDNode *OtherAdd = *UI;
14528               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14529                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14530                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14531                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14532                   return SDValue(*VI, 0);
14533                 }
14534               }
14535             }
14536           }
14537         }
14538       }
14539 
14540       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14541       // Expose the vabsduw/h/b opportunity for down stream
14542       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14543           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14544            IID == Intrinsic::ppc_altivec_vmaxsh ||
14545            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14546         SDValue V1 = N->getOperand(1);
14547         SDValue V2 = N->getOperand(2);
14548         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14549              V1.getSimpleValueType() == MVT::v8i16 ||
14550              V1.getSimpleValueType() == MVT::v16i8) &&
14551             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14552           // (0-a, a)
14553           if (V1.getOpcode() == ISD::SUB &&
14554               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14555               V1.getOperand(1) == V2) {
14556             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14557           }
14558           // (a, 0-a)
14559           if (V2.getOpcode() == ISD::SUB &&
14560               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14561               V2.getOperand(1) == V1) {
14562             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14563           }
14564           // (x-y, y-x)
14565           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14566               V1.getOperand(0) == V2.getOperand(1) &&
14567               V1.getOperand(1) == V2.getOperand(0)) {
14568             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14569           }
14570         }
14571       }
14572     }
14573 
14574     break;
14575   case ISD::INTRINSIC_W_CHAIN:
14576     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14577     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14578     if (Subtarget.needsSwapsForVSXMemOps()) {
14579       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14580       default:
14581         break;
14582       case Intrinsic::ppc_vsx_lxvw4x:
14583       case Intrinsic::ppc_vsx_lxvd2x:
14584         return expandVSXLoadForLE(N, DCI);
14585       }
14586     }
14587     break;
14588   case ISD::INTRINSIC_VOID:
14589     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14590     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14591     if (Subtarget.needsSwapsForVSXMemOps()) {
14592       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14593       default:
14594         break;
14595       case Intrinsic::ppc_vsx_stxvw4x:
14596       case Intrinsic::ppc_vsx_stxvd2x:
14597         return expandVSXStoreForLE(N, DCI);
14598       }
14599     }
14600     break;
14601   case ISD::BSWAP:
14602     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14603     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14604         N->getOperand(0).hasOneUse() &&
14605         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14606          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14607           N->getValueType(0) == MVT::i64))) {
14608       SDValue Load = N->getOperand(0);
14609       LoadSDNode *LD = cast<LoadSDNode>(Load);
14610       // Create the byte-swapping load.
14611       SDValue Ops[] = {
14612         LD->getChain(),    // Chain
14613         LD->getBasePtr(),  // Ptr
14614         DAG.getValueType(N->getValueType(0)) // VT
14615       };
14616       SDValue BSLoad =
14617         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14618                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14619                                               MVT::i64 : MVT::i32, MVT::Other),
14620                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14621 
14622       // If this is an i16 load, insert the truncate.
14623       SDValue ResVal = BSLoad;
14624       if (N->getValueType(0) == MVT::i16)
14625         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14626 
14627       // First, combine the bswap away.  This makes the value produced by the
14628       // load dead.
14629       DCI.CombineTo(N, ResVal);
14630 
14631       // Next, combine the load away, we give it a bogus result value but a real
14632       // chain result.  The result value is dead because the bswap is dead.
14633       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14634 
14635       // Return N so it doesn't get rechecked!
14636       return SDValue(N, 0);
14637     }
14638     break;
14639   case PPCISD::VCMP:
14640     // If a VCMPo node already exists with exactly the same operands as this
14641     // node, use its result instead of this node (VCMPo computes both a CR6 and
14642     // a normal output).
14643     //
14644     if (!N->getOperand(0).hasOneUse() &&
14645         !N->getOperand(1).hasOneUse() &&
14646         !N->getOperand(2).hasOneUse()) {
14647 
14648       // Scan all of the users of the LHS, looking for VCMPo's that match.
14649       SDNode *VCMPoNode = nullptr;
14650 
14651       SDNode *LHSN = N->getOperand(0).getNode();
14652       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14653            UI != E; ++UI)
14654         if (UI->getOpcode() == PPCISD::VCMPo &&
14655             UI->getOperand(1) == N->getOperand(1) &&
14656             UI->getOperand(2) == N->getOperand(2) &&
14657             UI->getOperand(0) == N->getOperand(0)) {
14658           VCMPoNode = *UI;
14659           break;
14660         }
14661 
14662       // If there is no VCMPo node, or if the flag value has a single use, don't
14663       // transform this.
14664       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14665         break;
14666 
14667       // Look at the (necessarily single) use of the flag value.  If it has a
14668       // chain, this transformation is more complex.  Note that multiple things
14669       // could use the value result, which we should ignore.
14670       SDNode *FlagUser = nullptr;
14671       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14672            FlagUser == nullptr; ++UI) {
14673         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14674         SDNode *User = *UI;
14675         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14676           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14677             FlagUser = User;
14678             break;
14679           }
14680         }
14681       }
14682 
14683       // If the user is a MFOCRF instruction, we know this is safe.
14684       // Otherwise we give up for right now.
14685       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14686         return SDValue(VCMPoNode, 0);
14687     }
14688     break;
14689   case ISD::BRCOND: {
14690     SDValue Cond = N->getOperand(1);
14691     SDValue Target = N->getOperand(2);
14692 
14693     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14694         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14695           Intrinsic::loop_decrement) {
14696 
14697       // We now need to make the intrinsic dead (it cannot be instruction
14698       // selected).
14699       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14700       assert(Cond.getNode()->hasOneUse() &&
14701              "Counter decrement has more than one use");
14702 
14703       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14704                          N->getOperand(0), Target);
14705     }
14706   }
14707   break;
14708   case ISD::BR_CC: {
14709     // If this is a branch on an altivec predicate comparison, lower this so
14710     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14711     // lowering is done pre-legalize, because the legalizer lowers the predicate
14712     // compare down to code that is difficult to reassemble.
14713     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14714     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14715 
14716     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14717     // value. If so, pass-through the AND to get to the intrinsic.
14718     if (LHS.getOpcode() == ISD::AND &&
14719         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14720         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14721           Intrinsic::loop_decrement &&
14722         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14723         !isNullConstant(LHS.getOperand(1)))
14724       LHS = LHS.getOperand(0);
14725 
14726     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14727         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14728           Intrinsic::loop_decrement &&
14729         isa<ConstantSDNode>(RHS)) {
14730       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14731              "Counter decrement comparison is not EQ or NE");
14732 
14733       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14734       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14735                     (CC == ISD::SETNE && !Val);
14736 
14737       // We now need to make the intrinsic dead (it cannot be instruction
14738       // selected).
14739       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14740       assert(LHS.getNode()->hasOneUse() &&
14741              "Counter decrement has more than one use");
14742 
14743       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14744                          N->getOperand(0), N->getOperand(4));
14745     }
14746 
14747     int CompareOpc;
14748     bool isDot;
14749 
14750     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14751         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14752         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14753       assert(isDot && "Can't compare against a vector result!");
14754 
14755       // If this is a comparison against something other than 0/1, then we know
14756       // that the condition is never/always true.
14757       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14758       if (Val != 0 && Val != 1) {
14759         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14760           return N->getOperand(0);
14761         // Always !=, turn it into an unconditional branch.
14762         return DAG.getNode(ISD::BR, dl, MVT::Other,
14763                            N->getOperand(0), N->getOperand(4));
14764       }
14765 
14766       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14767 
14768       // Create the PPCISD altivec 'dot' comparison node.
14769       SDValue Ops[] = {
14770         LHS.getOperand(2),  // LHS of compare
14771         LHS.getOperand(3),  // RHS of compare
14772         DAG.getConstant(CompareOpc, dl, MVT::i32)
14773       };
14774       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14775       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14776 
14777       // Unpack the result based on how the target uses it.
14778       PPC::Predicate CompOpc;
14779       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14780       default:  // Can't happen, don't crash on invalid number though.
14781       case 0:   // Branch on the value of the EQ bit of CR6.
14782         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14783         break;
14784       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14785         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14786         break;
14787       case 2:   // Branch on the value of the LT bit of CR6.
14788         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14789         break;
14790       case 3:   // Branch on the inverted value of the LT bit of CR6.
14791         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14792         break;
14793       }
14794 
14795       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14796                          DAG.getConstant(CompOpc, dl, MVT::i32),
14797                          DAG.getRegister(PPC::CR6, MVT::i32),
14798                          N->getOperand(4), CompNode.getValue(1));
14799     }
14800     break;
14801   }
14802   case ISD::BUILD_VECTOR:
14803     return DAGCombineBuildVector(N, DCI);
14804   case ISD::ABS:
14805     return combineABS(N, DCI);
14806   case ISD::VSELECT:
14807     return combineVSelect(N, DCI);
14808   }
14809 
14810   return SDValue();
14811 }
14812 
14813 SDValue
14814 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14815                                  SelectionDAG &DAG,
14816                                  SmallVectorImpl<SDNode *> &Created) const {
14817   // fold (sdiv X, pow2)
14818   EVT VT = N->getValueType(0);
14819   if (VT == MVT::i64 && !Subtarget.isPPC64())
14820     return SDValue();
14821   if ((VT != MVT::i32 && VT != MVT::i64) ||
14822       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14823     return SDValue();
14824 
14825   SDLoc DL(N);
14826   SDValue N0 = N->getOperand(0);
14827 
14828   bool IsNegPow2 = (-Divisor).isPowerOf2();
14829   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14830   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14831 
14832   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14833   Created.push_back(Op.getNode());
14834 
14835   if (IsNegPow2) {
14836     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14837     Created.push_back(Op.getNode());
14838   }
14839 
14840   return Op;
14841 }
14842 
14843 //===----------------------------------------------------------------------===//
14844 // Inline Assembly Support
14845 //===----------------------------------------------------------------------===//
14846 
14847 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14848                                                       KnownBits &Known,
14849                                                       const APInt &DemandedElts,
14850                                                       const SelectionDAG &DAG,
14851                                                       unsigned Depth) const {
14852   Known.resetAll();
14853   switch (Op.getOpcode()) {
14854   default: break;
14855   case PPCISD::LBRX: {
14856     // lhbrx is known to have the top bits cleared out.
14857     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14858       Known.Zero = 0xFFFF0000;
14859     break;
14860   }
14861   case ISD::INTRINSIC_WO_CHAIN: {
14862     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14863     default: break;
14864     case Intrinsic::ppc_altivec_vcmpbfp_p:
14865     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14866     case Intrinsic::ppc_altivec_vcmpequb_p:
14867     case Intrinsic::ppc_altivec_vcmpequh_p:
14868     case Intrinsic::ppc_altivec_vcmpequw_p:
14869     case Intrinsic::ppc_altivec_vcmpequd_p:
14870     case Intrinsic::ppc_altivec_vcmpgefp_p:
14871     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14872     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14873     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14874     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14875     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14876     case Intrinsic::ppc_altivec_vcmpgtub_p:
14877     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14878     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14879     case Intrinsic::ppc_altivec_vcmpgtud_p:
14880       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14881       break;
14882     }
14883   }
14884   }
14885 }
14886 
14887 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14888   switch (Subtarget.getCPUDirective()) {
14889   default: break;
14890   case PPC::DIR_970:
14891   case PPC::DIR_PWR4:
14892   case PPC::DIR_PWR5:
14893   case PPC::DIR_PWR5X:
14894   case PPC::DIR_PWR6:
14895   case PPC::DIR_PWR6X:
14896   case PPC::DIR_PWR7:
14897   case PPC::DIR_PWR8:
14898   case PPC::DIR_PWR9:
14899   case PPC::DIR_PWR_FUTURE: {
14900     if (!ML)
14901       break;
14902 
14903     if (!DisableInnermostLoopAlign32) {
14904       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14905       // so that we can decrease cache misses and branch-prediction misses.
14906       // Actual alignment of the loop will depend on the hotness check and other
14907       // logic in alignBlocks.
14908       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14909         return Align(32);
14910     }
14911 
14912     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14913 
14914     // For small loops (between 5 and 8 instructions), align to a 32-byte
14915     // boundary so that the entire loop fits in one instruction-cache line.
14916     uint64_t LoopSize = 0;
14917     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14918       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14919         LoopSize += TII->getInstSizeInBytes(*J);
14920         if (LoopSize > 32)
14921           break;
14922       }
14923 
14924     if (LoopSize > 16 && LoopSize <= 32)
14925       return Align(32);
14926 
14927     break;
14928   }
14929   }
14930 
14931   return TargetLowering::getPrefLoopAlignment(ML);
14932 }
14933 
14934 /// getConstraintType - Given a constraint, return the type of
14935 /// constraint it is for this target.
14936 PPCTargetLowering::ConstraintType
14937 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14938   if (Constraint.size() == 1) {
14939     switch (Constraint[0]) {
14940     default: break;
14941     case 'b':
14942     case 'r':
14943     case 'f':
14944     case 'd':
14945     case 'v':
14946     case 'y':
14947       return C_RegisterClass;
14948     case 'Z':
14949       // FIXME: While Z does indicate a memory constraint, it specifically
14950       // indicates an r+r address (used in conjunction with the 'y' modifier
14951       // in the replacement string). Currently, we're forcing the base
14952       // register to be r0 in the asm printer (which is interpreted as zero)
14953       // and forming the complete address in the second register. This is
14954       // suboptimal.
14955       return C_Memory;
14956     }
14957   } else if (Constraint == "wc") { // individual CR bits.
14958     return C_RegisterClass;
14959   } else if (Constraint == "wa" || Constraint == "wd" ||
14960              Constraint == "wf" || Constraint == "ws" ||
14961              Constraint == "wi" || Constraint == "ww") {
14962     return C_RegisterClass; // VSX registers.
14963   }
14964   return TargetLowering::getConstraintType(Constraint);
14965 }
14966 
14967 /// Examine constraint type and operand type and determine a weight value.
14968 /// This object must already have been set up with the operand type
14969 /// and the current alternative constraint selected.
14970 TargetLowering::ConstraintWeight
14971 PPCTargetLowering::getSingleConstraintMatchWeight(
14972     AsmOperandInfo &info, const char *constraint) const {
14973   ConstraintWeight weight = CW_Invalid;
14974   Value *CallOperandVal = info.CallOperandVal;
14975     // If we don't have a value, we can't do a match,
14976     // but allow it at the lowest weight.
14977   if (!CallOperandVal)
14978     return CW_Default;
14979   Type *type = CallOperandVal->getType();
14980 
14981   // Look at the constraint type.
14982   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14983     return CW_Register; // an individual CR bit.
14984   else if ((StringRef(constraint) == "wa" ||
14985             StringRef(constraint) == "wd" ||
14986             StringRef(constraint) == "wf") &&
14987            type->isVectorTy())
14988     return CW_Register;
14989   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14990     return CW_Register; // just hold 64-bit integers data.
14991   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14992     return CW_Register;
14993   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14994     return CW_Register;
14995 
14996   switch (*constraint) {
14997   default:
14998     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14999     break;
15000   case 'b':
15001     if (type->isIntegerTy())
15002       weight = CW_Register;
15003     break;
15004   case 'f':
15005     if (type->isFloatTy())
15006       weight = CW_Register;
15007     break;
15008   case 'd':
15009     if (type->isDoubleTy())
15010       weight = CW_Register;
15011     break;
15012   case 'v':
15013     if (type->isVectorTy())
15014       weight = CW_Register;
15015     break;
15016   case 'y':
15017     weight = CW_Register;
15018     break;
15019   case 'Z':
15020     weight = CW_Memory;
15021     break;
15022   }
15023   return weight;
15024 }
15025 
15026 std::pair<unsigned, const TargetRegisterClass *>
15027 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15028                                                 StringRef Constraint,
15029                                                 MVT VT) const {
15030   if (Constraint.size() == 1) {
15031     // GCC RS6000 Constraint Letters
15032     switch (Constraint[0]) {
15033     case 'b':   // R1-R31
15034       if (VT == MVT::i64 && Subtarget.isPPC64())
15035         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15036       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15037     case 'r':   // R0-R31
15038       if (VT == MVT::i64 && Subtarget.isPPC64())
15039         return std::make_pair(0U, &PPC::G8RCRegClass);
15040       return std::make_pair(0U, &PPC::GPRCRegClass);
15041     // 'd' and 'f' constraints are both defined to be "the floating point
15042     // registers", where one is for 32-bit and the other for 64-bit. We don't
15043     // really care overly much here so just give them all the same reg classes.
15044     case 'd':
15045     case 'f':
15046       if (Subtarget.hasSPE()) {
15047         if (VT == MVT::f32 || VT == MVT::i32)
15048           return std::make_pair(0U, &PPC::GPRCRegClass);
15049         if (VT == MVT::f64 || VT == MVT::i64)
15050           return std::make_pair(0U, &PPC::SPERCRegClass);
15051       } else {
15052         if (VT == MVT::f32 || VT == MVT::i32)
15053           return std::make_pair(0U, &PPC::F4RCRegClass);
15054         if (VT == MVT::f64 || VT == MVT::i64)
15055           return std::make_pair(0U, &PPC::F8RCRegClass);
15056         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15057           return std::make_pair(0U, &PPC::QFRCRegClass);
15058         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15059           return std::make_pair(0U, &PPC::QSRCRegClass);
15060       }
15061       break;
15062     case 'v':
15063       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15064         return std::make_pair(0U, &PPC::QFRCRegClass);
15065       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15066         return std::make_pair(0U, &PPC::QSRCRegClass);
15067       if (Subtarget.hasAltivec())
15068         return std::make_pair(0U, &PPC::VRRCRegClass);
15069       break;
15070     case 'y':   // crrc
15071       return std::make_pair(0U, &PPC::CRRCRegClass);
15072     }
15073   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15074     // An individual CR bit.
15075     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15076   } else if ((Constraint == "wa" || Constraint == "wd" ||
15077              Constraint == "wf" || Constraint == "wi") &&
15078              Subtarget.hasVSX()) {
15079     return std::make_pair(0U, &PPC::VSRCRegClass);
15080   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15081     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15082       return std::make_pair(0U, &PPC::VSSRCRegClass);
15083     else
15084       return std::make_pair(0U, &PPC::VSFRCRegClass);
15085   }
15086 
15087   // If we name a VSX register, we can't defer to the base class because it
15088   // will not recognize the correct register (their names will be VSL{0-31}
15089   // and V{0-31} so they won't match). So we match them here.
15090   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15091     int VSNum = atoi(Constraint.data() + 3);
15092     assert(VSNum >= 0 && VSNum <= 63 &&
15093            "Attempted to access a vsr out of range");
15094     if (VSNum < 32)
15095       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15096     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15097   }
15098   std::pair<unsigned, const TargetRegisterClass *> R =
15099       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15100 
15101   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15102   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15103   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15104   // register.
15105   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15106   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15107   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15108       PPC::GPRCRegClass.contains(R.first))
15109     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15110                             PPC::sub_32, &PPC::G8RCRegClass),
15111                           &PPC::G8RCRegClass);
15112 
15113   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15114   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15115     R.first = PPC::CR0;
15116     R.second = &PPC::CRRCRegClass;
15117   }
15118 
15119   return R;
15120 }
15121 
15122 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15123 /// vector.  If it is invalid, don't add anything to Ops.
15124 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15125                                                      std::string &Constraint,
15126                                                      std::vector<SDValue>&Ops,
15127                                                      SelectionDAG &DAG) const {
15128   SDValue Result;
15129 
15130   // Only support length 1 constraints.
15131   if (Constraint.length() > 1) return;
15132 
15133   char Letter = Constraint[0];
15134   switch (Letter) {
15135   default: break;
15136   case 'I':
15137   case 'J':
15138   case 'K':
15139   case 'L':
15140   case 'M':
15141   case 'N':
15142   case 'O':
15143   case 'P': {
15144     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15145     if (!CST) return; // Must be an immediate to match.
15146     SDLoc dl(Op);
15147     int64_t Value = CST->getSExtValue();
15148     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15149                          // numbers are printed as such.
15150     switch (Letter) {
15151     default: llvm_unreachable("Unknown constraint letter!");
15152     case 'I':  // "I" is a signed 16-bit constant.
15153       if (isInt<16>(Value))
15154         Result = DAG.getTargetConstant(Value, dl, TCVT);
15155       break;
15156     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15157       if (isShiftedUInt<16, 16>(Value))
15158         Result = DAG.getTargetConstant(Value, dl, TCVT);
15159       break;
15160     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15161       if (isShiftedInt<16, 16>(Value))
15162         Result = DAG.getTargetConstant(Value, dl, TCVT);
15163       break;
15164     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15165       if (isUInt<16>(Value))
15166         Result = DAG.getTargetConstant(Value, dl, TCVT);
15167       break;
15168     case 'M':  // "M" is a constant that is greater than 31.
15169       if (Value > 31)
15170         Result = DAG.getTargetConstant(Value, dl, TCVT);
15171       break;
15172     case 'N':  // "N" is a positive constant that is an exact power of two.
15173       if (Value > 0 && isPowerOf2_64(Value))
15174         Result = DAG.getTargetConstant(Value, dl, TCVT);
15175       break;
15176     case 'O':  // "O" is the constant zero.
15177       if (Value == 0)
15178         Result = DAG.getTargetConstant(Value, dl, TCVT);
15179       break;
15180     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15181       if (isInt<16>(-Value))
15182         Result = DAG.getTargetConstant(Value, dl, TCVT);
15183       break;
15184     }
15185     break;
15186   }
15187   }
15188 
15189   if (Result.getNode()) {
15190     Ops.push_back(Result);
15191     return;
15192   }
15193 
15194   // Handle standard constraint letters.
15195   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15196 }
15197 
15198 // isLegalAddressingMode - Return true if the addressing mode represented
15199 // by AM is legal for this target, for a load/store of the specified type.
15200 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15201                                               const AddrMode &AM, Type *Ty,
15202                                               unsigned AS, Instruction *I) const {
15203   // PPC does not allow r+i addressing modes for vectors!
15204   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15205     return false;
15206 
15207   // PPC allows a sign-extended 16-bit immediate field.
15208   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15209     return false;
15210 
15211   // No global is ever allowed as a base.
15212   if (AM.BaseGV)
15213     return false;
15214 
15215   // PPC only support r+r,
15216   switch (AM.Scale) {
15217   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15218     break;
15219   case 1:
15220     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15221       return false;
15222     // Otherwise we have r+r or r+i.
15223     break;
15224   case 2:
15225     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15226       return false;
15227     // Allow 2*r as r+r.
15228     break;
15229   default:
15230     // No other scales are supported.
15231     return false;
15232   }
15233 
15234   return true;
15235 }
15236 
15237 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15238                                            SelectionDAG &DAG) const {
15239   MachineFunction &MF = DAG.getMachineFunction();
15240   MachineFrameInfo &MFI = MF.getFrameInfo();
15241   MFI.setReturnAddressIsTaken(true);
15242 
15243   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15244     return SDValue();
15245 
15246   SDLoc dl(Op);
15247   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15248 
15249   // Make sure the function does not optimize away the store of the RA to
15250   // the stack.
15251   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15252   FuncInfo->setLRStoreRequired();
15253   bool isPPC64 = Subtarget.isPPC64();
15254   auto PtrVT = getPointerTy(MF.getDataLayout());
15255 
15256   if (Depth > 0) {
15257     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15258     SDValue Offset =
15259         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15260                         isPPC64 ? MVT::i64 : MVT::i32);
15261     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15262                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15263                        MachinePointerInfo());
15264   }
15265 
15266   // Just load the return address off the stack.
15267   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15268   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15269                      MachinePointerInfo());
15270 }
15271 
15272 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15273                                           SelectionDAG &DAG) const {
15274   SDLoc dl(Op);
15275   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15276 
15277   MachineFunction &MF = DAG.getMachineFunction();
15278   MachineFrameInfo &MFI = MF.getFrameInfo();
15279   MFI.setFrameAddressIsTaken(true);
15280 
15281   EVT PtrVT = getPointerTy(MF.getDataLayout());
15282   bool isPPC64 = PtrVT == MVT::i64;
15283 
15284   // Naked functions never have a frame pointer, and so we use r1. For all
15285   // other functions, this decision must be delayed until during PEI.
15286   unsigned FrameReg;
15287   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15288     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15289   else
15290     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15291 
15292   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15293                                          PtrVT);
15294   while (Depth--)
15295     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15296                             FrameAddr, MachinePointerInfo());
15297   return FrameAddr;
15298 }
15299 
15300 // FIXME? Maybe this could be a TableGen attribute on some registers and
15301 // this table could be generated automatically from RegInfo.
15302 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15303                                               const MachineFunction &MF) const {
15304   bool isPPC64 = Subtarget.isPPC64();
15305 
15306   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15307   if (!is64Bit && VT != LLT::scalar(32))
15308     report_fatal_error("Invalid register global variable type");
15309 
15310   Register Reg = StringSwitch<Register>(RegName)
15311                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15312                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15313                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15314                      .Default(Register());
15315 
15316   if (Reg)
15317     return Reg;
15318   report_fatal_error("Invalid register name global variable");
15319 }
15320 
15321 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15322   // 32-bit SVR4 ABI access everything as got-indirect.
15323   if (Subtarget.is32BitELFABI())
15324     return true;
15325 
15326   // AIX accesses everything indirectly through the TOC, which is similar to
15327   // the GOT.
15328   if (Subtarget.isAIXABI())
15329     return true;
15330 
15331   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15332   // If it is small or large code model, module locals are accessed
15333   // indirectly by loading their address from .toc/.got.
15334   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15335     return true;
15336 
15337   // JumpTable and BlockAddress are accessed as got-indirect.
15338   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15339     return true;
15340 
15341   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15342     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15343 
15344   return false;
15345 }
15346 
15347 bool
15348 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15349   // The PowerPC target isn't yet aware of offsets.
15350   return false;
15351 }
15352 
15353 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15354                                            const CallInst &I,
15355                                            MachineFunction &MF,
15356                                            unsigned Intrinsic) const {
15357   switch (Intrinsic) {
15358   case Intrinsic::ppc_qpx_qvlfd:
15359   case Intrinsic::ppc_qpx_qvlfs:
15360   case Intrinsic::ppc_qpx_qvlfcd:
15361   case Intrinsic::ppc_qpx_qvlfcs:
15362   case Intrinsic::ppc_qpx_qvlfiwa:
15363   case Intrinsic::ppc_qpx_qvlfiwz:
15364   case Intrinsic::ppc_altivec_lvx:
15365   case Intrinsic::ppc_altivec_lvxl:
15366   case Intrinsic::ppc_altivec_lvebx:
15367   case Intrinsic::ppc_altivec_lvehx:
15368   case Intrinsic::ppc_altivec_lvewx:
15369   case Intrinsic::ppc_vsx_lxvd2x:
15370   case Intrinsic::ppc_vsx_lxvw4x: {
15371     EVT VT;
15372     switch (Intrinsic) {
15373     case Intrinsic::ppc_altivec_lvebx:
15374       VT = MVT::i8;
15375       break;
15376     case Intrinsic::ppc_altivec_lvehx:
15377       VT = MVT::i16;
15378       break;
15379     case Intrinsic::ppc_altivec_lvewx:
15380       VT = MVT::i32;
15381       break;
15382     case Intrinsic::ppc_vsx_lxvd2x:
15383       VT = MVT::v2f64;
15384       break;
15385     case Intrinsic::ppc_qpx_qvlfd:
15386       VT = MVT::v4f64;
15387       break;
15388     case Intrinsic::ppc_qpx_qvlfs:
15389       VT = MVT::v4f32;
15390       break;
15391     case Intrinsic::ppc_qpx_qvlfcd:
15392       VT = MVT::v2f64;
15393       break;
15394     case Intrinsic::ppc_qpx_qvlfcs:
15395       VT = MVT::v2f32;
15396       break;
15397     default:
15398       VT = MVT::v4i32;
15399       break;
15400     }
15401 
15402     Info.opc = ISD::INTRINSIC_W_CHAIN;
15403     Info.memVT = VT;
15404     Info.ptrVal = I.getArgOperand(0);
15405     Info.offset = -VT.getStoreSize()+1;
15406     Info.size = 2*VT.getStoreSize()-1;
15407     Info.align = Align(1);
15408     Info.flags = MachineMemOperand::MOLoad;
15409     return true;
15410   }
15411   case Intrinsic::ppc_qpx_qvlfda:
15412   case Intrinsic::ppc_qpx_qvlfsa:
15413   case Intrinsic::ppc_qpx_qvlfcda:
15414   case Intrinsic::ppc_qpx_qvlfcsa:
15415   case Intrinsic::ppc_qpx_qvlfiwaa:
15416   case Intrinsic::ppc_qpx_qvlfiwza: {
15417     EVT VT;
15418     switch (Intrinsic) {
15419     case Intrinsic::ppc_qpx_qvlfda:
15420       VT = MVT::v4f64;
15421       break;
15422     case Intrinsic::ppc_qpx_qvlfsa:
15423       VT = MVT::v4f32;
15424       break;
15425     case Intrinsic::ppc_qpx_qvlfcda:
15426       VT = MVT::v2f64;
15427       break;
15428     case Intrinsic::ppc_qpx_qvlfcsa:
15429       VT = MVT::v2f32;
15430       break;
15431     default:
15432       VT = MVT::v4i32;
15433       break;
15434     }
15435 
15436     Info.opc = ISD::INTRINSIC_W_CHAIN;
15437     Info.memVT = VT;
15438     Info.ptrVal = I.getArgOperand(0);
15439     Info.offset = 0;
15440     Info.size = VT.getStoreSize();
15441     Info.align = Align(1);
15442     Info.flags = MachineMemOperand::MOLoad;
15443     return true;
15444   }
15445   case Intrinsic::ppc_qpx_qvstfd:
15446   case Intrinsic::ppc_qpx_qvstfs:
15447   case Intrinsic::ppc_qpx_qvstfcd:
15448   case Intrinsic::ppc_qpx_qvstfcs:
15449   case Intrinsic::ppc_qpx_qvstfiw:
15450   case Intrinsic::ppc_altivec_stvx:
15451   case Intrinsic::ppc_altivec_stvxl:
15452   case Intrinsic::ppc_altivec_stvebx:
15453   case Intrinsic::ppc_altivec_stvehx:
15454   case Intrinsic::ppc_altivec_stvewx:
15455   case Intrinsic::ppc_vsx_stxvd2x:
15456   case Intrinsic::ppc_vsx_stxvw4x: {
15457     EVT VT;
15458     switch (Intrinsic) {
15459     case Intrinsic::ppc_altivec_stvebx:
15460       VT = MVT::i8;
15461       break;
15462     case Intrinsic::ppc_altivec_stvehx:
15463       VT = MVT::i16;
15464       break;
15465     case Intrinsic::ppc_altivec_stvewx:
15466       VT = MVT::i32;
15467       break;
15468     case Intrinsic::ppc_vsx_stxvd2x:
15469       VT = MVT::v2f64;
15470       break;
15471     case Intrinsic::ppc_qpx_qvstfd:
15472       VT = MVT::v4f64;
15473       break;
15474     case Intrinsic::ppc_qpx_qvstfs:
15475       VT = MVT::v4f32;
15476       break;
15477     case Intrinsic::ppc_qpx_qvstfcd:
15478       VT = MVT::v2f64;
15479       break;
15480     case Intrinsic::ppc_qpx_qvstfcs:
15481       VT = MVT::v2f32;
15482       break;
15483     default:
15484       VT = MVT::v4i32;
15485       break;
15486     }
15487 
15488     Info.opc = ISD::INTRINSIC_VOID;
15489     Info.memVT = VT;
15490     Info.ptrVal = I.getArgOperand(1);
15491     Info.offset = -VT.getStoreSize()+1;
15492     Info.size = 2*VT.getStoreSize()-1;
15493     Info.align = Align(1);
15494     Info.flags = MachineMemOperand::MOStore;
15495     return true;
15496   }
15497   case Intrinsic::ppc_qpx_qvstfda:
15498   case Intrinsic::ppc_qpx_qvstfsa:
15499   case Intrinsic::ppc_qpx_qvstfcda:
15500   case Intrinsic::ppc_qpx_qvstfcsa:
15501   case Intrinsic::ppc_qpx_qvstfiwa: {
15502     EVT VT;
15503     switch (Intrinsic) {
15504     case Intrinsic::ppc_qpx_qvstfda:
15505       VT = MVT::v4f64;
15506       break;
15507     case Intrinsic::ppc_qpx_qvstfsa:
15508       VT = MVT::v4f32;
15509       break;
15510     case Intrinsic::ppc_qpx_qvstfcda:
15511       VT = MVT::v2f64;
15512       break;
15513     case Intrinsic::ppc_qpx_qvstfcsa:
15514       VT = MVT::v2f32;
15515       break;
15516     default:
15517       VT = MVT::v4i32;
15518       break;
15519     }
15520 
15521     Info.opc = ISD::INTRINSIC_VOID;
15522     Info.memVT = VT;
15523     Info.ptrVal = I.getArgOperand(1);
15524     Info.offset = 0;
15525     Info.size = VT.getStoreSize();
15526     Info.align = Align(1);
15527     Info.flags = MachineMemOperand::MOStore;
15528     return true;
15529   }
15530   default:
15531     break;
15532   }
15533 
15534   return false;
15535 }
15536 
15537 /// It returns EVT::Other if the type should be determined using generic
15538 /// target-independent logic.
15539 EVT PPCTargetLowering::getOptimalMemOpType(
15540     const MemOp &Op, const AttributeList &FuncAttributes) const {
15541   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15542     // When expanding a memset, require at least two QPX instructions to cover
15543     // the cost of loading the value to be stored from the constant pool.
15544     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15545         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15546         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15547       return MVT::v4f64;
15548     }
15549 
15550     // We should use Altivec/VSX loads and stores when available. For unaligned
15551     // addresses, unaligned VSX loads are only fast starting with the P8.
15552     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15553         (Op.isAligned(Align(16)) ||
15554          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15555       return MVT::v4i32;
15556   }
15557 
15558   if (Subtarget.isPPC64()) {
15559     return MVT::i64;
15560   }
15561 
15562   return MVT::i32;
15563 }
15564 
15565 /// Returns true if it is beneficial to convert a load of a constant
15566 /// to just the constant itself.
15567 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15568                                                           Type *Ty) const {
15569   assert(Ty->isIntegerTy());
15570 
15571   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15572   return !(BitSize == 0 || BitSize > 64);
15573 }
15574 
15575 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15576   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15577     return false;
15578   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15579   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15580   return NumBits1 == 64 && NumBits2 == 32;
15581 }
15582 
15583 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15584   if (!VT1.isInteger() || !VT2.isInteger())
15585     return false;
15586   unsigned NumBits1 = VT1.getSizeInBits();
15587   unsigned NumBits2 = VT2.getSizeInBits();
15588   return NumBits1 == 64 && NumBits2 == 32;
15589 }
15590 
15591 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15592   // Generally speaking, zexts are not free, but they are free when they can be
15593   // folded with other operations.
15594   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15595     EVT MemVT = LD->getMemoryVT();
15596     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15597          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15598         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15599          LD->getExtensionType() == ISD::ZEXTLOAD))
15600       return true;
15601   }
15602 
15603   // FIXME: Add other cases...
15604   //  - 32-bit shifts with a zext to i64
15605   //  - zext after ctlz, bswap, etc.
15606   //  - zext after and by a constant mask
15607 
15608   return TargetLowering::isZExtFree(Val, VT2);
15609 }
15610 
15611 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15612   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15613          "invalid fpext types");
15614   // Extending to float128 is not free.
15615   if (DestVT == MVT::f128)
15616     return false;
15617   return true;
15618 }
15619 
15620 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15621   return isInt<16>(Imm) || isUInt<16>(Imm);
15622 }
15623 
15624 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15625   return isInt<16>(Imm) || isUInt<16>(Imm);
15626 }
15627 
15628 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15629                                                        unsigned,
15630                                                        unsigned,
15631                                                        MachineMemOperand::Flags,
15632                                                        bool *Fast) const {
15633   if (DisablePPCUnaligned)
15634     return false;
15635 
15636   // PowerPC supports unaligned memory access for simple non-vector types.
15637   // Although accessing unaligned addresses is not as efficient as accessing
15638   // aligned addresses, it is generally more efficient than manual expansion,
15639   // and generally only traps for software emulation when crossing page
15640   // boundaries.
15641 
15642   if (!VT.isSimple())
15643     return false;
15644 
15645   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15646     return false;
15647 
15648   if (VT.getSimpleVT().isVector()) {
15649     if (Subtarget.hasVSX()) {
15650       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15651           VT != MVT::v4f32 && VT != MVT::v4i32)
15652         return false;
15653     } else {
15654       return false;
15655     }
15656   }
15657 
15658   if (VT == MVT::ppcf128)
15659     return false;
15660 
15661   if (Fast)
15662     *Fast = true;
15663 
15664   return true;
15665 }
15666 
15667 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15668                                                    EVT VT) const {
15669   return isFMAFasterThanFMulAndFAdd(
15670       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15671 }
15672 
15673 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15674                                                    Type *Ty) const {
15675   switch (Ty->getScalarType()->getTypeID()) {
15676   case Type::FloatTyID:
15677   case Type::DoubleTyID:
15678     return true;
15679   case Type::FP128TyID:
15680     return EnableQuadPrecision && Subtarget.hasP9Vector();
15681   default:
15682     return false;
15683   }
15684 }
15685 
15686 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15687 // FIXME: add more patterns which are profitable to hoist.
15688 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15689   if (I->getOpcode() != Instruction::FMul)
15690     return true;
15691 
15692   if (!I->hasOneUse())
15693     return true;
15694 
15695   Instruction *User = I->user_back();
15696   assert(User && "A single use instruction with no uses.");
15697 
15698   if (User->getOpcode() != Instruction::FSub &&
15699       User->getOpcode() != Instruction::FAdd)
15700     return true;
15701 
15702   const TargetOptions &Options = getTargetMachine().Options;
15703   const Function *F = I->getFunction();
15704   const DataLayout &DL = F->getParent()->getDataLayout();
15705   Type *Ty = User->getOperand(0)->getType();
15706 
15707   return !(
15708       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15709       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15710       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15711 }
15712 
15713 const MCPhysReg *
15714 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15715   // LR is a callee-save register, but we must treat it as clobbered by any call
15716   // site. Hence we include LR in the scratch registers, which are in turn added
15717   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15718   // to CTR, which is used by any indirect call.
15719   static const MCPhysReg ScratchRegs[] = {
15720     PPC::X12, PPC::LR8, PPC::CTR8, 0
15721   };
15722 
15723   return ScratchRegs;
15724 }
15725 
15726 Register PPCTargetLowering::getExceptionPointerRegister(
15727     const Constant *PersonalityFn) const {
15728   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15729 }
15730 
15731 Register PPCTargetLowering::getExceptionSelectorRegister(
15732     const Constant *PersonalityFn) const {
15733   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15734 }
15735 
15736 bool
15737 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15738                      EVT VT , unsigned DefinedValues) const {
15739   if (VT == MVT::v2i64)
15740     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15741 
15742   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15743     return true;
15744 
15745   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15746 }
15747 
15748 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15749   if (DisableILPPref || Subtarget.enableMachineScheduler())
15750     return TargetLowering::getSchedulingPreference(N);
15751 
15752   return Sched::ILP;
15753 }
15754 
15755 // Create a fast isel object.
15756 FastISel *
15757 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15758                                   const TargetLibraryInfo *LibInfo) const {
15759   return PPC::createFastISel(FuncInfo, LibInfo);
15760 }
15761 
15762 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15763 bool PPCTargetLowering::useLoadStackGuardNode() const {
15764   if (!Subtarget.isTargetLinux())
15765     return TargetLowering::useLoadStackGuardNode();
15766   return true;
15767 }
15768 
15769 // Override to disable global variable loading on Linux.
15770 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15771   if (!Subtarget.isTargetLinux())
15772     return TargetLowering::insertSSPDeclarations(M);
15773 }
15774 
15775 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15776                                      bool ForCodeSize) const {
15777   if (!VT.isSimple() || !Subtarget.hasVSX())
15778     return false;
15779 
15780   switch(VT.getSimpleVT().SimpleTy) {
15781   default:
15782     // For FP types that are currently not supported by PPC backend, return
15783     // false. Examples: f16, f80.
15784     return false;
15785   case MVT::f32:
15786   case MVT::f64:
15787   case MVT::ppcf128:
15788     return Imm.isPosZero();
15789   }
15790 }
15791 
15792 // For vector shift operation op, fold
15793 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15794 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15795                                   SelectionDAG &DAG) {
15796   SDValue N0 = N->getOperand(0);
15797   SDValue N1 = N->getOperand(1);
15798   EVT VT = N0.getValueType();
15799   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15800   unsigned Opcode = N->getOpcode();
15801   unsigned TargetOpcode;
15802 
15803   switch (Opcode) {
15804   default:
15805     llvm_unreachable("Unexpected shift operation");
15806   case ISD::SHL:
15807     TargetOpcode = PPCISD::SHL;
15808     break;
15809   case ISD::SRL:
15810     TargetOpcode = PPCISD::SRL;
15811     break;
15812   case ISD::SRA:
15813     TargetOpcode = PPCISD::SRA;
15814     break;
15815   }
15816 
15817   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15818       N1->getOpcode() == ISD::AND)
15819     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15820       if (Mask->getZExtValue() == OpSizeInBits - 1)
15821         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15822 
15823   return SDValue();
15824 }
15825 
15826 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15827   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15828     return Value;
15829 
15830   SDValue N0 = N->getOperand(0);
15831   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15832   if (!Subtarget.isISA3_0() ||
15833       N0.getOpcode() != ISD::SIGN_EXTEND ||
15834       N0.getOperand(0).getValueType() != MVT::i32 ||
15835       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15836     return SDValue();
15837 
15838   // We can't save an operation here if the value is already extended, and
15839   // the existing shift is easier to combine.
15840   SDValue ExtsSrc = N0.getOperand(0);
15841   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15842       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15843     return SDValue();
15844 
15845   SDLoc DL(N0);
15846   SDValue ShiftBy = SDValue(CN1, 0);
15847   // We want the shift amount to be i32 on the extswli, but the shift could
15848   // have an i64.
15849   if (ShiftBy.getValueType() == MVT::i64)
15850     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15851 
15852   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15853                          ShiftBy);
15854 }
15855 
15856 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15857   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15858     return Value;
15859 
15860   return SDValue();
15861 }
15862 
15863 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15864   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15865     return Value;
15866 
15867   return SDValue();
15868 }
15869 
15870 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15871 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15872 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15873 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15874 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15875                                  const PPCSubtarget &Subtarget) {
15876   if (!Subtarget.isPPC64())
15877     return SDValue();
15878 
15879   SDValue LHS = N->getOperand(0);
15880   SDValue RHS = N->getOperand(1);
15881 
15882   auto isZextOfCompareWithConstant = [](SDValue Op) {
15883     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15884         Op.getValueType() != MVT::i64)
15885       return false;
15886 
15887     SDValue Cmp = Op.getOperand(0);
15888     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15889         Cmp.getOperand(0).getValueType() != MVT::i64)
15890       return false;
15891 
15892     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15893       int64_t NegConstant = 0 - Constant->getSExtValue();
15894       // Due to the limitations of the addi instruction,
15895       // -C is required to be [-32768, 32767].
15896       return isInt<16>(NegConstant);
15897     }
15898 
15899     return false;
15900   };
15901 
15902   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15903   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15904 
15905   // If there is a pattern, canonicalize a zext operand to the RHS.
15906   if (LHSHasPattern && !RHSHasPattern)
15907     std::swap(LHS, RHS);
15908   else if (!LHSHasPattern && !RHSHasPattern)
15909     return SDValue();
15910 
15911   SDLoc DL(N);
15912   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15913   SDValue Cmp = RHS.getOperand(0);
15914   SDValue Z = Cmp.getOperand(0);
15915   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15916 
15917   assert(Constant && "Constant Should not be a null pointer.");
15918   int64_t NegConstant = 0 - Constant->getSExtValue();
15919 
15920   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15921   default: break;
15922   case ISD::SETNE: {
15923     //                                 when C == 0
15924     //                             --> addze X, (addic Z, -1).carry
15925     //                            /
15926     // add X, (zext(setne Z, C))--
15927     //                            \    when -32768 <= -C <= 32767 && C != 0
15928     //                             --> addze X, (addic (addi Z, -C), -1).carry
15929     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15930                               DAG.getConstant(NegConstant, DL, MVT::i64));
15931     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15932     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15933                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15934     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15935                        SDValue(Addc.getNode(), 1));
15936     }
15937   case ISD::SETEQ: {
15938     //                                 when C == 0
15939     //                             --> addze X, (subfic Z, 0).carry
15940     //                            /
15941     // add X, (zext(sete  Z, C))--
15942     //                            \    when -32768 <= -C <= 32767 && C != 0
15943     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15944     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15945                               DAG.getConstant(NegConstant, DL, MVT::i64));
15946     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15947     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15948                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15949     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15950                        SDValue(Subc.getNode(), 1));
15951     }
15952   }
15953 
15954   return SDValue();
15955 }
15956 
15957 // Transform
15958 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
15959 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
15960 // In this case both C1 and C2 must be known constants.
15961 // C1+C2 must fit into a 34 bit signed integer.
15962 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
15963                                           const PPCSubtarget &Subtarget) {
15964   if (!Subtarget.isUsingPCRelativeCalls())
15965     return SDValue();
15966 
15967   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
15968   // If we find that node try to cast the Global Address and the Constant.
15969   SDValue LHS = N->getOperand(0);
15970   SDValue RHS = N->getOperand(1);
15971 
15972   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15973     std::swap(LHS, RHS);
15974 
15975   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15976     return SDValue();
15977 
15978   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
15979   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
15980   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
15981 
15982   // Check that both casts succeeded.
15983   if (!GSDN || !ConstNode)
15984     return SDValue();
15985 
15986   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
15987   SDLoc DL(GSDN);
15988 
15989   // The signed int offset needs to fit in 34 bits.
15990   if (!isInt<34>(NewOffset))
15991     return SDValue();
15992 
15993   // The new global address is a copy of the old global address except
15994   // that it has the updated Offset.
15995   SDValue GA =
15996       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
15997                                  NewOffset, GSDN->getTargetFlags());
15998   SDValue MatPCRel =
15999       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16000   return MatPCRel;
16001 }
16002 
16003 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16004   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16005     return Value;
16006 
16007   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16008     return Value;
16009 
16010   return SDValue();
16011 }
16012 
16013 // Detect TRUNCATE operations on bitcasts of float128 values.
16014 // What we are looking for here is the situtation where we extract a subset
16015 // of bits from a 128 bit float.
16016 // This can be of two forms:
16017 // 1) BITCAST of f128 feeding TRUNCATE
16018 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16019 // The reason this is required is because we do not have a legal i128 type
16020 // and so we want to prevent having to store the f128 and then reload part
16021 // of it.
16022 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16023                                            DAGCombinerInfo &DCI) const {
16024   // If we are using CRBits then try that first.
16025   if (Subtarget.useCRBits()) {
16026     // Check if CRBits did anything and return that if it did.
16027     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16028       return CRTruncValue;
16029   }
16030 
16031   SDLoc dl(N);
16032   SDValue Op0 = N->getOperand(0);
16033 
16034   // Looking for a truncate of i128 to i64.
16035   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16036     return SDValue();
16037 
16038   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16039 
16040   // SRL feeding TRUNCATE.
16041   if (Op0.getOpcode() == ISD::SRL) {
16042     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16043     // The right shift has to be by 64 bits.
16044     if (!ConstNode || ConstNode->getZExtValue() != 64)
16045       return SDValue();
16046 
16047     // Switch the element number to extract.
16048     EltToExtract = EltToExtract ? 0 : 1;
16049     // Update Op0 past the SRL.
16050     Op0 = Op0.getOperand(0);
16051   }
16052 
16053   // BITCAST feeding a TRUNCATE possibly via SRL.
16054   if (Op0.getOpcode() == ISD::BITCAST &&
16055       Op0.getValueType() == MVT::i128 &&
16056       Op0.getOperand(0).getValueType() == MVT::f128) {
16057     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16058     return DCI.DAG.getNode(
16059         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16060         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16061   }
16062   return SDValue();
16063 }
16064 
16065 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16066   SelectionDAG &DAG = DCI.DAG;
16067 
16068   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16069   if (!ConstOpOrElement)
16070     return SDValue();
16071 
16072   // An imul is usually smaller than the alternative sequence for legal type.
16073   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16074       isOperationLegal(ISD::MUL, N->getValueType(0)))
16075     return SDValue();
16076 
16077   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16078     switch (this->Subtarget.getCPUDirective()) {
16079     default:
16080       // TODO: enhance the condition for subtarget before pwr8
16081       return false;
16082     case PPC::DIR_PWR8:
16083       //  type        mul     add    shl
16084       // scalar        4       1      1
16085       // vector        7       2      2
16086       return true;
16087     case PPC::DIR_PWR9:
16088     case PPC::DIR_PWR_FUTURE:
16089       //  type        mul     add    shl
16090       // scalar        5       2      2
16091       // vector        7       2      2
16092 
16093       // The cycle RATIO of related operations are showed as a table above.
16094       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16095       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16096       // are 4, it is always profitable; but for 3 instrs patterns
16097       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16098       // So we should only do it for vector type.
16099       return IsAddOne && IsNeg ? VT.isVector() : true;
16100     }
16101   };
16102 
16103   EVT VT = N->getValueType(0);
16104   SDLoc DL(N);
16105 
16106   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16107   bool IsNeg = MulAmt.isNegative();
16108   APInt MulAmtAbs = MulAmt.abs();
16109 
16110   if ((MulAmtAbs - 1).isPowerOf2()) {
16111     // (mul x, 2^N + 1) => (add (shl x, N), x)
16112     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16113 
16114     if (!IsProfitable(IsNeg, true, VT))
16115       return SDValue();
16116 
16117     SDValue Op0 = N->getOperand(0);
16118     SDValue Op1 =
16119         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16120                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16121     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16122 
16123     if (!IsNeg)
16124       return Res;
16125 
16126     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16127   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16128     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16129     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16130 
16131     if (!IsProfitable(IsNeg, false, VT))
16132       return SDValue();
16133 
16134     SDValue Op0 = N->getOperand(0);
16135     SDValue Op1 =
16136         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16137                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16138 
16139     if (!IsNeg)
16140       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16141     else
16142       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16143 
16144   } else {
16145     return SDValue();
16146   }
16147 }
16148 
16149 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16150   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16151   if (!Subtarget.is64BitELFABI())
16152     return false;
16153 
16154   // If not a tail call then no need to proceed.
16155   if (!CI->isTailCall())
16156     return false;
16157 
16158   // If sibling calls have been disabled and tail-calls aren't guaranteed
16159   // there is no reason to duplicate.
16160   auto &TM = getTargetMachine();
16161   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16162     return false;
16163 
16164   // Can't tail call a function called indirectly, or if it has variadic args.
16165   const Function *Callee = CI->getCalledFunction();
16166   if (!Callee || Callee->isVarArg())
16167     return false;
16168 
16169   // Make sure the callee and caller calling conventions are eligible for tco.
16170   const Function *Caller = CI->getParent()->getParent();
16171   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16172                                            CI->getCallingConv()))
16173       return false;
16174 
16175   // If the function is local then we have a good chance at tail-calling it
16176   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16177 }
16178 
16179 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16180   if (!Subtarget.hasVSX())
16181     return false;
16182   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16183     return true;
16184   return VT == MVT::f32 || VT == MVT::f64 ||
16185     VT == MVT::v4f32 || VT == MVT::v2f64;
16186 }
16187 
16188 bool PPCTargetLowering::
16189 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16190   const Value *Mask = AndI.getOperand(1);
16191   // If the mask is suitable for andi. or andis. we should sink the and.
16192   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16193     // Can't handle constants wider than 64-bits.
16194     if (CI->getBitWidth() > 64)
16195       return false;
16196     int64_t ConstVal = CI->getZExtValue();
16197     return isUInt<16>(ConstVal) ||
16198       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16199   }
16200 
16201   // For non-constant masks, we can always use the record-form and.
16202   return true;
16203 }
16204 
16205 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16206 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16207 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16208 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16209 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16210 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16211   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16212   assert(Subtarget.hasP9Altivec() &&
16213          "Only combine this when P9 altivec supported!");
16214   EVT VT = N->getValueType(0);
16215   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16216     return SDValue();
16217 
16218   SelectionDAG &DAG = DCI.DAG;
16219   SDLoc dl(N);
16220   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16221     // Even for signed integers, if it's known to be positive (as signed
16222     // integer) due to zero-extended inputs.
16223     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16224     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16225     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16226          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16227         (SubOpcd1 == ISD::ZERO_EXTEND ||
16228          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16229       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16230                          N->getOperand(0)->getOperand(0),
16231                          N->getOperand(0)->getOperand(1),
16232                          DAG.getTargetConstant(0, dl, MVT::i32));
16233     }
16234 
16235     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16236     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16237         N->getOperand(0).hasOneUse()) {
16238       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16239                          N->getOperand(0)->getOperand(0),
16240                          N->getOperand(0)->getOperand(1),
16241                          DAG.getTargetConstant(1, dl, MVT::i32));
16242     }
16243   }
16244 
16245   return SDValue();
16246 }
16247 
16248 // For type v4i32/v8ii16/v16i8, transform
16249 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16250 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16251 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16252 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16253 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16254                                           DAGCombinerInfo &DCI) const {
16255   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16256   assert(Subtarget.hasP9Altivec() &&
16257          "Only combine this when P9 altivec supported!");
16258 
16259   SelectionDAG &DAG = DCI.DAG;
16260   SDLoc dl(N);
16261   SDValue Cond = N->getOperand(0);
16262   SDValue TrueOpnd = N->getOperand(1);
16263   SDValue FalseOpnd = N->getOperand(2);
16264   EVT VT = N->getOperand(1).getValueType();
16265 
16266   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16267       FalseOpnd.getOpcode() != ISD::SUB)
16268     return SDValue();
16269 
16270   // ABSD only available for type v4i32/v8i16/v16i8
16271   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16272     return SDValue();
16273 
16274   // At least to save one more dependent computation
16275   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16276     return SDValue();
16277 
16278   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16279 
16280   // Can only handle unsigned comparison here
16281   switch (CC) {
16282   default:
16283     return SDValue();
16284   case ISD::SETUGT:
16285   case ISD::SETUGE:
16286     break;
16287   case ISD::SETULT:
16288   case ISD::SETULE:
16289     std::swap(TrueOpnd, FalseOpnd);
16290     break;
16291   }
16292 
16293   SDValue CmpOpnd1 = Cond.getOperand(0);
16294   SDValue CmpOpnd2 = Cond.getOperand(1);
16295 
16296   // SETCC CmpOpnd1 CmpOpnd2 cond
16297   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16298   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16299   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16300       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16301       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16302       FalseOpnd.getOperand(1) == CmpOpnd1) {
16303     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16304                        CmpOpnd1, CmpOpnd2,
16305                        DAG.getTargetConstant(0, dl, MVT::i32));
16306   }
16307 
16308   return SDValue();
16309 }
16310