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     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
722     if (!Subtarget.hasP8Vector()) {
723       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
724       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
725       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
726       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
727     }
728 
729     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
730       setOperationAction(ISD::ABS, VT, Custom);
731 
732     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
733     // with merges, splats, etc.
734     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
735 
736     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
737     // are cheap, so handle them before they get expanded to scalar.
738     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
739     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
740     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
741     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
742     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
743 
744     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
745     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
746     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
747     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
748     setOperationAction(ISD::SELECT, MVT::v4i32,
749                        Subtarget.useCRBits() ? Legal : Expand);
750     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
751     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
752     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
753     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
754     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
755     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
756     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
757     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
758     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
759 
760     // Without hasP8Altivec set, v2i64 SMAX isn't available.
761     // But ABS custom lowering requires SMAX support.
762     if (!Subtarget.hasP8Altivec())
763       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
764 
765     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
766     if (Subtarget.hasAltivec())
767       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
768         setOperationAction(ISD::ROTL, VT, Legal);
769     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
770     if (Subtarget.hasP8Altivec())
771       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
772 
773     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
774     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
775     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
776     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
777 
778     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
779     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
780 
781     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
782       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
783       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
784     }
785 
786     if (Subtarget.hasP8Altivec())
787       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
788     else
789       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
790 
791     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
792     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
793 
794     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
795     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
796 
797     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
798     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
799     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
800     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
801 
802     // Altivec does not contain unordered floating-point compare instructions
803     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
804     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
805     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
806     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
807 
808     if (Subtarget.hasVSX()) {
809       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
810       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
811       if (Subtarget.hasP8Vector()) {
812         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
813         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
814       }
815       if (Subtarget.hasDirectMove() && isPPC64) {
816         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
817         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
818         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
819         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
820         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
821         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
822         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
823         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
824       }
825       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
826 
827       // The nearbyint variants are not allowed to raise the inexact exception
828       // so we can only code-gen them with unsafe math.
829       if (TM.Options.UnsafeFPMath) {
830         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
831         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
832       }
833 
834       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
835       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
836       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
837       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
838       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
839       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
840       setOperationAction(ISD::FROUND, MVT::f64, Legal);
841       setOperationAction(ISD::FRINT, MVT::f64, Legal);
842 
843       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
844       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
845       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
846       setOperationAction(ISD::FROUND, MVT::f32, Legal);
847       setOperationAction(ISD::FRINT, MVT::f32, Legal);
848 
849       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
850       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
851 
852       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
853       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
854 
855       // Share the Altivec comparison restrictions.
856       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
857       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
858       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
859       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
860 
861       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
862       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
863 
864       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
865 
866       if (Subtarget.hasP8Vector())
867         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
868 
869       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
870 
871       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
872       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
873       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
874 
875       if (Subtarget.hasP8Altivec()) {
876         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
877         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
878         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
879 
880         // 128 bit shifts can be accomplished via 3 instructions for SHL and
881         // SRL, but not for SRA because of the instructions available:
882         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
883         // doing
884         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
885         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
886         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
887 
888         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
889       }
890       else {
891         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
892         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
893         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
894 
895         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
896 
897         // VSX v2i64 only supports non-arithmetic operations.
898         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
899         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
900       }
901 
902       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
903       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
904       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
905       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
906 
907       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
908 
909       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
910       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
911       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
912       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
913 
914       // Custom handling for partial vectors of integers converted to
915       // floating point. We already have optimal handling for v2i32 through
916       // the DAG combine, so those aren't necessary.
917       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
918       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
919       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
920       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
921       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
922       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
923       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
924       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
925 
926       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
927       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
928       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
929       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
930       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
931       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
932 
933       if (Subtarget.hasDirectMove())
934         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
935       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
936 
937       // Handle constrained floating-point operations of vector.
938       // The predictor is `hasVSX` because altivec instruction has
939       // no exception but VSX vector instruction has.
940       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
941       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
942       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
943       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
944       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
945       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
946       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
947       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
948 
949       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
950       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
951       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
952       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
953       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
954       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
955       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
956       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
957 
958       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
959     }
960 
961     if (Subtarget.hasP8Altivec()) {
962       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
963       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
964     }
965 
966     if (Subtarget.hasP9Vector()) {
967       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
969 
970       // 128 bit shifts can be accomplished via 3 instructions for SHL and
971       // SRL, but not for SRA because of the instructions available:
972       // VS{RL} and VS{RL}O.
973       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
974       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
975       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
976 
977       if (EnableQuadPrecision) {
978         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
979         setOperationAction(ISD::FADD, MVT::f128, Legal);
980         setOperationAction(ISD::FSUB, MVT::f128, Legal);
981         setOperationAction(ISD::FDIV, MVT::f128, Legal);
982         setOperationAction(ISD::FMUL, MVT::f128, Legal);
983         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
984         // No extending loads to f128 on PPC.
985         for (MVT FPT : MVT::fp_valuetypes())
986           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
987         setOperationAction(ISD::FMA, MVT::f128, Legal);
988         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
989         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
990         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
991         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
992         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
993         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
994 
995         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
996         setOperationAction(ISD::FRINT, MVT::f128, Legal);
997         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
998         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
999         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1000         setOperationAction(ISD::FROUND, MVT::f128, Legal);
1001 
1002         setOperationAction(ISD::SELECT, MVT::f128, Expand);
1003         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1004         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1005         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1006         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1007         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1008         // No implementation for these ops for PowerPC.
1009         setOperationAction(ISD::FSIN , MVT::f128, Expand);
1010         setOperationAction(ISD::FCOS , MVT::f128, Expand);
1011         setOperationAction(ISD::FPOW, MVT::f128, Expand);
1012         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1013         setOperationAction(ISD::FREM, MVT::f128, Expand);
1014 
1015         // Handle constrained floating-point operations of fp128
1016         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1017         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1018         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1019         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1020         setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1021         setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1022       }
1023       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1024       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1025       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1026       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1027       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1028     }
1029 
1030     if (Subtarget.hasP9Altivec()) {
1031       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1032       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1033 
1034       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1035       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1036       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1037       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1038       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1039       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1040       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1041     }
1042   }
1043 
1044   if (Subtarget.hasQPX()) {
1045     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1046     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1047     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1048     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1049 
1050     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1051     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1052 
1053     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1054     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1055 
1056     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1057     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1058 
1059     if (!Subtarget.useCRBits())
1060       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1061     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1062 
1063     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1064     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1065     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1066     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1067     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1068     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1069     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1070 
1071     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1072     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1073 
1074     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1075     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1076 
1077     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1078     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1079     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1080     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1081     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1082     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1083     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1084     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1085     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1086     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1087 
1088     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1089     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1090 
1091     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1092     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1093 
1094     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1095 
1096     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1097     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1098     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1099     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1100 
1101     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1102     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1103 
1104     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1105     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1106 
1107     if (!Subtarget.useCRBits())
1108       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1109     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1110 
1111     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1112     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1113     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1114     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1115     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1116     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1117     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1118 
1119     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1120     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1121 
1122     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1123     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1124     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1125     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1126     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1127     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1128     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1129     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1130     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1131     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1132 
1133     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1134     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1135 
1136     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1137     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1138 
1139     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1140 
1141     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1142     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1143     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1144 
1145     if (!Subtarget.useCRBits())
1146       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1147     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1148 
1149     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1150     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1151 
1152     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1153     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1154     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1155     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1156     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1157     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1158     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1159 
1160     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1161     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1162 
1163     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1164 
1165     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1166     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1167     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1168     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1169 
1170     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1171     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1172     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1173     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1174 
1175     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1176     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1177 
1178     // These need to set FE_INEXACT, and so cannot be vectorized here.
1179     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1180     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1181 
1182     if (TM.Options.UnsafeFPMath) {
1183       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1184       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1185 
1186       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1187       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1188     } else {
1189       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1190       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1191 
1192       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1193       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1194     }
1195 
1196     // TODO: Handle constrained floating-point operations of v4f64
1197   }
1198 
1199   if (Subtarget.has64BitSupport())
1200     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1201 
1202   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1203 
1204   if (!isPPC64) {
1205     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1206     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1207   }
1208 
1209   setBooleanContents(ZeroOrOneBooleanContent);
1210 
1211   if (Subtarget.hasAltivec()) {
1212     // Altivec instructions set fields to all zeros or all ones.
1213     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1214   }
1215 
1216   if (!isPPC64) {
1217     // These libcalls are not available in 32-bit.
1218     setLibcallName(RTLIB::SHL_I128, nullptr);
1219     setLibcallName(RTLIB::SRL_I128, nullptr);
1220     setLibcallName(RTLIB::SRA_I128, nullptr);
1221   }
1222 
1223   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1224 
1225   // We have target-specific dag combine patterns for the following nodes:
1226   setTargetDAGCombine(ISD::ADD);
1227   setTargetDAGCombine(ISD::SHL);
1228   setTargetDAGCombine(ISD::SRA);
1229   setTargetDAGCombine(ISD::SRL);
1230   setTargetDAGCombine(ISD::MUL);
1231   setTargetDAGCombine(ISD::FMA);
1232   setTargetDAGCombine(ISD::SINT_TO_FP);
1233   setTargetDAGCombine(ISD::BUILD_VECTOR);
1234   if (Subtarget.hasFPCVT())
1235     setTargetDAGCombine(ISD::UINT_TO_FP);
1236   setTargetDAGCombine(ISD::LOAD);
1237   setTargetDAGCombine(ISD::STORE);
1238   setTargetDAGCombine(ISD::BR_CC);
1239   if (Subtarget.useCRBits())
1240     setTargetDAGCombine(ISD::BRCOND);
1241   setTargetDAGCombine(ISD::BSWAP);
1242   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1243   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1244   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1245 
1246   setTargetDAGCombine(ISD::SIGN_EXTEND);
1247   setTargetDAGCombine(ISD::ZERO_EXTEND);
1248   setTargetDAGCombine(ISD::ANY_EXTEND);
1249 
1250   setTargetDAGCombine(ISD::TRUNCATE);
1251   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1252 
1253 
1254   if (Subtarget.useCRBits()) {
1255     setTargetDAGCombine(ISD::TRUNCATE);
1256     setTargetDAGCombine(ISD::SETCC);
1257     setTargetDAGCombine(ISD::SELECT_CC);
1258   }
1259 
1260   // Use reciprocal estimates.
1261   if (TM.Options.UnsafeFPMath) {
1262     setTargetDAGCombine(ISD::FDIV);
1263     setTargetDAGCombine(ISD::FSQRT);
1264   }
1265 
1266   if (Subtarget.hasP9Altivec()) {
1267     setTargetDAGCombine(ISD::ABS);
1268     setTargetDAGCombine(ISD::VSELECT);
1269   }
1270 
1271   if (EnableQuadPrecision) {
1272     setLibcallName(RTLIB::LOG_F128, "logf128");
1273     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1274     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1275     setLibcallName(RTLIB::EXP_F128, "expf128");
1276     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1277     setLibcallName(RTLIB::SIN_F128, "sinf128");
1278     setLibcallName(RTLIB::COS_F128, "cosf128");
1279     setLibcallName(RTLIB::POW_F128, "powf128");
1280     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1281     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1282     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1283     setLibcallName(RTLIB::REM_F128, "fmodf128");
1284   }
1285 
1286   // With 32 condition bits, we don't need to sink (and duplicate) compares
1287   // aggressively in CodeGenPrep.
1288   if (Subtarget.useCRBits()) {
1289     setHasMultipleConditionRegisters();
1290     setJumpIsExpensive();
1291   }
1292 
1293   setMinFunctionAlignment(Align(4));
1294 
1295   switch (Subtarget.getCPUDirective()) {
1296   default: break;
1297   case PPC::DIR_970:
1298   case PPC::DIR_A2:
1299   case PPC::DIR_E500:
1300   case PPC::DIR_E500mc:
1301   case PPC::DIR_E5500:
1302   case PPC::DIR_PWR4:
1303   case PPC::DIR_PWR5:
1304   case PPC::DIR_PWR5X:
1305   case PPC::DIR_PWR6:
1306   case PPC::DIR_PWR6X:
1307   case PPC::DIR_PWR7:
1308   case PPC::DIR_PWR8:
1309   case PPC::DIR_PWR9:
1310   case PPC::DIR_PWR10:
1311   case PPC::DIR_PWR_FUTURE:
1312     setPrefLoopAlignment(Align(16));
1313     setPrefFunctionAlignment(Align(16));
1314     break;
1315   }
1316 
1317   if (Subtarget.enableMachineScheduler())
1318     setSchedulingPreference(Sched::Source);
1319   else
1320     setSchedulingPreference(Sched::Hybrid);
1321 
1322   computeRegisterProperties(STI.getRegisterInfo());
1323 
1324   // The Freescale cores do better with aggressive inlining of memcpy and
1325   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1326   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1327       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1328     MaxStoresPerMemset = 32;
1329     MaxStoresPerMemsetOptSize = 16;
1330     MaxStoresPerMemcpy = 32;
1331     MaxStoresPerMemcpyOptSize = 8;
1332     MaxStoresPerMemmove = 32;
1333     MaxStoresPerMemmoveOptSize = 8;
1334   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1335     // The A2 also benefits from (very) aggressive inlining of memcpy and
1336     // friends. The overhead of a the function call, even when warm, can be
1337     // over one hundred cycles.
1338     MaxStoresPerMemset = 128;
1339     MaxStoresPerMemcpy = 128;
1340     MaxStoresPerMemmove = 128;
1341     MaxLoadsPerMemcmp = 128;
1342   } else {
1343     MaxLoadsPerMemcmp = 8;
1344     MaxLoadsPerMemcmpOptSize = 4;
1345   }
1346 
1347   // Let the subtarget (CPU) decide if a predictable select is more expensive
1348   // than the corresponding branch. This information is used in CGP to decide
1349   // when to convert selects into branches.
1350   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1351 }
1352 
1353 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1354 /// the desired ByVal argument alignment.
1355 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1356                              unsigned MaxMaxAlign) {
1357   if (MaxAlign == MaxMaxAlign)
1358     return;
1359   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1360     if (MaxMaxAlign >= 32 &&
1361         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1362       MaxAlign = 32;
1363     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1364              MaxAlign < 16)
1365       MaxAlign = 16;
1366   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1367     unsigned EltAlign = 0;
1368     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1369     if (EltAlign > MaxAlign)
1370       MaxAlign = EltAlign;
1371   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1372     for (auto *EltTy : STy->elements()) {
1373       unsigned EltAlign = 0;
1374       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1375       if (EltAlign > MaxAlign)
1376         MaxAlign = EltAlign;
1377       if (MaxAlign == MaxMaxAlign)
1378         break;
1379     }
1380   }
1381 }
1382 
1383 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1384 /// function arguments in the caller parameter area.
1385 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1386                                                   const DataLayout &DL) const {
1387   // 16byte and wider vectors are passed on 16byte boundary.
1388   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1389   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1390   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1391     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1392   return Align;
1393 }
1394 
1395 bool PPCTargetLowering::useSoftFloat() const {
1396   return Subtarget.useSoftFloat();
1397 }
1398 
1399 bool PPCTargetLowering::hasSPE() const {
1400   return Subtarget.hasSPE();
1401 }
1402 
1403 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1404   return VT.isScalarInteger();
1405 }
1406 
1407 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1408 /// type is cheaper than a multiply followed by a shift.
1409 /// This is true for words and doublewords on 64-bit PowerPC.
1410 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1411   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1412                               isOperationLegal(ISD::MULHU, Type)))
1413     return true;
1414   return TargetLowering::isMulhCheaperThanMulShift(Type);
1415 }
1416 
1417 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1418   switch ((PPCISD::NodeType)Opcode) {
1419   case PPCISD::FIRST_NUMBER:    break;
1420   case PPCISD::FSEL:            return "PPCISD::FSEL";
1421   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1422   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1423   case PPCISD::FCFID:           return "PPCISD::FCFID";
1424   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1425   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1426   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1427   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1428   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1429   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1430   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1431   case PPCISD::FP_TO_UINT_IN_VSR:
1432                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1433   case PPCISD::FP_TO_SINT_IN_VSR:
1434                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1435   case PPCISD::FRE:             return "PPCISD::FRE";
1436   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1437   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1438   case PPCISD::VPERM:           return "PPCISD::VPERM";
1439   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1440   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1441   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1442   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1443   case PPCISD::CMPB:            return "PPCISD::CMPB";
1444   case PPCISD::Hi:              return "PPCISD::Hi";
1445   case PPCISD::Lo:              return "PPCISD::Lo";
1446   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1447   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1448   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1449   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1450   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1451   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1452   case PPCISD::SRL:             return "PPCISD::SRL";
1453   case PPCISD::SRA:             return "PPCISD::SRA";
1454   case PPCISD::SHL:             return "PPCISD::SHL";
1455   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1456   case PPCISD::CALL:            return "PPCISD::CALL";
1457   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1458   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1459   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1460   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1461   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1462   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1463   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1464   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1465   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1466   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1467   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1468   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1469   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1470   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1471   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1472   case PPCISD::ANDI_rec_1_EQ_BIT:
1473     return "PPCISD::ANDI_rec_1_EQ_BIT";
1474   case PPCISD::ANDI_rec_1_GT_BIT:
1475     return "PPCISD::ANDI_rec_1_GT_BIT";
1476   case PPCISD::VCMP:            return "PPCISD::VCMP";
1477   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1478   case PPCISD::LBRX:            return "PPCISD::LBRX";
1479   case PPCISD::STBRX:           return "PPCISD::STBRX";
1480   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1481   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1482   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1483   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1484   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1485   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1486   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1487   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1488   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1489   case PPCISD::ST_VSR_SCAL_INT:
1490                                 return "PPCISD::ST_VSR_SCAL_INT";
1491   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1492   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1493   case PPCISD::BDZ:             return "PPCISD::BDZ";
1494   case PPCISD::MFFS:            return "PPCISD::MFFS";
1495   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1496   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1497   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1498   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1499   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1500   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1501   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1502   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1503   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1504   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1505   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1506   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1507   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1508   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1509   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1510   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1511   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1512   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1513   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1514   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1515   case PPCISD::SC:              return "PPCISD::SC";
1516   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1517   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1518   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1519   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1520   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1521   case PPCISD::VABSD:           return "PPCISD::VABSD";
1522   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1523   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1524   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1525   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1526   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1527   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1528   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1529   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1530   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1531   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1532   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1533   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1534   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1535   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1536   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1537   }
1538   return nullptr;
1539 }
1540 
1541 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1542                                           EVT VT) const {
1543   if (!VT.isVector())
1544     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1545 
1546   if (Subtarget.hasQPX())
1547     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1548 
1549   return VT.changeVectorElementTypeToInteger();
1550 }
1551 
1552 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1553   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1554   return true;
1555 }
1556 
1557 //===----------------------------------------------------------------------===//
1558 // Node matching predicates, for use by the tblgen matching code.
1559 //===----------------------------------------------------------------------===//
1560 
1561 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1562 static bool isFloatingPointZero(SDValue Op) {
1563   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1564     return CFP->getValueAPF().isZero();
1565   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1566     // Maybe this has already been legalized into the constant pool?
1567     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1568       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1569         return CFP->getValueAPF().isZero();
1570   }
1571   return false;
1572 }
1573 
1574 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1575 /// true if Op is undef or if it matches the specified value.
1576 static bool isConstantOrUndef(int Op, int Val) {
1577   return Op < 0 || Op == Val;
1578 }
1579 
1580 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1581 /// VPKUHUM instruction.
1582 /// The ShuffleKind distinguishes between big-endian operations with
1583 /// two different inputs (0), either-endian operations with two identical
1584 /// inputs (1), and little-endian operations with two different inputs (2).
1585 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1586 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1587                                SelectionDAG &DAG) {
1588   bool IsLE = DAG.getDataLayout().isLittleEndian();
1589   if (ShuffleKind == 0) {
1590     if (IsLE)
1591       return false;
1592     for (unsigned i = 0; i != 16; ++i)
1593       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1594         return false;
1595   } else if (ShuffleKind == 2) {
1596     if (!IsLE)
1597       return false;
1598     for (unsigned i = 0; i != 16; ++i)
1599       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1600         return false;
1601   } else if (ShuffleKind == 1) {
1602     unsigned j = IsLE ? 0 : 1;
1603     for (unsigned i = 0; i != 8; ++i)
1604       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1605           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1606         return false;
1607   }
1608   return true;
1609 }
1610 
1611 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1612 /// VPKUWUM instruction.
1613 /// The ShuffleKind distinguishes between big-endian operations with
1614 /// two different inputs (0), either-endian operations with two identical
1615 /// inputs (1), and little-endian operations with two different inputs (2).
1616 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1617 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1618                                SelectionDAG &DAG) {
1619   bool IsLE = DAG.getDataLayout().isLittleEndian();
1620   if (ShuffleKind == 0) {
1621     if (IsLE)
1622       return false;
1623     for (unsigned i = 0; i != 16; i += 2)
1624       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1625           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1626         return false;
1627   } else if (ShuffleKind == 2) {
1628     if (!IsLE)
1629       return false;
1630     for (unsigned i = 0; i != 16; i += 2)
1631       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1632           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1633         return false;
1634   } else if (ShuffleKind == 1) {
1635     unsigned j = IsLE ? 0 : 2;
1636     for (unsigned i = 0; i != 8; i += 2)
1637       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1638           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1639           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1640           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1641         return false;
1642   }
1643   return true;
1644 }
1645 
1646 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1647 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1648 /// current subtarget.
1649 ///
1650 /// The ShuffleKind distinguishes between big-endian operations with
1651 /// two different inputs (0), either-endian operations with two identical
1652 /// inputs (1), and little-endian operations with two different inputs (2).
1653 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1654 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1655                                SelectionDAG &DAG) {
1656   const PPCSubtarget& Subtarget =
1657       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1658   if (!Subtarget.hasP8Vector())
1659     return false;
1660 
1661   bool IsLE = DAG.getDataLayout().isLittleEndian();
1662   if (ShuffleKind == 0) {
1663     if (IsLE)
1664       return false;
1665     for (unsigned i = 0; i != 16; i += 4)
1666       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1667           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1668           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1669           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1670         return false;
1671   } else if (ShuffleKind == 2) {
1672     if (!IsLE)
1673       return false;
1674     for (unsigned i = 0; i != 16; i += 4)
1675       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1676           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1677           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1678           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1679         return false;
1680   } else if (ShuffleKind == 1) {
1681     unsigned j = IsLE ? 0 : 4;
1682     for (unsigned i = 0; i != 8; i += 4)
1683       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1684           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1685           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1686           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1687           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1688           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1689           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1690           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1691         return false;
1692   }
1693   return true;
1694 }
1695 
1696 /// isVMerge - Common function, used to match vmrg* shuffles.
1697 ///
1698 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1699                      unsigned LHSStart, unsigned RHSStart) {
1700   if (N->getValueType(0) != MVT::v16i8)
1701     return false;
1702   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1703          "Unsupported merge size!");
1704 
1705   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1706     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1707       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1708                              LHSStart+j+i*UnitSize) ||
1709           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1710                              RHSStart+j+i*UnitSize))
1711         return false;
1712     }
1713   return true;
1714 }
1715 
1716 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1717 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1718 /// The ShuffleKind distinguishes between big-endian merges with two
1719 /// different inputs (0), either-endian merges with two identical inputs (1),
1720 /// and little-endian merges with two different inputs (2).  For the latter,
1721 /// the input operands are swapped (see PPCInstrAltivec.td).
1722 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1723                              unsigned ShuffleKind, SelectionDAG &DAG) {
1724   if (DAG.getDataLayout().isLittleEndian()) {
1725     if (ShuffleKind == 1) // unary
1726       return isVMerge(N, UnitSize, 0, 0);
1727     else if (ShuffleKind == 2) // swapped
1728       return isVMerge(N, UnitSize, 0, 16);
1729     else
1730       return false;
1731   } else {
1732     if (ShuffleKind == 1) // unary
1733       return isVMerge(N, UnitSize, 8, 8);
1734     else if (ShuffleKind == 0) // normal
1735       return isVMerge(N, UnitSize, 8, 24);
1736     else
1737       return false;
1738   }
1739 }
1740 
1741 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1742 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1743 /// The ShuffleKind distinguishes between big-endian merges with two
1744 /// different inputs (0), either-endian merges with two identical inputs (1),
1745 /// and little-endian merges with two different inputs (2).  For the latter,
1746 /// the input operands are swapped (see PPCInstrAltivec.td).
1747 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1748                              unsigned ShuffleKind, SelectionDAG &DAG) {
1749   if (DAG.getDataLayout().isLittleEndian()) {
1750     if (ShuffleKind == 1) // unary
1751       return isVMerge(N, UnitSize, 8, 8);
1752     else if (ShuffleKind == 2) // swapped
1753       return isVMerge(N, UnitSize, 8, 24);
1754     else
1755       return false;
1756   } else {
1757     if (ShuffleKind == 1) // unary
1758       return isVMerge(N, UnitSize, 0, 0);
1759     else if (ShuffleKind == 0) // normal
1760       return isVMerge(N, UnitSize, 0, 16);
1761     else
1762       return false;
1763   }
1764 }
1765 
1766 /**
1767  * Common function used to match vmrgew and vmrgow shuffles
1768  *
1769  * The indexOffset determines whether to look for even or odd words in
1770  * the shuffle mask. This is based on the of the endianness of the target
1771  * machine.
1772  *   - Little Endian:
1773  *     - Use offset of 0 to check for odd elements
1774  *     - Use offset of 4 to check for even elements
1775  *   - Big Endian:
1776  *     - Use offset of 0 to check for even elements
1777  *     - Use offset of 4 to check for odd elements
1778  * A detailed description of the vector element ordering for little endian and
1779  * big endian can be found at
1780  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1781  * Targeting your applications - what little endian and big endian IBM XL C/C++
1782  * compiler differences mean to you
1783  *
1784  * The mask to the shuffle vector instruction specifies the indices of the
1785  * elements from the two input vectors to place in the result. The elements are
1786  * numbered in array-access order, starting with the first vector. These vectors
1787  * are always of type v16i8, thus each vector will contain 16 elements of size
1788  * 8. More info on the shuffle vector can be found in the
1789  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1790  * Language Reference.
1791  *
1792  * The RHSStartValue indicates whether the same input vectors are used (unary)
1793  * or two different input vectors are used, based on the following:
1794  *   - If the instruction uses the same vector for both inputs, the range of the
1795  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1796  *     be 0.
1797  *   - If the instruction has two different vectors then the range of the
1798  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1799  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1800  *     to 31 specify elements in the second vector).
1801  *
1802  * \param[in] N The shuffle vector SD Node to analyze
1803  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1804  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1805  * vector to the shuffle_vector instruction
1806  * \return true iff this shuffle vector represents an even or odd word merge
1807  */
1808 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1809                      unsigned RHSStartValue) {
1810   if (N->getValueType(0) != MVT::v16i8)
1811     return false;
1812 
1813   for (unsigned i = 0; i < 2; ++i)
1814     for (unsigned j = 0; j < 4; ++j)
1815       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1816                              i*RHSStartValue+j+IndexOffset) ||
1817           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1818                              i*RHSStartValue+j+IndexOffset+8))
1819         return false;
1820   return true;
1821 }
1822 
1823 /**
1824  * Determine if the specified shuffle mask is suitable for the vmrgew or
1825  * vmrgow instructions.
1826  *
1827  * \param[in] N The shuffle vector SD Node to analyze
1828  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1829  * \param[in] ShuffleKind Identify the type of merge:
1830  *   - 0 = big-endian merge with two different inputs;
1831  *   - 1 = either-endian merge with two identical inputs;
1832  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1833  *     little-endian merges).
1834  * \param[in] DAG The current SelectionDAG
1835  * \return true iff this shuffle mask
1836  */
1837 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1838                               unsigned ShuffleKind, SelectionDAG &DAG) {
1839   if (DAG.getDataLayout().isLittleEndian()) {
1840     unsigned indexOffset = CheckEven ? 4 : 0;
1841     if (ShuffleKind == 1) // Unary
1842       return isVMerge(N, indexOffset, 0);
1843     else if (ShuffleKind == 2) // swapped
1844       return isVMerge(N, indexOffset, 16);
1845     else
1846       return false;
1847   }
1848   else {
1849     unsigned indexOffset = CheckEven ? 0 : 4;
1850     if (ShuffleKind == 1) // Unary
1851       return isVMerge(N, indexOffset, 0);
1852     else if (ShuffleKind == 0) // Normal
1853       return isVMerge(N, indexOffset, 16);
1854     else
1855       return false;
1856   }
1857   return false;
1858 }
1859 
1860 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1861 /// amount, otherwise return -1.
1862 /// The ShuffleKind distinguishes between big-endian operations with two
1863 /// different inputs (0), either-endian operations with two identical inputs
1864 /// (1), and little-endian operations with two different inputs (2).  For the
1865 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1866 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1867                              SelectionDAG &DAG) {
1868   if (N->getValueType(0) != MVT::v16i8)
1869     return -1;
1870 
1871   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1872 
1873   // Find the first non-undef value in the shuffle mask.
1874   unsigned i;
1875   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1876     /*search*/;
1877 
1878   if (i == 16) return -1;  // all undef.
1879 
1880   // Otherwise, check to see if the rest of the elements are consecutively
1881   // numbered from this value.
1882   unsigned ShiftAmt = SVOp->getMaskElt(i);
1883   if (ShiftAmt < i) return -1;
1884 
1885   ShiftAmt -= i;
1886   bool isLE = DAG.getDataLayout().isLittleEndian();
1887 
1888   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1889     // Check the rest of the elements to see if they are consecutive.
1890     for (++i; i != 16; ++i)
1891       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1892         return -1;
1893   } else if (ShuffleKind == 1) {
1894     // Check the rest of the elements to see if they are consecutive.
1895     for (++i; i != 16; ++i)
1896       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1897         return -1;
1898   } else
1899     return -1;
1900 
1901   if (isLE)
1902     ShiftAmt = 16 - ShiftAmt;
1903 
1904   return ShiftAmt;
1905 }
1906 
1907 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1908 /// specifies a splat of a single element that is suitable for input to
1909 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1910 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1911   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1912          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1913 
1914   // The consecutive indices need to specify an element, not part of two
1915   // different elements.  So abandon ship early if this isn't the case.
1916   if (N->getMaskElt(0) % EltSize != 0)
1917     return false;
1918 
1919   // This is a splat operation if each element of the permute is the same, and
1920   // if the value doesn't reference the second vector.
1921   unsigned ElementBase = N->getMaskElt(0);
1922 
1923   // FIXME: Handle UNDEF elements too!
1924   if (ElementBase >= 16)
1925     return false;
1926 
1927   // Check that the indices are consecutive, in the case of a multi-byte element
1928   // splatted with a v16i8 mask.
1929   for (unsigned i = 1; i != EltSize; ++i)
1930     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1931       return false;
1932 
1933   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1934     if (N->getMaskElt(i) < 0) continue;
1935     for (unsigned j = 0; j != EltSize; ++j)
1936       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1937         return false;
1938   }
1939   return true;
1940 }
1941 
1942 /// Check that the mask is shuffling N byte elements. Within each N byte
1943 /// element of the mask, the indices could be either in increasing or
1944 /// decreasing order as long as they are consecutive.
1945 /// \param[in] N the shuffle vector SD Node to analyze
1946 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1947 /// Word/DoubleWord/QuadWord).
1948 /// \param[in] StepLen the delta indices number among the N byte element, if
1949 /// the mask is in increasing/decreasing order then it is 1/-1.
1950 /// \return true iff the mask is shuffling N byte elements.
1951 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1952                                    int StepLen) {
1953   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1954          "Unexpected element width.");
1955   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1956 
1957   unsigned NumOfElem = 16 / Width;
1958   unsigned MaskVal[16]; //  Width is never greater than 16
1959   for (unsigned i = 0; i < NumOfElem; ++i) {
1960     MaskVal[0] = N->getMaskElt(i * Width);
1961     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1962       return false;
1963     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1964       return false;
1965     }
1966 
1967     for (unsigned int j = 1; j < Width; ++j) {
1968       MaskVal[j] = N->getMaskElt(i * Width + j);
1969       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1970         return false;
1971       }
1972     }
1973   }
1974 
1975   return true;
1976 }
1977 
1978 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1979                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1980   if (!isNByteElemShuffleMask(N, 4, 1))
1981     return false;
1982 
1983   // Now we look at mask elements 0,4,8,12
1984   unsigned M0 = N->getMaskElt(0) / 4;
1985   unsigned M1 = N->getMaskElt(4) / 4;
1986   unsigned M2 = N->getMaskElt(8) / 4;
1987   unsigned M3 = N->getMaskElt(12) / 4;
1988   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1989   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1990 
1991   // Below, let H and L be arbitrary elements of the shuffle mask
1992   // where H is in the range [4,7] and L is in the range [0,3].
1993   // H, 1, 2, 3 or L, 5, 6, 7
1994   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1995       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1996     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1997     InsertAtByte = IsLE ? 12 : 0;
1998     Swap = M0 < 4;
1999     return true;
2000   }
2001   // 0, H, 2, 3 or 4, L, 6, 7
2002   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2003       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2004     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2005     InsertAtByte = IsLE ? 8 : 4;
2006     Swap = M1 < 4;
2007     return true;
2008   }
2009   // 0, 1, H, 3 or 4, 5, L, 7
2010   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2011       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2012     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2013     InsertAtByte = IsLE ? 4 : 8;
2014     Swap = M2 < 4;
2015     return true;
2016   }
2017   // 0, 1, 2, H or 4, 5, 6, L
2018   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2019       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2020     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2021     InsertAtByte = IsLE ? 0 : 12;
2022     Swap = M3 < 4;
2023     return true;
2024   }
2025 
2026   // If both vector operands for the shuffle are the same vector, the mask will
2027   // contain only elements from the first one and the second one will be undef.
2028   if (N->getOperand(1).isUndef()) {
2029     ShiftElts = 0;
2030     Swap = true;
2031     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2032     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2033       InsertAtByte = IsLE ? 12 : 0;
2034       return true;
2035     }
2036     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2037       InsertAtByte = IsLE ? 8 : 4;
2038       return true;
2039     }
2040     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2041       InsertAtByte = IsLE ? 4 : 8;
2042       return true;
2043     }
2044     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2045       InsertAtByte = IsLE ? 0 : 12;
2046       return true;
2047     }
2048   }
2049 
2050   return false;
2051 }
2052 
2053 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2054                                bool &Swap, bool IsLE) {
2055   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2056   // Ensure each byte index of the word is consecutive.
2057   if (!isNByteElemShuffleMask(N, 4, 1))
2058     return false;
2059 
2060   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2061   unsigned M0 = N->getMaskElt(0) / 4;
2062   unsigned M1 = N->getMaskElt(4) / 4;
2063   unsigned M2 = N->getMaskElt(8) / 4;
2064   unsigned M3 = N->getMaskElt(12) / 4;
2065 
2066   // If both vector operands for the shuffle are the same vector, the mask will
2067   // contain only elements from the first one and the second one will be undef.
2068   if (N->getOperand(1).isUndef()) {
2069     assert(M0 < 4 && "Indexing into an undef vector?");
2070     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2071       return false;
2072 
2073     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2074     Swap = false;
2075     return true;
2076   }
2077 
2078   // Ensure each word index of the ShuffleVector Mask is consecutive.
2079   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2080     return false;
2081 
2082   if (IsLE) {
2083     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2084       // Input vectors don't need to be swapped if the leading element
2085       // of the result is one of the 3 left elements of the second vector
2086       // (or if there is no shift to be done at all).
2087       Swap = false;
2088       ShiftElts = (8 - M0) % 8;
2089     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2090       // Input vectors need to be swapped if the leading element
2091       // of the result is one of the 3 left elements of the first vector
2092       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2093       Swap = true;
2094       ShiftElts = (4 - M0) % 4;
2095     }
2096 
2097     return true;
2098   } else {                                          // BE
2099     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2100       // Input vectors don't need to be swapped if the leading element
2101       // of the result is one of the 4 elements of the first vector.
2102       Swap = false;
2103       ShiftElts = M0;
2104     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2105       // Input vectors need to be swapped if the leading element
2106       // of the result is one of the 4 elements of the right vector.
2107       Swap = true;
2108       ShiftElts = M0 - 4;
2109     }
2110 
2111     return true;
2112   }
2113 }
2114 
2115 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2116   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2117 
2118   if (!isNByteElemShuffleMask(N, Width, -1))
2119     return false;
2120 
2121   for (int i = 0; i < 16; i += Width)
2122     if (N->getMaskElt(i) != i + Width - 1)
2123       return false;
2124 
2125   return true;
2126 }
2127 
2128 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2129   return isXXBRShuffleMaskHelper(N, 2);
2130 }
2131 
2132 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2133   return isXXBRShuffleMaskHelper(N, 4);
2134 }
2135 
2136 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2137   return isXXBRShuffleMaskHelper(N, 8);
2138 }
2139 
2140 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2141   return isXXBRShuffleMaskHelper(N, 16);
2142 }
2143 
2144 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2145 /// if the inputs to the instruction should be swapped and set \p DM to the
2146 /// value for the immediate.
2147 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2148 /// AND element 0 of the result comes from the first input (LE) or second input
2149 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2150 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2151 /// mask.
2152 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2153                                bool &Swap, bool IsLE) {
2154   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2155 
2156   // Ensure each byte index of the double word is consecutive.
2157   if (!isNByteElemShuffleMask(N, 8, 1))
2158     return false;
2159 
2160   unsigned M0 = N->getMaskElt(0) / 8;
2161   unsigned M1 = N->getMaskElt(8) / 8;
2162   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2163 
2164   // If both vector operands for the shuffle are the same vector, the mask will
2165   // contain only elements from the first one and the second one will be undef.
2166   if (N->getOperand(1).isUndef()) {
2167     if ((M0 | M1) < 2) {
2168       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2169       Swap = false;
2170       return true;
2171     } else
2172       return false;
2173   }
2174 
2175   if (IsLE) {
2176     if (M0 > 1 && M1 < 2) {
2177       Swap = false;
2178     } else if (M0 < 2 && M1 > 1) {
2179       M0 = (M0 + 2) % 4;
2180       M1 = (M1 + 2) % 4;
2181       Swap = true;
2182     } else
2183       return false;
2184 
2185     // Note: if control flow comes here that means Swap is already set above
2186     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2187     return true;
2188   } else { // BE
2189     if (M0 < 2 && M1 > 1) {
2190       Swap = false;
2191     } else if (M0 > 1 && M1 < 2) {
2192       M0 = (M0 + 2) % 4;
2193       M1 = (M1 + 2) % 4;
2194       Swap = true;
2195     } else
2196       return false;
2197 
2198     // Note: if control flow comes here that means Swap is already set above
2199     DM = (M0 << 1) + (M1 & 1);
2200     return true;
2201   }
2202 }
2203 
2204 
2205 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2206 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2207 /// elements are counted from the left of the vector register).
2208 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2209                                          SelectionDAG &DAG) {
2210   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2211   assert(isSplatShuffleMask(SVOp, EltSize));
2212   if (DAG.getDataLayout().isLittleEndian())
2213     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2214   else
2215     return SVOp->getMaskElt(0) / EltSize;
2216 }
2217 
2218 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2219 /// by using a vspltis[bhw] instruction of the specified element size, return
2220 /// the constant being splatted.  The ByteSize field indicates the number of
2221 /// bytes of each element [124] -> [bhw].
2222 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2223   SDValue OpVal(nullptr, 0);
2224 
2225   // If ByteSize of the splat is bigger than the element size of the
2226   // build_vector, then we have a case where we are checking for a splat where
2227   // multiple elements of the buildvector are folded together into a single
2228   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2229   unsigned EltSize = 16/N->getNumOperands();
2230   if (EltSize < ByteSize) {
2231     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2232     SDValue UniquedVals[4];
2233     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2234 
2235     // See if all of the elements in the buildvector agree across.
2236     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2237       if (N->getOperand(i).isUndef()) continue;
2238       // If the element isn't a constant, bail fully out.
2239       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2240 
2241       if (!UniquedVals[i&(Multiple-1)].getNode())
2242         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2243       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2244         return SDValue();  // no match.
2245     }
2246 
2247     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2248     // either constant or undef values that are identical for each chunk.  See
2249     // if these chunks can form into a larger vspltis*.
2250 
2251     // Check to see if all of the leading entries are either 0 or -1.  If
2252     // neither, then this won't fit into the immediate field.
2253     bool LeadingZero = true;
2254     bool LeadingOnes = true;
2255     for (unsigned i = 0; i != Multiple-1; ++i) {
2256       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2257 
2258       LeadingZero &= isNullConstant(UniquedVals[i]);
2259       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2260     }
2261     // Finally, check the least significant entry.
2262     if (LeadingZero) {
2263       if (!UniquedVals[Multiple-1].getNode())
2264         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2265       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2266       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2267         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2268     }
2269     if (LeadingOnes) {
2270       if (!UniquedVals[Multiple-1].getNode())
2271         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2272       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2273       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2274         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2275     }
2276 
2277     return SDValue();
2278   }
2279 
2280   // Check to see if this buildvec has a single non-undef value in its elements.
2281   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2282     if (N->getOperand(i).isUndef()) continue;
2283     if (!OpVal.getNode())
2284       OpVal = N->getOperand(i);
2285     else if (OpVal != N->getOperand(i))
2286       return SDValue();
2287   }
2288 
2289   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2290 
2291   unsigned ValSizeInBytes = EltSize;
2292   uint64_t Value = 0;
2293   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2294     Value = CN->getZExtValue();
2295   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2296     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2297     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2298   }
2299 
2300   // If the splat value is larger than the element value, then we can never do
2301   // this splat.  The only case that we could fit the replicated bits into our
2302   // immediate field for would be zero, and we prefer to use vxor for it.
2303   if (ValSizeInBytes < ByteSize) return SDValue();
2304 
2305   // If the element value is larger than the splat value, check if it consists
2306   // of a repeated bit pattern of size ByteSize.
2307   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2308     return SDValue();
2309 
2310   // Properly sign extend the value.
2311   int MaskVal = SignExtend32(Value, ByteSize * 8);
2312 
2313   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2314   if (MaskVal == 0) return SDValue();
2315 
2316   // Finally, if this value fits in a 5 bit sext field, return it
2317   if (SignExtend32<5>(MaskVal) == MaskVal)
2318     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2319   return SDValue();
2320 }
2321 
2322 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2323 /// amount, otherwise return -1.
2324 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2325   EVT VT = N->getValueType(0);
2326   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2327     return -1;
2328 
2329   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2330 
2331   // Find the first non-undef value in the shuffle mask.
2332   unsigned i;
2333   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2334     /*search*/;
2335 
2336   if (i == 4) return -1;  // all undef.
2337 
2338   // Otherwise, check to see if the rest of the elements are consecutively
2339   // numbered from this value.
2340   unsigned ShiftAmt = SVOp->getMaskElt(i);
2341   if (ShiftAmt < i) return -1;
2342   ShiftAmt -= i;
2343 
2344   // Check the rest of the elements to see if they are consecutive.
2345   for (++i; i != 4; ++i)
2346     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2347       return -1;
2348 
2349   return ShiftAmt;
2350 }
2351 
2352 //===----------------------------------------------------------------------===//
2353 //  Addressing Mode Selection
2354 //===----------------------------------------------------------------------===//
2355 
2356 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2357 /// or 64-bit immediate, and if the value can be accurately represented as a
2358 /// sign extension from a 16-bit value.  If so, this returns true and the
2359 /// immediate.
2360 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2361   if (!isa<ConstantSDNode>(N))
2362     return false;
2363 
2364   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2365   if (N->getValueType(0) == MVT::i32)
2366     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2367   else
2368     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2369 }
2370 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2371   return isIntS16Immediate(Op.getNode(), Imm);
2372 }
2373 
2374 
2375 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2376 /// be represented as an indexed [r+r] operation.
2377 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2378                                                SDValue &Index,
2379                                                SelectionDAG &DAG) const {
2380   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2381       UI != E; ++UI) {
2382     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2383       if (Memop->getMemoryVT() == MVT::f64) {
2384           Base = N.getOperand(0);
2385           Index = N.getOperand(1);
2386           return true;
2387       }
2388     }
2389   }
2390   return false;
2391 }
2392 
2393 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2394 /// can be represented as an indexed [r+r] operation.  Returns false if it
2395 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2396 /// non-zero and N can be represented by a base register plus a signed 16-bit
2397 /// displacement, make a more precise judgement by checking (displacement % \p
2398 /// EncodingAlignment).
2399 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2400                                             SDValue &Index, SelectionDAG &DAG,
2401                                             unsigned EncodingAlignment) const {
2402   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2403   // a [pc+imm].
2404   if (SelectAddressPCRel(N, Base))
2405     return false;
2406 
2407   int16_t imm = 0;
2408   if (N.getOpcode() == ISD::ADD) {
2409     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2410     // SPE load/store can only handle 8-bit offsets.
2411     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2412         return true;
2413     if (isIntS16Immediate(N.getOperand(1), imm) &&
2414         (!EncodingAlignment || !(imm % EncodingAlignment)))
2415       return false; // r+i
2416     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2417       return false;    // r+i
2418 
2419     Base = N.getOperand(0);
2420     Index = N.getOperand(1);
2421     return true;
2422   } else if (N.getOpcode() == ISD::OR) {
2423     if (isIntS16Immediate(N.getOperand(1), imm) &&
2424         (!EncodingAlignment || !(imm % EncodingAlignment)))
2425       return false; // r+i can fold it if we can.
2426 
2427     // If this is an or of disjoint bitfields, we can codegen this as an add
2428     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2429     // disjoint.
2430     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2431 
2432     if (LHSKnown.Zero.getBoolValue()) {
2433       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2434       // If all of the bits are known zero on the LHS or RHS, the add won't
2435       // carry.
2436       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2437         Base = N.getOperand(0);
2438         Index = N.getOperand(1);
2439         return true;
2440       }
2441     }
2442   }
2443 
2444   return false;
2445 }
2446 
2447 // If we happen to be doing an i64 load or store into a stack slot that has
2448 // less than a 4-byte alignment, then the frame-index elimination may need to
2449 // use an indexed load or store instruction (because the offset may not be a
2450 // multiple of 4). The extra register needed to hold the offset comes from the
2451 // register scavenger, and it is possible that the scavenger will need to use
2452 // an emergency spill slot. As a result, we need to make sure that a spill slot
2453 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2454 // stack slot.
2455 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2456   // FIXME: This does not handle the LWA case.
2457   if (VT != MVT::i64)
2458     return;
2459 
2460   // NOTE: We'll exclude negative FIs here, which come from argument
2461   // lowering, because there are no known test cases triggering this problem
2462   // using packed structures (or similar). We can remove this exclusion if
2463   // we find such a test case. The reason why this is so test-case driven is
2464   // because this entire 'fixup' is only to prevent crashes (from the
2465   // register scavenger) on not-really-valid inputs. For example, if we have:
2466   //   %a = alloca i1
2467   //   %b = bitcast i1* %a to i64*
2468   //   store i64* a, i64 b
2469   // then the store should really be marked as 'align 1', but is not. If it
2470   // were marked as 'align 1' then the indexed form would have been
2471   // instruction-selected initially, and the problem this 'fixup' is preventing
2472   // won't happen regardless.
2473   if (FrameIdx < 0)
2474     return;
2475 
2476   MachineFunction &MF = DAG.getMachineFunction();
2477   MachineFrameInfo &MFI = MF.getFrameInfo();
2478 
2479   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2480     return;
2481 
2482   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2483   FuncInfo->setHasNonRISpills();
2484 }
2485 
2486 /// Returns true if the address N can be represented by a base register plus
2487 /// a signed 16-bit displacement [r+imm], and if it is not better
2488 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2489 /// displacements that are multiples of that value.
2490 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2491                                             SDValue &Base,
2492                                             SelectionDAG &DAG,
2493                                             unsigned EncodingAlignment) const {
2494   // FIXME dl should come from parent load or store, not from address
2495   SDLoc dl(N);
2496 
2497   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2498   // a [pc+imm].
2499   if (SelectAddressPCRel(N, Base))
2500     return false;
2501 
2502   // If this can be more profitably realized as r+r, fail.
2503   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2504     return false;
2505 
2506   if (N.getOpcode() == ISD::ADD) {
2507     int16_t imm = 0;
2508     if (isIntS16Immediate(N.getOperand(1), imm) &&
2509         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2510       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2511       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2512         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2513         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2514       } else {
2515         Base = N.getOperand(0);
2516       }
2517       return true; // [r+i]
2518     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2519       // Match LOAD (ADD (X, Lo(G))).
2520       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2521              && "Cannot handle constant offsets yet!");
2522       Disp = N.getOperand(1).getOperand(0);  // The global address.
2523       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2524              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2525              Disp.getOpcode() == ISD::TargetConstantPool ||
2526              Disp.getOpcode() == ISD::TargetJumpTable);
2527       Base = N.getOperand(0);
2528       return true;  // [&g+r]
2529     }
2530   } else if (N.getOpcode() == ISD::OR) {
2531     int16_t imm = 0;
2532     if (isIntS16Immediate(N.getOperand(1), imm) &&
2533         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2534       // If this is an or of disjoint bitfields, we can codegen this as an add
2535       // (for better address arithmetic) if the LHS and RHS of the OR are
2536       // provably disjoint.
2537       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2538 
2539       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2540         // If all of the bits are known zero on the LHS or RHS, the add won't
2541         // carry.
2542         if (FrameIndexSDNode *FI =
2543               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2544           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2545           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2546         } else {
2547           Base = N.getOperand(0);
2548         }
2549         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2550         return true;
2551       }
2552     }
2553   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2554     // Loading from a constant address.
2555 
2556     // If this address fits entirely in a 16-bit sext immediate field, codegen
2557     // this as "d, 0"
2558     int16_t Imm;
2559     if (isIntS16Immediate(CN, Imm) &&
2560         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2561       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2562       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2563                              CN->getValueType(0));
2564       return true;
2565     }
2566 
2567     // Handle 32-bit sext immediates with LIS + addr mode.
2568     if ((CN->getValueType(0) == MVT::i32 ||
2569          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2570         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2571       int Addr = (int)CN->getZExtValue();
2572 
2573       // Otherwise, break this down into an LIS + disp.
2574       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2575 
2576       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2577                                    MVT::i32);
2578       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2579       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2580       return true;
2581     }
2582   }
2583 
2584   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2585   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2586     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2587     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2588   } else
2589     Base = N;
2590   return true;      // [r+0]
2591 }
2592 
2593 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2594 /// represented as an indexed [r+r] operation.
2595 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2596                                                 SDValue &Index,
2597                                                 SelectionDAG &DAG) const {
2598   // Check to see if we can easily represent this as an [r+r] address.  This
2599   // will fail if it thinks that the address is more profitably represented as
2600   // reg+imm, e.g. where imm = 0.
2601   if (SelectAddressRegReg(N, Base, Index, DAG))
2602     return true;
2603 
2604   // If the address is the result of an add, we will utilize the fact that the
2605   // address calculation includes an implicit add.  However, we can reduce
2606   // register pressure if we do not materialize a constant just for use as the
2607   // index register.  We only get rid of the add if it is not an add of a
2608   // value and a 16-bit signed constant and both have a single use.
2609   int16_t imm = 0;
2610   if (N.getOpcode() == ISD::ADD &&
2611       (!isIntS16Immediate(N.getOperand(1), imm) ||
2612        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2613     Base = N.getOperand(0);
2614     Index = N.getOperand(1);
2615     return true;
2616   }
2617 
2618   // Otherwise, do it the hard way, using R0 as the base register.
2619   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2620                          N.getValueType());
2621   Index = N;
2622   return true;
2623 }
2624 
2625 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2626   Ty *PCRelCand = dyn_cast<Ty>(N);
2627   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2628 }
2629 
2630 /// Returns true if this address is a PC Relative address.
2631 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2632 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2633 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2634   // This is a materialize PC Relative node. Always select this as PC Relative.
2635   Base = N;
2636   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2637     return true;
2638   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2639       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2640       isValidPCRelNode<JumpTableSDNode>(N) ||
2641       isValidPCRelNode<BlockAddressSDNode>(N))
2642     return true;
2643   return false;
2644 }
2645 
2646 /// Returns true if we should use a direct load into vector instruction
2647 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2648 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2649 
2650   // If there are any other uses other than scalar to vector, then we should
2651   // keep it as a scalar load -> direct move pattern to prevent multiple
2652   // loads.
2653   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2654   if (!LD)
2655     return false;
2656 
2657   EVT MemVT = LD->getMemoryVT();
2658   if (!MemVT.isSimple())
2659     return false;
2660   switch(MemVT.getSimpleVT().SimpleTy) {
2661   case MVT::i64:
2662     break;
2663   case MVT::i32:
2664     if (!ST.hasP8Vector())
2665       return false;
2666     break;
2667   case MVT::i16:
2668   case MVT::i8:
2669     if (!ST.hasP9Vector())
2670       return false;
2671     break;
2672   default:
2673     return false;
2674   }
2675 
2676   SDValue LoadedVal(N, 0);
2677   if (!LoadedVal.hasOneUse())
2678     return false;
2679 
2680   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2681        UI != UE; ++UI)
2682     if (UI.getUse().get().getResNo() == 0 &&
2683         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2684       return false;
2685 
2686   return true;
2687 }
2688 
2689 /// getPreIndexedAddressParts - returns true by value, base pointer and
2690 /// offset pointer and addressing mode by reference if the node's address
2691 /// can be legally represented as pre-indexed load / store address.
2692 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2693                                                   SDValue &Offset,
2694                                                   ISD::MemIndexedMode &AM,
2695                                                   SelectionDAG &DAG) const {
2696   if (DisablePPCPreinc) return false;
2697 
2698   bool isLoad = true;
2699   SDValue Ptr;
2700   EVT VT;
2701   unsigned Alignment;
2702   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2703     Ptr = LD->getBasePtr();
2704     VT = LD->getMemoryVT();
2705     Alignment = LD->getAlignment();
2706   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2707     Ptr = ST->getBasePtr();
2708     VT  = ST->getMemoryVT();
2709     Alignment = ST->getAlignment();
2710     isLoad = false;
2711   } else
2712     return false;
2713 
2714   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2715   // instructions because we can fold these into a more efficient instruction
2716   // instead, (such as LXSD).
2717   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2718     return false;
2719   }
2720 
2721   // PowerPC doesn't have preinc load/store instructions for vectors (except
2722   // for QPX, which does have preinc r+r forms).
2723   if (VT.isVector()) {
2724     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2725       return false;
2726     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2727       AM = ISD::PRE_INC;
2728       return true;
2729     }
2730   }
2731 
2732   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2733     // Common code will reject creating a pre-inc form if the base pointer
2734     // is a frame index, or if N is a store and the base pointer is either
2735     // the same as or a predecessor of the value being stored.  Check for
2736     // those situations here, and try with swapped Base/Offset instead.
2737     bool Swap = false;
2738 
2739     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2740       Swap = true;
2741     else if (!isLoad) {
2742       SDValue Val = cast<StoreSDNode>(N)->getValue();
2743       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2744         Swap = true;
2745     }
2746 
2747     if (Swap)
2748       std::swap(Base, Offset);
2749 
2750     AM = ISD::PRE_INC;
2751     return true;
2752   }
2753 
2754   // LDU/STU can only handle immediates that are a multiple of 4.
2755   if (VT != MVT::i64) {
2756     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2757       return false;
2758   } else {
2759     // LDU/STU need an address with at least 4-byte alignment.
2760     if (Alignment < 4)
2761       return false;
2762 
2763     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2764       return false;
2765   }
2766 
2767   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2768     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2769     // sext i32 to i64 when addr mode is r+i.
2770     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2771         LD->getExtensionType() == ISD::SEXTLOAD &&
2772         isa<ConstantSDNode>(Offset))
2773       return false;
2774   }
2775 
2776   AM = ISD::PRE_INC;
2777   return true;
2778 }
2779 
2780 //===----------------------------------------------------------------------===//
2781 //  LowerOperation implementation
2782 //===----------------------------------------------------------------------===//
2783 
2784 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2785 /// and LoOpFlags to the target MO flags.
2786 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2787                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2788                                const GlobalValue *GV = nullptr) {
2789   HiOpFlags = PPCII::MO_HA;
2790   LoOpFlags = PPCII::MO_LO;
2791 
2792   // Don't use the pic base if not in PIC relocation model.
2793   if (IsPIC) {
2794     HiOpFlags |= PPCII::MO_PIC_FLAG;
2795     LoOpFlags |= PPCII::MO_PIC_FLAG;
2796   }
2797 }
2798 
2799 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2800                              SelectionDAG &DAG) {
2801   SDLoc DL(HiPart);
2802   EVT PtrVT = HiPart.getValueType();
2803   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2804 
2805   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2806   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2807 
2808   // With PIC, the first instruction is actually "GR+hi(&G)".
2809   if (isPIC)
2810     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2811                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2812 
2813   // Generate non-pic code that has direct accesses to the constant pool.
2814   // The address of the global is just (hi(&g)+lo(&g)).
2815   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2816 }
2817 
2818 static void setUsesTOCBasePtr(MachineFunction &MF) {
2819   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2820   FuncInfo->setUsesTOCBasePtr();
2821 }
2822 
2823 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2824   setUsesTOCBasePtr(DAG.getMachineFunction());
2825 }
2826 
2827 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2828                                        SDValue GA) const {
2829   const bool Is64Bit = Subtarget.isPPC64();
2830   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2831   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2832                         : Subtarget.isAIXABI()
2833                               ? DAG.getRegister(PPC::R2, VT)
2834                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2835   SDValue Ops[] = { GA, Reg };
2836   return DAG.getMemIntrinsicNode(
2837       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2838       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2839       MachineMemOperand::MOLoad);
2840 }
2841 
2842 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2843                                              SelectionDAG &DAG) const {
2844   EVT PtrVT = Op.getValueType();
2845   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2846   const Constant *C = CP->getConstVal();
2847 
2848   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2849   // The actual address of the GlobalValue is stored in the TOC.
2850   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2851     if (Subtarget.isUsingPCRelativeCalls()) {
2852       SDLoc DL(CP);
2853       EVT Ty = getPointerTy(DAG.getDataLayout());
2854       SDValue ConstPool = DAG.getTargetConstantPool(
2855           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2856       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2857     }
2858     setUsesTOCBasePtr(DAG);
2859     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2860     return getTOCEntry(DAG, SDLoc(CP), GA);
2861   }
2862 
2863   unsigned MOHiFlag, MOLoFlag;
2864   bool IsPIC = isPositionIndependent();
2865   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2866 
2867   if (IsPIC && Subtarget.isSVR4ABI()) {
2868     SDValue GA =
2869         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2870     return getTOCEntry(DAG, SDLoc(CP), GA);
2871   }
2872 
2873   SDValue CPIHi =
2874       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2875   SDValue CPILo =
2876       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2877   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2878 }
2879 
2880 // For 64-bit PowerPC, prefer the more compact relative encodings.
2881 // This trades 32 bits per jump table entry for one or two instructions
2882 // on the jump site.
2883 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2884   if (isJumpTableRelative())
2885     return MachineJumpTableInfo::EK_LabelDifference32;
2886 
2887   return TargetLowering::getJumpTableEncoding();
2888 }
2889 
2890 bool PPCTargetLowering::isJumpTableRelative() const {
2891   if (UseAbsoluteJumpTables)
2892     return false;
2893   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2894     return true;
2895   return TargetLowering::isJumpTableRelative();
2896 }
2897 
2898 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2899                                                     SelectionDAG &DAG) const {
2900   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2901     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2902 
2903   switch (getTargetMachine().getCodeModel()) {
2904   case CodeModel::Small:
2905   case CodeModel::Medium:
2906     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2907   default:
2908     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2909                        getPointerTy(DAG.getDataLayout()));
2910   }
2911 }
2912 
2913 const MCExpr *
2914 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2915                                                 unsigned JTI,
2916                                                 MCContext &Ctx) const {
2917   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2918     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2919 
2920   switch (getTargetMachine().getCodeModel()) {
2921   case CodeModel::Small:
2922   case CodeModel::Medium:
2923     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2924   default:
2925     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2926   }
2927 }
2928 
2929 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2930   EVT PtrVT = Op.getValueType();
2931   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2932 
2933   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2934   if (Subtarget.isUsingPCRelativeCalls()) {
2935     SDLoc DL(JT);
2936     EVT Ty = getPointerTy(DAG.getDataLayout());
2937     SDValue GA =
2938         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2939     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2940     return MatAddr;
2941   }
2942 
2943   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2944   // The actual address of the GlobalValue is stored in the TOC.
2945   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2946     setUsesTOCBasePtr(DAG);
2947     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2948     return getTOCEntry(DAG, SDLoc(JT), GA);
2949   }
2950 
2951   unsigned MOHiFlag, MOLoFlag;
2952   bool IsPIC = isPositionIndependent();
2953   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2954 
2955   if (IsPIC && Subtarget.isSVR4ABI()) {
2956     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2957                                         PPCII::MO_PIC_FLAG);
2958     return getTOCEntry(DAG, SDLoc(GA), GA);
2959   }
2960 
2961   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2962   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2963   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2964 }
2965 
2966 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2967                                              SelectionDAG &DAG) const {
2968   EVT PtrVT = Op.getValueType();
2969   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2970   const BlockAddress *BA = BASDN->getBlockAddress();
2971 
2972   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2973   if (Subtarget.isUsingPCRelativeCalls()) {
2974     SDLoc DL(BASDN);
2975     EVT Ty = getPointerTy(DAG.getDataLayout());
2976     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2977                                            PPCII::MO_PCREL_FLAG);
2978     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2979     return MatAddr;
2980   }
2981 
2982   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2983   // The actual BlockAddress is stored in the TOC.
2984   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2985     setUsesTOCBasePtr(DAG);
2986     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2987     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2988   }
2989 
2990   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2991   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2992     return getTOCEntry(
2993         DAG, SDLoc(BASDN),
2994         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2995 
2996   unsigned MOHiFlag, MOLoFlag;
2997   bool IsPIC = isPositionIndependent();
2998   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2999   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3000   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3001   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3002 }
3003 
3004 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3005                                               SelectionDAG &DAG) const {
3006   // FIXME: TLS addresses currently use medium model code sequences,
3007   // which is the most useful form.  Eventually support for small and
3008   // large models could be added if users need it, at the cost of
3009   // additional complexity.
3010   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3011   if (DAG.getTarget().useEmulatedTLS())
3012     return LowerToTLSEmulatedModel(GA, DAG);
3013 
3014   SDLoc dl(GA);
3015   const GlobalValue *GV = GA->getGlobal();
3016   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3017   bool is64bit = Subtarget.isPPC64();
3018   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3019   PICLevel::Level picLevel = M->getPICLevel();
3020 
3021   const TargetMachine &TM = getTargetMachine();
3022   TLSModel::Model Model = TM.getTLSModel(GV);
3023 
3024   if (Model == TLSModel::LocalExec) {
3025     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3026                                                PPCII::MO_TPREL_HA);
3027     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3028                                                PPCII::MO_TPREL_LO);
3029     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3030                              : DAG.getRegister(PPC::R2, MVT::i32);
3031 
3032     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3033     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3034   }
3035 
3036   if (Model == TLSModel::InitialExec) {
3037     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3038     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3039                                                 PPCII::MO_TLS);
3040     SDValue GOTPtr;
3041     if (is64bit) {
3042       setUsesTOCBasePtr(DAG);
3043       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3044       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
3045                            PtrVT, GOTReg, TGA);
3046     } else {
3047       if (!TM.isPositionIndependent())
3048         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3049       else if (picLevel == PICLevel::SmallPIC)
3050         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3051       else
3052         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3053     }
3054     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3055                                    PtrVT, TGA, GOTPtr);
3056     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3057   }
3058 
3059   if (Model == TLSModel::GeneralDynamic) {
3060     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3061     SDValue GOTPtr;
3062     if (is64bit) {
3063       setUsesTOCBasePtr(DAG);
3064       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3065       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3066                                    GOTReg, TGA);
3067     } else {
3068       if (picLevel == PICLevel::SmallPIC)
3069         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3070       else
3071         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3072     }
3073     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3074                        GOTPtr, TGA, TGA);
3075   }
3076 
3077   if (Model == TLSModel::LocalDynamic) {
3078     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3079     SDValue GOTPtr;
3080     if (is64bit) {
3081       setUsesTOCBasePtr(DAG);
3082       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3083       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3084                            GOTReg, TGA);
3085     } else {
3086       if (picLevel == PICLevel::SmallPIC)
3087         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3088       else
3089         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3090     }
3091     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3092                                   PtrVT, GOTPtr, TGA, TGA);
3093     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3094                                       PtrVT, TLSAddr, TGA);
3095     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3096   }
3097 
3098   llvm_unreachable("Unknown TLS model!");
3099 }
3100 
3101 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3102                                               SelectionDAG &DAG) const {
3103   EVT PtrVT = Op.getValueType();
3104   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3105   SDLoc DL(GSDN);
3106   const GlobalValue *GV = GSDN->getGlobal();
3107 
3108   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3109   // The actual address of the GlobalValue is stored in the TOC.
3110   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3111     if (Subtarget.isUsingPCRelativeCalls()) {
3112       EVT Ty = getPointerTy(DAG.getDataLayout());
3113       if (isAccessedAsGotIndirect(Op)) {
3114         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3115                                                 PPCII::MO_PCREL_FLAG |
3116                                                     PPCII::MO_GOT_FLAG);
3117         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3118         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3119                                    MachinePointerInfo());
3120         return Load;
3121       } else {
3122         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3123                                                 PPCII::MO_PCREL_FLAG);
3124         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3125       }
3126     }
3127     setUsesTOCBasePtr(DAG);
3128     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3129     return getTOCEntry(DAG, DL, GA);
3130   }
3131 
3132   unsigned MOHiFlag, MOLoFlag;
3133   bool IsPIC = isPositionIndependent();
3134   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3135 
3136   if (IsPIC && Subtarget.isSVR4ABI()) {
3137     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3138                                             GSDN->getOffset(),
3139                                             PPCII::MO_PIC_FLAG);
3140     return getTOCEntry(DAG, DL, GA);
3141   }
3142 
3143   SDValue GAHi =
3144     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3145   SDValue GALo =
3146     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3147 
3148   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3149 }
3150 
3151 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3152   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3153   SDLoc dl(Op);
3154 
3155   if (Op.getValueType() == MVT::v2i64) {
3156     // When the operands themselves are v2i64 values, we need to do something
3157     // special because VSX has no underlying comparison operations for these.
3158     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3159       // Equality can be handled by casting to the legal type for Altivec
3160       // comparisons, everything else needs to be expanded.
3161       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3162         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3163                  DAG.getSetCC(dl, MVT::v4i32,
3164                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3165                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3166                    CC));
3167       }
3168 
3169       return SDValue();
3170     }
3171 
3172     // We handle most of these in the usual way.
3173     return Op;
3174   }
3175 
3176   // If we're comparing for equality to zero, expose the fact that this is
3177   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3178   // fold the new nodes.
3179   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3180     return V;
3181 
3182   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3183     // Leave comparisons against 0 and -1 alone for now, since they're usually
3184     // optimized.  FIXME: revisit this when we can custom lower all setcc
3185     // optimizations.
3186     if (C->isAllOnesValue() || C->isNullValue())
3187       return SDValue();
3188   }
3189 
3190   // If we have an integer seteq/setne, turn it into a compare against zero
3191   // by xor'ing the rhs with the lhs, which is faster than setting a
3192   // condition register, reading it back out, and masking the correct bit.  The
3193   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3194   // the result to other bit-twiddling opportunities.
3195   EVT LHSVT = Op.getOperand(0).getValueType();
3196   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3197     EVT VT = Op.getValueType();
3198     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3199                                 Op.getOperand(1));
3200     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3201   }
3202   return SDValue();
3203 }
3204 
3205 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3206   SDNode *Node = Op.getNode();
3207   EVT VT = Node->getValueType(0);
3208   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3209   SDValue InChain = Node->getOperand(0);
3210   SDValue VAListPtr = Node->getOperand(1);
3211   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3212   SDLoc dl(Node);
3213 
3214   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3215 
3216   // gpr_index
3217   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3218                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3219   InChain = GprIndex.getValue(1);
3220 
3221   if (VT == MVT::i64) {
3222     // Check if GprIndex is even
3223     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3224                                  DAG.getConstant(1, dl, MVT::i32));
3225     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3226                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3227     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3228                                           DAG.getConstant(1, dl, MVT::i32));
3229     // Align GprIndex to be even if it isn't
3230     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3231                            GprIndex);
3232   }
3233 
3234   // fpr index is 1 byte after gpr
3235   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3236                                DAG.getConstant(1, dl, MVT::i32));
3237 
3238   // fpr
3239   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3240                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3241   InChain = FprIndex.getValue(1);
3242 
3243   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3244                                        DAG.getConstant(8, dl, MVT::i32));
3245 
3246   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3247                                         DAG.getConstant(4, dl, MVT::i32));
3248 
3249   // areas
3250   SDValue OverflowArea =
3251       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3252   InChain = OverflowArea.getValue(1);
3253 
3254   SDValue RegSaveArea =
3255       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3256   InChain = RegSaveArea.getValue(1);
3257 
3258   // select overflow_area if index > 8
3259   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3260                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3261 
3262   // adjustment constant gpr_index * 4/8
3263   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3264                                     VT.isInteger() ? GprIndex : FprIndex,
3265                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3266                                                     MVT::i32));
3267 
3268   // OurReg = RegSaveArea + RegConstant
3269   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3270                                RegConstant);
3271 
3272   // Floating types are 32 bytes into RegSaveArea
3273   if (VT.isFloatingPoint())
3274     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3275                          DAG.getConstant(32, dl, MVT::i32));
3276 
3277   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3278   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3279                                    VT.isInteger() ? GprIndex : FprIndex,
3280                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3281                                                    MVT::i32));
3282 
3283   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3284                               VT.isInteger() ? VAListPtr : FprPtr,
3285                               MachinePointerInfo(SV), MVT::i8);
3286 
3287   // determine if we should load from reg_save_area or overflow_area
3288   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3289 
3290   // increase overflow_area by 4/8 if gpr/fpr > 8
3291   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3292                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3293                                           dl, MVT::i32));
3294 
3295   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3296                              OverflowAreaPlusN);
3297 
3298   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3299                               MachinePointerInfo(), MVT::i32);
3300 
3301   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3302 }
3303 
3304 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3305   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3306 
3307   // We have to copy the entire va_list struct:
3308   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3309   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3310                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3311                        false, true, false, MachinePointerInfo(),
3312                        MachinePointerInfo());
3313 }
3314 
3315 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3316                                                   SelectionDAG &DAG) const {
3317   if (Subtarget.isAIXABI())
3318     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3319 
3320   return Op.getOperand(0);
3321 }
3322 
3323 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3324                                                 SelectionDAG &DAG) const {
3325   if (Subtarget.isAIXABI())
3326     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3327 
3328   SDValue Chain = Op.getOperand(0);
3329   SDValue Trmp = Op.getOperand(1); // trampoline
3330   SDValue FPtr = Op.getOperand(2); // nested function
3331   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3332   SDLoc dl(Op);
3333 
3334   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3335   bool isPPC64 = (PtrVT == MVT::i64);
3336   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3337 
3338   TargetLowering::ArgListTy Args;
3339   TargetLowering::ArgListEntry Entry;
3340 
3341   Entry.Ty = IntPtrTy;
3342   Entry.Node = Trmp; Args.push_back(Entry);
3343 
3344   // TrampSize == (isPPC64 ? 48 : 40);
3345   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3346                                isPPC64 ? MVT::i64 : MVT::i32);
3347   Args.push_back(Entry);
3348 
3349   Entry.Node = FPtr; Args.push_back(Entry);
3350   Entry.Node = Nest; Args.push_back(Entry);
3351 
3352   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3353   TargetLowering::CallLoweringInfo CLI(DAG);
3354   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3355       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3356       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3357 
3358   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3359   return CallResult.second;
3360 }
3361 
3362 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3363   MachineFunction &MF = DAG.getMachineFunction();
3364   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3365   EVT PtrVT = getPointerTy(MF.getDataLayout());
3366 
3367   SDLoc dl(Op);
3368 
3369   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3370     // vastart just stores the address of the VarArgsFrameIndex slot into the
3371     // memory location argument.
3372     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3373     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3374     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3375                         MachinePointerInfo(SV));
3376   }
3377 
3378   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3379   // We suppose the given va_list is already allocated.
3380   //
3381   // typedef struct {
3382   //  char gpr;     /* index into the array of 8 GPRs
3383   //                 * stored in the register save area
3384   //                 * gpr=0 corresponds to r3,
3385   //                 * gpr=1 to r4, etc.
3386   //                 */
3387   //  char fpr;     /* index into the array of 8 FPRs
3388   //                 * stored in the register save area
3389   //                 * fpr=0 corresponds to f1,
3390   //                 * fpr=1 to f2, etc.
3391   //                 */
3392   //  char *overflow_arg_area;
3393   //                /* location on stack that holds
3394   //                 * the next overflow argument
3395   //                 */
3396   //  char *reg_save_area;
3397   //               /* where r3:r10 and f1:f8 (if saved)
3398   //                * are stored
3399   //                */
3400   // } va_list[1];
3401 
3402   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3403   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3404   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3405                                             PtrVT);
3406   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3407                                  PtrVT);
3408 
3409   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3410   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3411 
3412   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3413   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3414 
3415   uint64_t FPROffset = 1;
3416   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3417 
3418   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3419 
3420   // Store first byte : number of int regs
3421   SDValue firstStore =
3422       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3423                         MachinePointerInfo(SV), MVT::i8);
3424   uint64_t nextOffset = FPROffset;
3425   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3426                                   ConstFPROffset);
3427 
3428   // Store second byte : number of float regs
3429   SDValue secondStore =
3430       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3431                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3432   nextOffset += StackOffset;
3433   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3434 
3435   // Store second word : arguments given on stack
3436   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3437                                     MachinePointerInfo(SV, nextOffset));
3438   nextOffset += FrameOffset;
3439   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3440 
3441   // Store third word : arguments given in registers
3442   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3443                       MachinePointerInfo(SV, nextOffset));
3444 }
3445 
3446 /// FPR - The set of FP registers that should be allocated for arguments
3447 /// on Darwin and AIX.
3448 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3449                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3450                                 PPC::F11, PPC::F12, PPC::F13};
3451 
3452 /// QFPR - The set of QPX registers that should be allocated for arguments.
3453 static const MCPhysReg QFPR[] = {
3454     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3455     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3456 
3457 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3458 /// the stack.
3459 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3460                                        unsigned PtrByteSize) {
3461   unsigned ArgSize = ArgVT.getStoreSize();
3462   if (Flags.isByVal())
3463     ArgSize = Flags.getByValSize();
3464 
3465   // Round up to multiples of the pointer size, except for array members,
3466   // which are always packed.
3467   if (!Flags.isInConsecutiveRegs())
3468     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3469 
3470   return ArgSize;
3471 }
3472 
3473 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3474 /// on the stack.
3475 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3476                                          ISD::ArgFlagsTy Flags,
3477                                          unsigned PtrByteSize) {
3478   Align Alignment(PtrByteSize);
3479 
3480   // Altivec parameters are padded to a 16 byte boundary.
3481   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3482       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3483       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3484       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3485     Alignment = Align(16);
3486   // QPX vector types stored in double-precision are padded to a 32 byte
3487   // boundary.
3488   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3489     Alignment = Align(32);
3490 
3491   // ByVal parameters are aligned as requested.
3492   if (Flags.isByVal()) {
3493     auto BVAlign = Flags.getNonZeroByValAlign();
3494     if (BVAlign > PtrByteSize) {
3495       if (BVAlign.value() % PtrByteSize != 0)
3496         llvm_unreachable(
3497             "ByVal alignment is not a multiple of the pointer size");
3498 
3499       Alignment = BVAlign;
3500     }
3501   }
3502 
3503   // Array members are always packed to their original alignment.
3504   if (Flags.isInConsecutiveRegs()) {
3505     // If the array member was split into multiple registers, the first
3506     // needs to be aligned to the size of the full type.  (Except for
3507     // ppcf128, which is only aligned as its f64 components.)
3508     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3509       Alignment = Align(OrigVT.getStoreSize());
3510     else
3511       Alignment = Align(ArgVT.getStoreSize());
3512   }
3513 
3514   return Alignment;
3515 }
3516 
3517 /// CalculateStackSlotUsed - Return whether this argument will use its
3518 /// stack slot (instead of being passed in registers).  ArgOffset,
3519 /// AvailableFPRs, and AvailableVRs must hold the current argument
3520 /// position, and will be updated to account for this argument.
3521 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3522                                    ISD::ArgFlagsTy Flags,
3523                                    unsigned PtrByteSize,
3524                                    unsigned LinkageSize,
3525                                    unsigned ParamAreaSize,
3526                                    unsigned &ArgOffset,
3527                                    unsigned &AvailableFPRs,
3528                                    unsigned &AvailableVRs, bool HasQPX) {
3529   bool UseMemory = false;
3530 
3531   // Respect alignment of argument on the stack.
3532   Align Alignment =
3533       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3534   ArgOffset = alignTo(ArgOffset, Alignment);
3535   // If there's no space left in the argument save area, we must
3536   // use memory (this check also catches zero-sized arguments).
3537   if (ArgOffset >= LinkageSize + ParamAreaSize)
3538     UseMemory = true;
3539 
3540   // Allocate argument on the stack.
3541   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3542   if (Flags.isInConsecutiveRegsLast())
3543     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3544   // If we overran the argument save area, we must use memory
3545   // (this check catches arguments passed partially in memory)
3546   if (ArgOffset > LinkageSize + ParamAreaSize)
3547     UseMemory = true;
3548 
3549   // However, if the argument is actually passed in an FPR or a VR,
3550   // we don't use memory after all.
3551   if (!Flags.isByVal()) {
3552     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3553         // QPX registers overlap with the scalar FP registers.
3554         (HasQPX && (ArgVT == MVT::v4f32 ||
3555                     ArgVT == MVT::v4f64 ||
3556                     ArgVT == MVT::v4i1)))
3557       if (AvailableFPRs > 0) {
3558         --AvailableFPRs;
3559         return false;
3560       }
3561     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3562         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3563         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3564         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3565       if (AvailableVRs > 0) {
3566         --AvailableVRs;
3567         return false;
3568       }
3569   }
3570 
3571   return UseMemory;
3572 }
3573 
3574 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3575 /// ensure minimum alignment required for target.
3576 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3577                                      unsigned NumBytes) {
3578   return alignTo(NumBytes, Lowering->getStackAlign());
3579 }
3580 
3581 SDValue PPCTargetLowering::LowerFormalArguments(
3582     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3583     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3584     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3585   if (Subtarget.isAIXABI())
3586     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3587                                     InVals);
3588   if (Subtarget.is64BitELFABI())
3589     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3590                                        InVals);
3591   if (Subtarget.is32BitELFABI())
3592     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3593                                        InVals);
3594 
3595   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3596                                      InVals);
3597 }
3598 
3599 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3600     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3601     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3602     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3603 
3604   // 32-bit SVR4 ABI Stack Frame Layout:
3605   //              +-----------------------------------+
3606   //        +-->  |            Back chain             |
3607   //        |     +-----------------------------------+
3608   //        |     | Floating-point register save area |
3609   //        |     +-----------------------------------+
3610   //        |     |    General register save area     |
3611   //        |     +-----------------------------------+
3612   //        |     |          CR save word             |
3613   //        |     +-----------------------------------+
3614   //        |     |         VRSAVE save word          |
3615   //        |     +-----------------------------------+
3616   //        |     |         Alignment padding         |
3617   //        |     +-----------------------------------+
3618   //        |     |     Vector register save area     |
3619   //        |     +-----------------------------------+
3620   //        |     |       Local variable space        |
3621   //        |     +-----------------------------------+
3622   //        |     |        Parameter list area        |
3623   //        |     +-----------------------------------+
3624   //        |     |           LR save word            |
3625   //        |     +-----------------------------------+
3626   // SP-->  +---  |            Back chain             |
3627   //              +-----------------------------------+
3628   //
3629   // Specifications:
3630   //   System V Application Binary Interface PowerPC Processor Supplement
3631   //   AltiVec Technology Programming Interface Manual
3632 
3633   MachineFunction &MF = DAG.getMachineFunction();
3634   MachineFrameInfo &MFI = MF.getFrameInfo();
3635   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3636 
3637   EVT PtrVT = getPointerTy(MF.getDataLayout());
3638   // Potential tail calls could cause overwriting of argument stack slots.
3639   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3640                        (CallConv == CallingConv::Fast));
3641   const Align PtrAlign(4);
3642 
3643   // Assign locations to all of the incoming arguments.
3644   SmallVector<CCValAssign, 16> ArgLocs;
3645   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3646                  *DAG.getContext());
3647 
3648   // Reserve space for the linkage area on the stack.
3649   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3650   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3651   if (useSoftFloat())
3652     CCInfo.PreAnalyzeFormalArguments(Ins);
3653 
3654   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3655   CCInfo.clearWasPPCF128();
3656 
3657   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3658     CCValAssign &VA = ArgLocs[i];
3659 
3660     // Arguments stored in registers.
3661     if (VA.isRegLoc()) {
3662       const TargetRegisterClass *RC;
3663       EVT ValVT = VA.getValVT();
3664 
3665       switch (ValVT.getSimpleVT().SimpleTy) {
3666         default:
3667           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3668         case MVT::i1:
3669         case MVT::i32:
3670           RC = &PPC::GPRCRegClass;
3671           break;
3672         case MVT::f32:
3673           if (Subtarget.hasP8Vector())
3674             RC = &PPC::VSSRCRegClass;
3675           else if (Subtarget.hasSPE())
3676             RC = &PPC::GPRCRegClass;
3677           else
3678             RC = &PPC::F4RCRegClass;
3679           break;
3680         case MVT::f64:
3681           if (Subtarget.hasVSX())
3682             RC = &PPC::VSFRCRegClass;
3683           else if (Subtarget.hasSPE())
3684             // SPE passes doubles in GPR pairs.
3685             RC = &PPC::GPRCRegClass;
3686           else
3687             RC = &PPC::F8RCRegClass;
3688           break;
3689         case MVT::v16i8:
3690         case MVT::v8i16:
3691         case MVT::v4i32:
3692           RC = &PPC::VRRCRegClass;
3693           break;
3694         case MVT::v4f32:
3695           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3696           break;
3697         case MVT::v2f64:
3698         case MVT::v2i64:
3699           RC = &PPC::VRRCRegClass;
3700           break;
3701         case MVT::v4f64:
3702           RC = &PPC::QFRCRegClass;
3703           break;
3704         case MVT::v4i1:
3705           RC = &PPC::QBRCRegClass;
3706           break;
3707       }
3708 
3709       SDValue ArgValue;
3710       // Transform the arguments stored in physical registers into
3711       // virtual ones.
3712       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3713         assert(i + 1 < e && "No second half of double precision argument");
3714         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3715         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3716         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3717         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3718         if (!Subtarget.isLittleEndian())
3719           std::swap (ArgValueLo, ArgValueHi);
3720         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3721                                ArgValueHi);
3722       } else {
3723         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3724         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3725                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3726         if (ValVT == MVT::i1)
3727           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3728       }
3729 
3730       InVals.push_back(ArgValue);
3731     } else {
3732       // Argument stored in memory.
3733       assert(VA.isMemLoc());
3734 
3735       // Get the extended size of the argument type in stack
3736       unsigned ArgSize = VA.getLocVT().getStoreSize();
3737       // Get the actual size of the argument type
3738       unsigned ObjSize = VA.getValVT().getStoreSize();
3739       unsigned ArgOffset = VA.getLocMemOffset();
3740       // Stack objects in PPC32 are right justified.
3741       ArgOffset += ArgSize - ObjSize;
3742       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3743 
3744       // Create load nodes to retrieve arguments from the stack.
3745       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3746       InVals.push_back(
3747           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3748     }
3749   }
3750 
3751   // Assign locations to all of the incoming aggregate by value arguments.
3752   // Aggregates passed by value are stored in the local variable space of the
3753   // caller's stack frame, right above the parameter list area.
3754   SmallVector<CCValAssign, 16> ByValArgLocs;
3755   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3756                       ByValArgLocs, *DAG.getContext());
3757 
3758   // Reserve stack space for the allocations in CCInfo.
3759   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3760 
3761   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3762 
3763   // Area that is at least reserved in the caller of this function.
3764   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3765   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3766 
3767   // Set the size that is at least reserved in caller of this function.  Tail
3768   // call optimized function's reserved stack space needs to be aligned so that
3769   // taking the difference between two stack areas will result in an aligned
3770   // stack.
3771   MinReservedArea =
3772       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3773   FuncInfo->setMinReservedArea(MinReservedArea);
3774 
3775   SmallVector<SDValue, 8> MemOps;
3776 
3777   // If the function takes variable number of arguments, make a frame index for
3778   // the start of the first vararg value... for expansion of llvm.va_start.
3779   if (isVarArg) {
3780     static const MCPhysReg GPArgRegs[] = {
3781       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3782       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3783     };
3784     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3785 
3786     static const MCPhysReg FPArgRegs[] = {
3787       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3788       PPC::F8
3789     };
3790     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3791 
3792     if (useSoftFloat() || hasSPE())
3793        NumFPArgRegs = 0;
3794 
3795     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3796     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3797 
3798     // Make room for NumGPArgRegs and NumFPArgRegs.
3799     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3800                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3801 
3802     FuncInfo->setVarArgsStackOffset(
3803       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3804                             CCInfo.getNextStackOffset(), true));
3805 
3806     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3807     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3808 
3809     // The fixed integer arguments of a variadic function are stored to the
3810     // VarArgsFrameIndex on the stack so that they may be loaded by
3811     // dereferencing the result of va_next.
3812     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3813       // Get an existing live-in vreg, or add a new one.
3814       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3815       if (!VReg)
3816         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3817 
3818       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3819       SDValue Store =
3820           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3821       MemOps.push_back(Store);
3822       // Increment the address by four for the next argument to store
3823       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3824       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3825     }
3826 
3827     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3828     // is set.
3829     // The double arguments are stored to the VarArgsFrameIndex
3830     // on the stack.
3831     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3832       // Get an existing live-in vreg, or add a new one.
3833       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3834       if (!VReg)
3835         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3836 
3837       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3838       SDValue Store =
3839           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3840       MemOps.push_back(Store);
3841       // Increment the address by eight for the next argument to store
3842       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3843                                          PtrVT);
3844       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3845     }
3846   }
3847 
3848   if (!MemOps.empty())
3849     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3850 
3851   return Chain;
3852 }
3853 
3854 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3855 // value to MVT::i64 and then truncate to the correct register size.
3856 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3857                                              EVT ObjectVT, SelectionDAG &DAG,
3858                                              SDValue ArgVal,
3859                                              const SDLoc &dl) const {
3860   if (Flags.isSExt())
3861     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3862                          DAG.getValueType(ObjectVT));
3863   else if (Flags.isZExt())
3864     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3865                          DAG.getValueType(ObjectVT));
3866 
3867   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3868 }
3869 
3870 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3871     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3872     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3873     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3874   // TODO: add description of PPC stack frame format, or at least some docs.
3875   //
3876   bool isELFv2ABI = Subtarget.isELFv2ABI();
3877   bool isLittleEndian = Subtarget.isLittleEndian();
3878   MachineFunction &MF = DAG.getMachineFunction();
3879   MachineFrameInfo &MFI = MF.getFrameInfo();
3880   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3881 
3882   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3883          "fastcc not supported on varargs functions");
3884 
3885   EVT PtrVT = getPointerTy(MF.getDataLayout());
3886   // Potential tail calls could cause overwriting of argument stack slots.
3887   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3888                        (CallConv == CallingConv::Fast));
3889   unsigned PtrByteSize = 8;
3890   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3891 
3892   static const MCPhysReg GPR[] = {
3893     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3894     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3895   };
3896   static const MCPhysReg VR[] = {
3897     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3898     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3899   };
3900 
3901   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3902   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3903   const unsigned Num_VR_Regs  = array_lengthof(VR);
3904   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3905 
3906   // Do a first pass over the arguments to determine whether the ABI
3907   // guarantees that our caller has allocated the parameter save area
3908   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3909   // in the ELFv2 ABI, it is true if this is a vararg function or if
3910   // any parameter is located in a stack slot.
3911 
3912   bool HasParameterArea = !isELFv2ABI || isVarArg;
3913   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3914   unsigned NumBytes = LinkageSize;
3915   unsigned AvailableFPRs = Num_FPR_Regs;
3916   unsigned AvailableVRs = Num_VR_Regs;
3917   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3918     if (Ins[i].Flags.isNest())
3919       continue;
3920 
3921     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3922                                PtrByteSize, LinkageSize, ParamAreaSize,
3923                                NumBytes, AvailableFPRs, AvailableVRs,
3924                                Subtarget.hasQPX()))
3925       HasParameterArea = true;
3926   }
3927 
3928   // Add DAG nodes to load the arguments or copy them out of registers.  On
3929   // entry to a function on PPC, the arguments start after the linkage area,
3930   // although the first ones are often in registers.
3931 
3932   unsigned ArgOffset = LinkageSize;
3933   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3934   unsigned &QFPR_idx = FPR_idx;
3935   SmallVector<SDValue, 8> MemOps;
3936   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3937   unsigned CurArgIdx = 0;
3938   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3939     SDValue ArgVal;
3940     bool needsLoad = false;
3941     EVT ObjectVT = Ins[ArgNo].VT;
3942     EVT OrigVT = Ins[ArgNo].ArgVT;
3943     unsigned ObjSize = ObjectVT.getStoreSize();
3944     unsigned ArgSize = ObjSize;
3945     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3946     if (Ins[ArgNo].isOrigArg()) {
3947       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3948       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3949     }
3950     // We re-align the argument offset for each argument, except when using the
3951     // fast calling convention, when we need to make sure we do that only when
3952     // we'll actually use a stack slot.
3953     unsigned CurArgOffset;
3954     Align Alignment;
3955     auto ComputeArgOffset = [&]() {
3956       /* Respect alignment of argument on the stack.  */
3957       Alignment =
3958           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3959       ArgOffset = alignTo(ArgOffset, Alignment);
3960       CurArgOffset = ArgOffset;
3961     };
3962 
3963     if (CallConv != CallingConv::Fast) {
3964       ComputeArgOffset();
3965 
3966       /* Compute GPR index associated with argument offset.  */
3967       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3968       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3969     }
3970 
3971     // FIXME the codegen can be much improved in some cases.
3972     // We do not have to keep everything in memory.
3973     if (Flags.isByVal()) {
3974       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3975 
3976       if (CallConv == CallingConv::Fast)
3977         ComputeArgOffset();
3978 
3979       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3980       ObjSize = Flags.getByValSize();
3981       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3982       // Empty aggregate parameters do not take up registers.  Examples:
3983       //   struct { } a;
3984       //   union  { } b;
3985       //   int c[0];
3986       // etc.  However, we have to provide a place-holder in InVals, so
3987       // pretend we have an 8-byte item at the current address for that
3988       // purpose.
3989       if (!ObjSize) {
3990         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3991         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3992         InVals.push_back(FIN);
3993         continue;
3994       }
3995 
3996       // Create a stack object covering all stack doublewords occupied
3997       // by the argument.  If the argument is (fully or partially) on
3998       // the stack, or if the argument is fully in registers but the
3999       // caller has allocated the parameter save anyway, we can refer
4000       // directly to the caller's stack frame.  Otherwise, create a
4001       // local copy in our own frame.
4002       int FI;
4003       if (HasParameterArea ||
4004           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4005         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4006       else
4007         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4008       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4009 
4010       // Handle aggregates smaller than 8 bytes.
4011       if (ObjSize < PtrByteSize) {
4012         // The value of the object is its address, which differs from the
4013         // address of the enclosing doubleword on big-endian systems.
4014         SDValue Arg = FIN;
4015         if (!isLittleEndian) {
4016           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4017           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4018         }
4019         InVals.push_back(Arg);
4020 
4021         if (GPR_idx != Num_GPR_Regs) {
4022           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4023           FuncInfo->addLiveInAttr(VReg, Flags);
4024           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4025           SDValue Store;
4026 
4027           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4028             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4029                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4030             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4031                                       MachinePointerInfo(&*FuncArg), ObjType);
4032           } else {
4033             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4034             // store the whole register as-is to the parameter save area
4035             // slot.
4036             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4037                                  MachinePointerInfo(&*FuncArg));
4038           }
4039 
4040           MemOps.push_back(Store);
4041         }
4042         // Whether we copied from a register or not, advance the offset
4043         // into the parameter save area by a full doubleword.
4044         ArgOffset += PtrByteSize;
4045         continue;
4046       }
4047 
4048       // The value of the object is its address, which is the address of
4049       // its first stack doubleword.
4050       InVals.push_back(FIN);
4051 
4052       // Store whatever pieces of the object are in registers to memory.
4053       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4054         if (GPR_idx == Num_GPR_Regs)
4055           break;
4056 
4057         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4058         FuncInfo->addLiveInAttr(VReg, Flags);
4059         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4060         SDValue Addr = FIN;
4061         if (j) {
4062           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4063           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4064         }
4065         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4066                                      MachinePointerInfo(&*FuncArg, j));
4067         MemOps.push_back(Store);
4068         ++GPR_idx;
4069       }
4070       ArgOffset += ArgSize;
4071       continue;
4072     }
4073 
4074     switch (ObjectVT.getSimpleVT().SimpleTy) {
4075     default: llvm_unreachable("Unhandled argument type!");
4076     case MVT::i1:
4077     case MVT::i32:
4078     case MVT::i64:
4079       if (Flags.isNest()) {
4080         // The 'nest' parameter, if any, is passed in R11.
4081         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4082         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4083 
4084         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4085           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4086 
4087         break;
4088       }
4089 
4090       // These can be scalar arguments or elements of an integer array type
4091       // passed directly.  Clang may use those instead of "byval" aggregate
4092       // types to avoid forcing arguments to memory unnecessarily.
4093       if (GPR_idx != Num_GPR_Regs) {
4094         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4095         FuncInfo->addLiveInAttr(VReg, Flags);
4096         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4097 
4098         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4099           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4100           // value to MVT::i64 and then truncate to the correct register size.
4101           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4102       } else {
4103         if (CallConv == CallingConv::Fast)
4104           ComputeArgOffset();
4105 
4106         needsLoad = true;
4107         ArgSize = PtrByteSize;
4108       }
4109       if (CallConv != CallingConv::Fast || needsLoad)
4110         ArgOffset += 8;
4111       break;
4112 
4113     case MVT::f32:
4114     case MVT::f64:
4115       // These can be scalar arguments or elements of a float array type
4116       // passed directly.  The latter are used to implement ELFv2 homogenous
4117       // float aggregates.
4118       if (FPR_idx != Num_FPR_Regs) {
4119         unsigned VReg;
4120 
4121         if (ObjectVT == MVT::f32)
4122           VReg = MF.addLiveIn(FPR[FPR_idx],
4123                               Subtarget.hasP8Vector()
4124                                   ? &PPC::VSSRCRegClass
4125                                   : &PPC::F4RCRegClass);
4126         else
4127           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4128                                                 ? &PPC::VSFRCRegClass
4129                                                 : &PPC::F8RCRegClass);
4130 
4131         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4132         ++FPR_idx;
4133       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4134         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4135         // once we support fp <-> gpr moves.
4136 
4137         // This can only ever happen in the presence of f32 array types,
4138         // since otherwise we never run out of FPRs before running out
4139         // of GPRs.
4140         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4141         FuncInfo->addLiveInAttr(VReg, Flags);
4142         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4143 
4144         if (ObjectVT == MVT::f32) {
4145           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4146             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4147                                  DAG.getConstant(32, dl, MVT::i32));
4148           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4149         }
4150 
4151         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4152       } else {
4153         if (CallConv == CallingConv::Fast)
4154           ComputeArgOffset();
4155 
4156         needsLoad = true;
4157       }
4158 
4159       // When passing an array of floats, the array occupies consecutive
4160       // space in the argument area; only round up to the next doubleword
4161       // at the end of the array.  Otherwise, each float takes 8 bytes.
4162       if (CallConv != CallingConv::Fast || needsLoad) {
4163         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4164         ArgOffset += ArgSize;
4165         if (Flags.isInConsecutiveRegsLast())
4166           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4167       }
4168       break;
4169     case MVT::v4f32:
4170     case MVT::v4i32:
4171     case MVT::v8i16:
4172     case MVT::v16i8:
4173     case MVT::v2f64:
4174     case MVT::v2i64:
4175     case MVT::v1i128:
4176     case MVT::f128:
4177       if (!Subtarget.hasQPX()) {
4178         // These can be scalar arguments or elements of a vector array type
4179         // passed directly.  The latter are used to implement ELFv2 homogenous
4180         // vector aggregates.
4181         if (VR_idx != Num_VR_Regs) {
4182           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4183           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4184           ++VR_idx;
4185         } else {
4186           if (CallConv == CallingConv::Fast)
4187             ComputeArgOffset();
4188           needsLoad = true;
4189         }
4190         if (CallConv != CallingConv::Fast || needsLoad)
4191           ArgOffset += 16;
4192         break;
4193       } // not QPX
4194 
4195       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4196              "Invalid QPX parameter type");
4197       LLVM_FALLTHROUGH;
4198 
4199     case MVT::v4f64:
4200     case MVT::v4i1:
4201       // QPX vectors are treated like their scalar floating-point subregisters
4202       // (except that they're larger).
4203       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4204       if (QFPR_idx != Num_QFPR_Regs) {
4205         const TargetRegisterClass *RC;
4206         switch (ObjectVT.getSimpleVT().SimpleTy) {
4207         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4208         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4209         default:         RC = &PPC::QBRCRegClass; break;
4210         }
4211 
4212         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4213         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4214         ++QFPR_idx;
4215       } else {
4216         if (CallConv == CallingConv::Fast)
4217           ComputeArgOffset();
4218         needsLoad = true;
4219       }
4220       if (CallConv != CallingConv::Fast || needsLoad)
4221         ArgOffset += Sz;
4222       break;
4223     }
4224 
4225     // We need to load the argument to a virtual register if we determined
4226     // above that we ran out of physical registers of the appropriate type.
4227     if (needsLoad) {
4228       if (ObjSize < ArgSize && !isLittleEndian)
4229         CurArgOffset += ArgSize - ObjSize;
4230       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4231       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4232       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4233     }
4234 
4235     InVals.push_back(ArgVal);
4236   }
4237 
4238   // Area that is at least reserved in the caller of this function.
4239   unsigned MinReservedArea;
4240   if (HasParameterArea)
4241     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4242   else
4243     MinReservedArea = LinkageSize;
4244 
4245   // Set the size that is at least reserved in caller of this function.  Tail
4246   // call optimized functions' reserved stack space needs to be aligned so that
4247   // taking the difference between two stack areas will result in an aligned
4248   // stack.
4249   MinReservedArea =
4250       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4251   FuncInfo->setMinReservedArea(MinReservedArea);
4252 
4253   // If the function takes variable number of arguments, make a frame index for
4254   // the start of the first vararg value... for expansion of llvm.va_start.
4255   if (isVarArg) {
4256     int Depth = ArgOffset;
4257 
4258     FuncInfo->setVarArgsFrameIndex(
4259       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4260     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4261 
4262     // If this function is vararg, store any remaining integer argument regs
4263     // to their spots on the stack so that they may be loaded by dereferencing
4264     // the result of va_next.
4265     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4266          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4267       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4268       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4269       SDValue Store =
4270           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4271       MemOps.push_back(Store);
4272       // Increment the address by four for the next argument to store
4273       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4274       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4275     }
4276   }
4277 
4278   if (!MemOps.empty())
4279     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4280 
4281   return Chain;
4282 }
4283 
4284 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4285     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4286     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4287     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4288   // TODO: add description of PPC stack frame format, or at least some docs.
4289   //
4290   MachineFunction &MF = DAG.getMachineFunction();
4291   MachineFrameInfo &MFI = MF.getFrameInfo();
4292   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4293 
4294   EVT PtrVT = getPointerTy(MF.getDataLayout());
4295   bool isPPC64 = PtrVT == MVT::i64;
4296   // Potential tail calls could cause overwriting of argument stack slots.
4297   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4298                        (CallConv == CallingConv::Fast));
4299   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4300   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4301   unsigned ArgOffset = LinkageSize;
4302   // Area that is at least reserved in caller of this function.
4303   unsigned MinReservedArea = ArgOffset;
4304 
4305   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4306     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4307     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4308   };
4309   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4310     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4311     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4312   };
4313   static const MCPhysReg VR[] = {
4314     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4315     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4316   };
4317 
4318   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4319   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4320   const unsigned Num_VR_Regs  = array_lengthof( VR);
4321 
4322   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4323 
4324   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4325 
4326   // In 32-bit non-varargs functions, the stack space for vectors is after the
4327   // stack space for non-vectors.  We do not use this space unless we have
4328   // too many vectors to fit in registers, something that only occurs in
4329   // constructed examples:), but we have to walk the arglist to figure
4330   // that out...for the pathological case, compute VecArgOffset as the
4331   // start of the vector parameter area.  Computing VecArgOffset is the
4332   // entire point of the following loop.
4333   unsigned VecArgOffset = ArgOffset;
4334   if (!isVarArg && !isPPC64) {
4335     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4336          ++ArgNo) {
4337       EVT ObjectVT = Ins[ArgNo].VT;
4338       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4339 
4340       if (Flags.isByVal()) {
4341         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4342         unsigned ObjSize = Flags.getByValSize();
4343         unsigned ArgSize =
4344                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4345         VecArgOffset += ArgSize;
4346         continue;
4347       }
4348 
4349       switch(ObjectVT.getSimpleVT().SimpleTy) {
4350       default: llvm_unreachable("Unhandled argument type!");
4351       case MVT::i1:
4352       case MVT::i32:
4353       case MVT::f32:
4354         VecArgOffset += 4;
4355         break;
4356       case MVT::i64:  // PPC64
4357       case MVT::f64:
4358         // FIXME: We are guaranteed to be !isPPC64 at this point.
4359         // Does MVT::i64 apply?
4360         VecArgOffset += 8;
4361         break;
4362       case MVT::v4f32:
4363       case MVT::v4i32:
4364       case MVT::v8i16:
4365       case MVT::v16i8:
4366         // Nothing to do, we're only looking at Nonvector args here.
4367         break;
4368       }
4369     }
4370   }
4371   // We've found where the vector parameter area in memory is.  Skip the
4372   // first 12 parameters; these don't use that memory.
4373   VecArgOffset = ((VecArgOffset+15)/16)*16;
4374   VecArgOffset += 12*16;
4375 
4376   // Add DAG nodes to load the arguments or copy them out of registers.  On
4377   // entry to a function on PPC, the arguments start after the linkage area,
4378   // although the first ones are often in registers.
4379 
4380   SmallVector<SDValue, 8> MemOps;
4381   unsigned nAltivecParamsAtEnd = 0;
4382   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4383   unsigned CurArgIdx = 0;
4384   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4385     SDValue ArgVal;
4386     bool needsLoad = false;
4387     EVT ObjectVT = Ins[ArgNo].VT;
4388     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4389     unsigned ArgSize = ObjSize;
4390     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4391     if (Ins[ArgNo].isOrigArg()) {
4392       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4393       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4394     }
4395     unsigned CurArgOffset = ArgOffset;
4396 
4397     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4398     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4399         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4400       if (isVarArg || isPPC64) {
4401         MinReservedArea = ((MinReservedArea+15)/16)*16;
4402         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4403                                                   Flags,
4404                                                   PtrByteSize);
4405       } else  nAltivecParamsAtEnd++;
4406     } else
4407       // Calculate min reserved area.
4408       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4409                                                 Flags,
4410                                                 PtrByteSize);
4411 
4412     // FIXME the codegen can be much improved in some cases.
4413     // We do not have to keep everything in memory.
4414     if (Flags.isByVal()) {
4415       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4416 
4417       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4418       ObjSize = Flags.getByValSize();
4419       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4420       // Objects of size 1 and 2 are right justified, everything else is
4421       // left justified.  This means the memory address is adjusted forwards.
4422       if (ObjSize==1 || ObjSize==2) {
4423         CurArgOffset = CurArgOffset + (4 - ObjSize);
4424       }
4425       // The value of the object is its address.
4426       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4427       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4428       InVals.push_back(FIN);
4429       if (ObjSize==1 || ObjSize==2) {
4430         if (GPR_idx != Num_GPR_Regs) {
4431           unsigned VReg;
4432           if (isPPC64)
4433             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4434           else
4435             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4436           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4437           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4438           SDValue Store =
4439               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4440                                 MachinePointerInfo(&*FuncArg), ObjType);
4441           MemOps.push_back(Store);
4442           ++GPR_idx;
4443         }
4444 
4445         ArgOffset += PtrByteSize;
4446 
4447         continue;
4448       }
4449       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4450         // Store whatever pieces of the object are in registers
4451         // to memory.  ArgOffset will be the address of the beginning
4452         // of the object.
4453         if (GPR_idx != Num_GPR_Regs) {
4454           unsigned VReg;
4455           if (isPPC64)
4456             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4457           else
4458             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4459           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4460           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4461           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4462           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4463                                        MachinePointerInfo(&*FuncArg, j));
4464           MemOps.push_back(Store);
4465           ++GPR_idx;
4466           ArgOffset += PtrByteSize;
4467         } else {
4468           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4469           break;
4470         }
4471       }
4472       continue;
4473     }
4474 
4475     switch (ObjectVT.getSimpleVT().SimpleTy) {
4476     default: llvm_unreachable("Unhandled argument type!");
4477     case MVT::i1:
4478     case MVT::i32:
4479       if (!isPPC64) {
4480         if (GPR_idx != Num_GPR_Regs) {
4481           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4482           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4483 
4484           if (ObjectVT == MVT::i1)
4485             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4486 
4487           ++GPR_idx;
4488         } else {
4489           needsLoad = true;
4490           ArgSize = PtrByteSize;
4491         }
4492         // All int arguments reserve stack space in the Darwin ABI.
4493         ArgOffset += PtrByteSize;
4494         break;
4495       }
4496       LLVM_FALLTHROUGH;
4497     case MVT::i64:  // PPC64
4498       if (GPR_idx != Num_GPR_Regs) {
4499         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4500         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4501 
4502         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4503           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4504           // value to MVT::i64 and then truncate to the correct register size.
4505           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4506 
4507         ++GPR_idx;
4508       } else {
4509         needsLoad = true;
4510         ArgSize = PtrByteSize;
4511       }
4512       // All int arguments reserve stack space in the Darwin ABI.
4513       ArgOffset += 8;
4514       break;
4515 
4516     case MVT::f32:
4517     case MVT::f64:
4518       // Every 4 bytes of argument space consumes one of the GPRs available for
4519       // argument passing.
4520       if (GPR_idx != Num_GPR_Regs) {
4521         ++GPR_idx;
4522         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4523           ++GPR_idx;
4524       }
4525       if (FPR_idx != Num_FPR_Regs) {
4526         unsigned VReg;
4527 
4528         if (ObjectVT == MVT::f32)
4529           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4530         else
4531           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4532 
4533         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4534         ++FPR_idx;
4535       } else {
4536         needsLoad = true;
4537       }
4538 
4539       // All FP arguments reserve stack space in the Darwin ABI.
4540       ArgOffset += isPPC64 ? 8 : ObjSize;
4541       break;
4542     case MVT::v4f32:
4543     case MVT::v4i32:
4544     case MVT::v8i16:
4545     case MVT::v16i8:
4546       // Note that vector arguments in registers don't reserve stack space,
4547       // except in varargs functions.
4548       if (VR_idx != Num_VR_Regs) {
4549         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4550         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4551         if (isVarArg) {
4552           while ((ArgOffset % 16) != 0) {
4553             ArgOffset += PtrByteSize;
4554             if (GPR_idx != Num_GPR_Regs)
4555               GPR_idx++;
4556           }
4557           ArgOffset += 16;
4558           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4559         }
4560         ++VR_idx;
4561       } else {
4562         if (!isVarArg && !isPPC64) {
4563           // Vectors go after all the nonvectors.
4564           CurArgOffset = VecArgOffset;
4565           VecArgOffset += 16;
4566         } else {
4567           // Vectors are aligned.
4568           ArgOffset = ((ArgOffset+15)/16)*16;
4569           CurArgOffset = ArgOffset;
4570           ArgOffset += 16;
4571         }
4572         needsLoad = true;
4573       }
4574       break;
4575     }
4576 
4577     // We need to load the argument to a virtual register if we determined above
4578     // that we ran out of physical registers of the appropriate type.
4579     if (needsLoad) {
4580       int FI = MFI.CreateFixedObject(ObjSize,
4581                                      CurArgOffset + (ArgSize - ObjSize),
4582                                      isImmutable);
4583       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4584       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4585     }
4586 
4587     InVals.push_back(ArgVal);
4588   }
4589 
4590   // Allow for Altivec parameters at the end, if needed.
4591   if (nAltivecParamsAtEnd) {
4592     MinReservedArea = ((MinReservedArea+15)/16)*16;
4593     MinReservedArea += 16*nAltivecParamsAtEnd;
4594   }
4595 
4596   // Area that is at least reserved in the caller of this function.
4597   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4598 
4599   // Set the size that is at least reserved in caller of this function.  Tail
4600   // call optimized functions' reserved stack space needs to be aligned so that
4601   // taking the difference between two stack areas will result in an aligned
4602   // stack.
4603   MinReservedArea =
4604       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4605   FuncInfo->setMinReservedArea(MinReservedArea);
4606 
4607   // If the function takes variable number of arguments, make a frame index for
4608   // the start of the first vararg value... for expansion of llvm.va_start.
4609   if (isVarArg) {
4610     int Depth = ArgOffset;
4611 
4612     FuncInfo->setVarArgsFrameIndex(
4613       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4614                             Depth, true));
4615     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4616 
4617     // If this function is vararg, store any remaining integer argument regs
4618     // to their spots on the stack so that they may be loaded by dereferencing
4619     // the result of va_next.
4620     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4621       unsigned VReg;
4622 
4623       if (isPPC64)
4624         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4625       else
4626         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4627 
4628       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4629       SDValue Store =
4630           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4631       MemOps.push_back(Store);
4632       // Increment the address by four for the next argument to store
4633       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4634       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4635     }
4636   }
4637 
4638   if (!MemOps.empty())
4639     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4640 
4641   return Chain;
4642 }
4643 
4644 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4645 /// adjusted to accommodate the arguments for the tailcall.
4646 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4647                                    unsigned ParamSize) {
4648 
4649   if (!isTailCall) return 0;
4650 
4651   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4652   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4653   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4654   // Remember only if the new adjustment is bigger.
4655   if (SPDiff < FI->getTailCallSPDelta())
4656     FI->setTailCallSPDelta(SPDiff);
4657 
4658   return SPDiff;
4659 }
4660 
4661 static bool isFunctionGlobalAddress(SDValue Callee);
4662 
4663 static bool
4664 callsShareTOCBase(const Function *Caller, SDValue Callee,
4665                     const TargetMachine &TM) {
4666    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4667    // don't have enough information to determine if the caller and calle share
4668    // the same  TOC base, so we have to pessimistically assume they don't for
4669    // correctness.
4670    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4671    if (!G)
4672      return false;
4673 
4674    const GlobalValue *GV = G->getGlobal();
4675   // The medium and large code models are expected to provide a sufficiently
4676   // large TOC to provide all data addressing needs of a module with a
4677   // single TOC. Since each module will be addressed with a single TOC then we
4678   // only need to check that caller and callee don't cross dso boundaries.
4679   if (CodeModel::Medium == TM.getCodeModel() ||
4680       CodeModel::Large == TM.getCodeModel())
4681     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4682 
4683   // Otherwise we need to ensure callee and caller are in the same section,
4684   // since the linker may allocate multiple TOCs, and we don't know which
4685   // sections will belong to the same TOC base.
4686 
4687   if (!GV->isStrongDefinitionForLinker())
4688     return false;
4689 
4690   // Any explicitly-specified sections and section prefixes must also match.
4691   // Also, if we're using -ffunction-sections, then each function is always in
4692   // a different section (the same is true for COMDAT functions).
4693   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4694       GV->getSection() != Caller->getSection())
4695     return false;
4696   if (const auto *F = dyn_cast<Function>(GV)) {
4697     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4698       return false;
4699   }
4700 
4701   // If the callee might be interposed, then we can't assume the ultimate call
4702   // target will be in the same section. Even in cases where we can assume that
4703   // interposition won't happen, in any case where the linker might insert a
4704   // stub to allow for interposition, we must generate code as though
4705   // interposition might occur. To understand why this matters, consider a
4706   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4707   // in the same section, but a is in a different module (i.e. has a different
4708   // TOC base pointer). If the linker allows for interposition between b and c,
4709   // then it will generate a stub for the call edge between b and c which will
4710   // save the TOC pointer into the designated stack slot allocated by b. If we
4711   // return true here, and therefore allow a tail call between b and c, that
4712   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4713   // pointer into the stack slot allocated by a (where the a -> b stub saved
4714   // a's TOC base pointer). If we're not considering a tail call, but rather,
4715   // whether a nop is needed after the call instruction in b, because the linker
4716   // will insert a stub, it might complain about a missing nop if we omit it
4717   // (although many don't complain in this case).
4718   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4719     return false;
4720 
4721   return true;
4722 }
4723 
4724 static bool
4725 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4726                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4727   assert(Subtarget.is64BitELFABI());
4728 
4729   const unsigned PtrByteSize = 8;
4730   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4731 
4732   static const MCPhysReg GPR[] = {
4733     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4734     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4735   };
4736   static const MCPhysReg VR[] = {
4737     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4738     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4739   };
4740 
4741   const unsigned NumGPRs = array_lengthof(GPR);
4742   const unsigned NumFPRs = 13;
4743   const unsigned NumVRs = array_lengthof(VR);
4744   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4745 
4746   unsigned NumBytes = LinkageSize;
4747   unsigned AvailableFPRs = NumFPRs;
4748   unsigned AvailableVRs = NumVRs;
4749 
4750   for (const ISD::OutputArg& Param : Outs) {
4751     if (Param.Flags.isNest()) continue;
4752 
4753     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4754                                PtrByteSize, LinkageSize, ParamAreaSize,
4755                                NumBytes, AvailableFPRs, AvailableVRs,
4756                                Subtarget.hasQPX()))
4757       return true;
4758   }
4759   return false;
4760 }
4761 
4762 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4763   if (CB.arg_size() != CallerFn->arg_size())
4764     return false;
4765 
4766   auto CalleeArgIter = CB.arg_begin();
4767   auto CalleeArgEnd = CB.arg_end();
4768   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4769 
4770   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4771     const Value* CalleeArg = *CalleeArgIter;
4772     const Value* CallerArg = &(*CallerArgIter);
4773     if (CalleeArg == CallerArg)
4774       continue;
4775 
4776     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4777     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4778     //      }
4779     // 1st argument of callee is undef and has the same type as caller.
4780     if (CalleeArg->getType() == CallerArg->getType() &&
4781         isa<UndefValue>(CalleeArg))
4782       continue;
4783 
4784     return false;
4785   }
4786 
4787   return true;
4788 }
4789 
4790 // Returns true if TCO is possible between the callers and callees
4791 // calling conventions.
4792 static bool
4793 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4794                                     CallingConv::ID CalleeCC) {
4795   // Tail calls are possible with fastcc and ccc.
4796   auto isTailCallableCC  = [] (CallingConv::ID CC){
4797       return  CC == CallingConv::C || CC == CallingConv::Fast;
4798   };
4799   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4800     return false;
4801 
4802   // We can safely tail call both fastcc and ccc callees from a c calling
4803   // convention caller. If the caller is fastcc, we may have less stack space
4804   // than a non-fastcc caller with the same signature so disable tail-calls in
4805   // that case.
4806   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4807 }
4808 
4809 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4810     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4811     const SmallVectorImpl<ISD::OutputArg> &Outs,
4812     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4813   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4814 
4815   if (DisableSCO && !TailCallOpt) return false;
4816 
4817   // Variadic argument functions are not supported.
4818   if (isVarArg) return false;
4819 
4820   auto &Caller = DAG.getMachineFunction().getFunction();
4821   // Check that the calling conventions are compatible for tco.
4822   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4823     return false;
4824 
4825   // Caller contains any byval parameter is not supported.
4826   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4827     return false;
4828 
4829   // Callee contains any byval parameter is not supported, too.
4830   // Note: This is a quick work around, because in some cases, e.g.
4831   // caller's stack size > callee's stack size, we are still able to apply
4832   // sibling call optimization. For example, gcc is able to do SCO for caller1
4833   // in the following example, but not for caller2.
4834   //   struct test {
4835   //     long int a;
4836   //     char ary[56];
4837   //   } gTest;
4838   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4839   //     b->a = v.a;
4840   //     return 0;
4841   //   }
4842   //   void caller1(struct test a, struct test c, struct test *b) {
4843   //     callee(gTest, b); }
4844   //   void caller2(struct test *b) { callee(gTest, b); }
4845   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4846     return false;
4847 
4848   // If callee and caller use different calling conventions, we cannot pass
4849   // parameters on stack since offsets for the parameter area may be different.
4850   if (Caller.getCallingConv() != CalleeCC &&
4851       needStackSlotPassParameters(Subtarget, Outs))
4852     return false;
4853 
4854   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4855   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4856   // callee potentially have different TOC bases then we cannot tail call since
4857   // we need to restore the TOC pointer after the call.
4858   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4859   // We cannot guarantee this for indirect calls or calls to external functions.
4860   // When PC-Relative addressing is used, the concept of the TOC is no longer
4861   // applicable so this check is not required.
4862   // Check first for indirect calls.
4863   if (!Subtarget.isUsingPCRelativeCalls() &&
4864       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4865     return false;
4866 
4867   // Check if we share the TOC base.
4868   if (!Subtarget.isUsingPCRelativeCalls() &&
4869       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4870     return false;
4871 
4872   // TCO allows altering callee ABI, so we don't have to check further.
4873   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4874     return true;
4875 
4876   if (DisableSCO) return false;
4877 
4878   // If callee use the same argument list that caller is using, then we can
4879   // apply SCO on this case. If it is not, then we need to check if callee needs
4880   // stack for passing arguments.
4881   // PC Relative tail calls may not have a CallBase.
4882   // If there is no CallBase we cannot verify if we have the same argument
4883   // list so assume that we don't have the same argument list.
4884   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4885       needStackSlotPassParameters(Subtarget, Outs))
4886     return false;
4887   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4888     return false;
4889 
4890   return true;
4891 }
4892 
4893 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4894 /// for tail call optimization. Targets which want to do tail call
4895 /// optimization should implement this function.
4896 bool
4897 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4898                                                      CallingConv::ID CalleeCC,
4899                                                      bool isVarArg,
4900                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4901                                                      SelectionDAG& DAG) const {
4902   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4903     return false;
4904 
4905   // Variable argument functions are not supported.
4906   if (isVarArg)
4907     return false;
4908 
4909   MachineFunction &MF = DAG.getMachineFunction();
4910   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4911   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4912     // Functions containing by val parameters are not supported.
4913     for (unsigned i = 0; i != Ins.size(); i++) {
4914        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4915        if (Flags.isByVal()) return false;
4916     }
4917 
4918     // Non-PIC/GOT tail calls are supported.
4919     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4920       return true;
4921 
4922     // At the moment we can only do local tail calls (in same module, hidden
4923     // or protected) if we are generating PIC.
4924     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4925       return G->getGlobal()->hasHiddenVisibility()
4926           || G->getGlobal()->hasProtectedVisibility();
4927   }
4928 
4929   return false;
4930 }
4931 
4932 /// isCallCompatibleAddress - Return the immediate to use if the specified
4933 /// 32-bit value is representable in the immediate field of a BxA instruction.
4934 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4935   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4936   if (!C) return nullptr;
4937 
4938   int Addr = C->getZExtValue();
4939   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4940       SignExtend32<26>(Addr) != Addr)
4941     return nullptr;  // Top 6 bits have to be sext of immediate.
4942 
4943   return DAG
4944       .getConstant(
4945           (int)C->getZExtValue() >> 2, SDLoc(Op),
4946           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4947       .getNode();
4948 }
4949 
4950 namespace {
4951 
4952 struct TailCallArgumentInfo {
4953   SDValue Arg;
4954   SDValue FrameIdxOp;
4955   int FrameIdx = 0;
4956 
4957   TailCallArgumentInfo() = default;
4958 };
4959 
4960 } // end anonymous namespace
4961 
4962 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4963 static void StoreTailCallArgumentsToStackSlot(
4964     SelectionDAG &DAG, SDValue Chain,
4965     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4966     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4967   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4968     SDValue Arg = TailCallArgs[i].Arg;
4969     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4970     int FI = TailCallArgs[i].FrameIdx;
4971     // Store relative to framepointer.
4972     MemOpChains.push_back(DAG.getStore(
4973         Chain, dl, Arg, FIN,
4974         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4975   }
4976 }
4977 
4978 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4979 /// the appropriate stack slot for the tail call optimized function call.
4980 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4981                                              SDValue OldRetAddr, SDValue OldFP,
4982                                              int SPDiff, const SDLoc &dl) {
4983   if (SPDiff) {
4984     // Calculate the new stack slot for the return address.
4985     MachineFunction &MF = DAG.getMachineFunction();
4986     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4987     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4988     bool isPPC64 = Subtarget.isPPC64();
4989     int SlotSize = isPPC64 ? 8 : 4;
4990     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4991     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4992                                                          NewRetAddrLoc, true);
4993     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4994     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4995     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4996                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4997   }
4998   return Chain;
4999 }
5000 
5001 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5002 /// the position of the argument.
5003 static void
5004 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5005                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5006                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5007   int Offset = ArgOffset + SPDiff;
5008   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5009   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5010   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5011   SDValue FIN = DAG.getFrameIndex(FI, VT);
5012   TailCallArgumentInfo Info;
5013   Info.Arg = Arg;
5014   Info.FrameIdxOp = FIN;
5015   Info.FrameIdx = FI;
5016   TailCallArguments.push_back(Info);
5017 }
5018 
5019 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5020 /// stack slot. Returns the chain as result and the loaded frame pointers in
5021 /// LROpOut/FPOpout. Used when tail calling.
5022 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5023     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5024     SDValue &FPOpOut, const SDLoc &dl) const {
5025   if (SPDiff) {
5026     // Load the LR and FP stack slot for later adjusting.
5027     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5028     LROpOut = getReturnAddrFrameIndex(DAG);
5029     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5030     Chain = SDValue(LROpOut.getNode(), 1);
5031   }
5032   return Chain;
5033 }
5034 
5035 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5036 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5037 /// specified by the specific parameter attribute. The copy will be passed as
5038 /// a byval function parameter.
5039 /// Sometimes what we are copying is the end of a larger object, the part that
5040 /// does not fit in registers.
5041 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5042                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5043                                          SelectionDAG &DAG, const SDLoc &dl) {
5044   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5045   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5046                        Flags.getNonZeroByValAlign(), false, false, false,
5047                        MachinePointerInfo(), MachinePointerInfo());
5048 }
5049 
5050 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5051 /// tail calls.
5052 static void LowerMemOpCallTo(
5053     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5054     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5055     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5056     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5057   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5058   if (!isTailCall) {
5059     if (isVector) {
5060       SDValue StackPtr;
5061       if (isPPC64)
5062         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5063       else
5064         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5065       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5066                            DAG.getConstant(ArgOffset, dl, PtrVT));
5067     }
5068     MemOpChains.push_back(
5069         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5070     // Calculate and remember argument location.
5071   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5072                                   TailCallArguments);
5073 }
5074 
5075 static void
5076 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5077                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5078                 SDValue FPOp,
5079                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5080   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5081   // might overwrite each other in case of tail call optimization.
5082   SmallVector<SDValue, 8> MemOpChains2;
5083   // Do not flag preceding copytoreg stuff together with the following stuff.
5084   InFlag = SDValue();
5085   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5086                                     MemOpChains2, dl);
5087   if (!MemOpChains2.empty())
5088     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5089 
5090   // Store the return address to the appropriate stack slot.
5091   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5092 
5093   // Emit callseq_end just before tailcall node.
5094   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5095                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5096   InFlag = Chain.getValue(1);
5097 }
5098 
5099 // Is this global address that of a function that can be called by name? (as
5100 // opposed to something that must hold a descriptor for an indirect call).
5101 static bool isFunctionGlobalAddress(SDValue Callee) {
5102   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5103     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5104         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5105       return false;
5106 
5107     return G->getGlobal()->getValueType()->isFunctionTy();
5108   }
5109 
5110   return false;
5111 }
5112 
5113 SDValue PPCTargetLowering::LowerCallResult(
5114     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5115     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5116     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5117   SmallVector<CCValAssign, 16> RVLocs;
5118   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5119                     *DAG.getContext());
5120 
5121   CCRetInfo.AnalyzeCallResult(
5122       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5123                ? RetCC_PPC_Cold
5124                : RetCC_PPC);
5125 
5126   // Copy all of the result registers out of their specified physreg.
5127   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5128     CCValAssign &VA = RVLocs[i];
5129     assert(VA.isRegLoc() && "Can only return in registers!");
5130 
5131     SDValue Val;
5132 
5133     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5134       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5135                                       InFlag);
5136       Chain = Lo.getValue(1);
5137       InFlag = Lo.getValue(2);
5138       VA = RVLocs[++i]; // skip ahead to next loc
5139       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5140                                       InFlag);
5141       Chain = Hi.getValue(1);
5142       InFlag = Hi.getValue(2);
5143       if (!Subtarget.isLittleEndian())
5144         std::swap (Lo, Hi);
5145       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5146     } else {
5147       Val = DAG.getCopyFromReg(Chain, dl,
5148                                VA.getLocReg(), VA.getLocVT(), InFlag);
5149       Chain = Val.getValue(1);
5150       InFlag = Val.getValue(2);
5151     }
5152 
5153     switch (VA.getLocInfo()) {
5154     default: llvm_unreachable("Unknown loc info!");
5155     case CCValAssign::Full: break;
5156     case CCValAssign::AExt:
5157       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5158       break;
5159     case CCValAssign::ZExt:
5160       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5161                         DAG.getValueType(VA.getValVT()));
5162       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5163       break;
5164     case CCValAssign::SExt:
5165       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5166                         DAG.getValueType(VA.getValVT()));
5167       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5168       break;
5169     }
5170 
5171     InVals.push_back(Val);
5172   }
5173 
5174   return Chain;
5175 }
5176 
5177 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5178                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5179   // PatchPoint calls are not indirect.
5180   if (isPatchPoint)
5181     return false;
5182 
5183   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5184     return false;
5185 
5186   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5187   // becuase the immediate function pointer points to a descriptor instead of
5188   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5189   // pointer immediate points to the global entry point, while the BLA would
5190   // need to jump to the local entry point (see rL211174).
5191   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5192       isBLACompatibleAddress(Callee, DAG))
5193     return false;
5194 
5195   return true;
5196 }
5197 
5198 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5199 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5200   return Subtarget.isAIXABI() ||
5201          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5202 }
5203 
5204 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5205                               const Function &Caller,
5206                               const SDValue &Callee,
5207                               const PPCSubtarget &Subtarget,
5208                               const TargetMachine &TM) {
5209   if (CFlags.IsTailCall)
5210     return PPCISD::TC_RETURN;
5211 
5212   // This is a call through a function pointer.
5213   if (CFlags.IsIndirect) {
5214     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5215     // indirect calls. The save of the caller's TOC pointer to the stack will be
5216     // inserted into the DAG as part of call lowering. The restore of the TOC
5217     // pointer is modeled by using a pseudo instruction for the call opcode that
5218     // represents the 2 instruction sequence of an indirect branch and link,
5219     // immediately followed by a load of the TOC pointer from the the stack save
5220     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5221     // as it is not saved or used.
5222     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5223                                                : PPCISD::BCTRL;
5224   }
5225 
5226   if (Subtarget.isUsingPCRelativeCalls()) {
5227     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5228     return PPCISD::CALL_NOTOC;
5229   }
5230 
5231   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5232   // immediately following the call instruction if the caller and callee may
5233   // have different TOC bases. At link time if the linker determines the calls
5234   // may not share a TOC base, the call is redirected to a trampoline inserted
5235   // by the linker. The trampoline will (among other things) save the callers
5236   // TOC pointer at an ABI designated offset in the linkage area and the linker
5237   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5238   // into gpr2.
5239   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5240       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5241                                                     : PPCISD::CALL_NOP;
5242 
5243   return PPCISD::CALL;
5244 }
5245 
5246 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5247                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5248   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5249     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5250       return SDValue(Dest, 0);
5251 
5252   // Returns true if the callee is local, and false otherwise.
5253   auto isLocalCallee = [&]() {
5254     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5255     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5256     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5257 
5258     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5259            !dyn_cast_or_null<GlobalIFunc>(GV);
5260   };
5261 
5262   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5263   // a static relocation model causes some versions of GNU LD (2.17.50, at
5264   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5265   // built with secure-PLT.
5266   bool UsePlt =
5267       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5268       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5269 
5270   // On AIX, direct function calls reference the symbol for the function's
5271   // entry point, which is named by prepending a "." before the function's
5272   // C-linkage name.
5273   const auto getAIXFuncEntryPointSymbolSDNode =
5274       [&](StringRef FuncName, bool IsDeclaration,
5275           const XCOFF::StorageClass &SC) {
5276         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5277 
5278         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5279             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5280 
5281         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5282           // On AIX, an undefined symbol needs to be associated with a
5283           // MCSectionXCOFF to get the correct storage mapping class.
5284           // In this case, XCOFF::XMC_PR.
5285           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5286               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5287               SectionKind::getMetadata());
5288           S->setRepresentedCsect(Sec);
5289         }
5290 
5291         MVT PtrVT =
5292             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5293         return DAG.getMCSymbol(S, PtrVT);
5294       };
5295 
5296   if (isFunctionGlobalAddress(Callee)) {
5297     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5298     const GlobalValue *GV = G->getGlobal();
5299 
5300     if (!Subtarget.isAIXABI())
5301       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5302                                         UsePlt ? PPCII::MO_PLT : 0);
5303 
5304     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5305     const GlobalObject *GO = cast<GlobalObject>(GV);
5306     const XCOFF::StorageClass SC =
5307         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5308     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5309                                             SC);
5310   }
5311 
5312   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5313     const char *SymName = S->getSymbol();
5314     if (!Subtarget.isAIXABI())
5315       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5316                                          UsePlt ? PPCII::MO_PLT : 0);
5317 
5318     // If there exists a user-declared function whose name is the same as the
5319     // ExternalSymbol's, then we pick up the user-declared version.
5320     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5321     if (const Function *F =
5322             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5323       const XCOFF::StorageClass SC =
5324           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5325       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5326                                               SC);
5327     }
5328 
5329     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5330   }
5331 
5332   // No transformation needed.
5333   assert(Callee.getNode() && "What no callee?");
5334   return Callee;
5335 }
5336 
5337 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5338   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5339          "Expected a CALLSEQ_STARTSDNode.");
5340 
5341   // The last operand is the chain, except when the node has glue. If the node
5342   // has glue, then the last operand is the glue, and the chain is the second
5343   // last operand.
5344   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5345   if (LastValue.getValueType() != MVT::Glue)
5346     return LastValue;
5347 
5348   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5349 }
5350 
5351 // Creates the node that moves a functions address into the count register
5352 // to prepare for an indirect call instruction.
5353 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5354                                 SDValue &Glue, SDValue &Chain,
5355                                 const SDLoc &dl) {
5356   SDValue MTCTROps[] = {Chain, Callee, Glue};
5357   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5358   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5359                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5360   // The glue is the second value produced.
5361   Glue = Chain.getValue(1);
5362 }
5363 
5364 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5365                                           SDValue &Glue, SDValue &Chain,
5366                                           SDValue CallSeqStart,
5367                                           const CallBase *CB, const SDLoc &dl,
5368                                           bool hasNest,
5369                                           const PPCSubtarget &Subtarget) {
5370   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5371   // entry point, but to the function descriptor (the function entry point
5372   // address is part of the function descriptor though).
5373   // The function descriptor is a three doubleword structure with the
5374   // following fields: function entry point, TOC base address and
5375   // environment pointer.
5376   // Thus for a call through a function pointer, the following actions need
5377   // to be performed:
5378   //   1. Save the TOC of the caller in the TOC save area of its stack
5379   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5380   //   2. Load the address of the function entry point from the function
5381   //      descriptor.
5382   //   3. Load the TOC of the callee from the function descriptor into r2.
5383   //   4. Load the environment pointer from the function descriptor into
5384   //      r11.
5385   //   5. Branch to the function entry point address.
5386   //   6. On return of the callee, the TOC of the caller needs to be
5387   //      restored (this is done in FinishCall()).
5388   //
5389   // The loads are scheduled at the beginning of the call sequence, and the
5390   // register copies are flagged together to ensure that no other
5391   // operations can be scheduled in between. E.g. without flagging the
5392   // copies together, a TOC access in the caller could be scheduled between
5393   // the assignment of the callee TOC and the branch to the callee, which leads
5394   // to incorrect code.
5395 
5396   // Start by loading the function address from the descriptor.
5397   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5398   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5399                       ? (MachineMemOperand::MODereferenceable |
5400                          MachineMemOperand::MOInvariant)
5401                       : MachineMemOperand::MONone;
5402 
5403   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5404 
5405   // Registers used in building the DAG.
5406   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5407   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5408 
5409   // Offsets of descriptor members.
5410   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5411   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5412 
5413   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5414   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5415 
5416   // One load for the functions entry point address.
5417   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5418                                     Alignment, MMOFlags);
5419 
5420   // One for loading the TOC anchor for the module that contains the called
5421   // function.
5422   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5423   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5424   SDValue TOCPtr =
5425       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5426                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5427 
5428   // One for loading the environment pointer.
5429   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5430   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5431   SDValue LoadEnvPtr =
5432       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5433                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5434 
5435 
5436   // Then copy the newly loaded TOC anchor to the TOC pointer.
5437   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5438   Chain = TOCVal.getValue(0);
5439   Glue = TOCVal.getValue(1);
5440 
5441   // If the function call has an explicit 'nest' parameter, it takes the
5442   // place of the environment pointer.
5443   assert((!hasNest || !Subtarget.isAIXABI()) &&
5444          "Nest parameter is not supported on AIX.");
5445   if (!hasNest) {
5446     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5447     Chain = EnvVal.getValue(0);
5448     Glue = EnvVal.getValue(1);
5449   }
5450 
5451   // The rest of the indirect call sequence is the same as the non-descriptor
5452   // DAG.
5453   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5454 }
5455 
5456 static void
5457 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5458                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5459                   SelectionDAG &DAG,
5460                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5461                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5462                   const PPCSubtarget &Subtarget) {
5463   const bool IsPPC64 = Subtarget.isPPC64();
5464   // MVT for a general purpose register.
5465   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5466 
5467   // First operand is always the chain.
5468   Ops.push_back(Chain);
5469 
5470   // If it's a direct call pass the callee as the second operand.
5471   if (!CFlags.IsIndirect)
5472     Ops.push_back(Callee);
5473   else {
5474     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5475 
5476     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5477     // on the stack (this would have been done in `LowerCall_64SVR4` or
5478     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5479     // represents both the indirect branch and a load that restores the TOC
5480     // pointer from the linkage area. The operand for the TOC restore is an add
5481     // of the TOC save offset to the stack pointer. This must be the second
5482     // operand: after the chain input but before any other variadic arguments.
5483     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5484     // saved or used.
5485     if (isTOCSaveRestoreRequired(Subtarget)) {
5486       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5487 
5488       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5489       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5490       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5491       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5492       Ops.push_back(AddTOC);
5493     }
5494 
5495     // Add the register used for the environment pointer.
5496     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5497       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5498                                     RegVT));
5499 
5500 
5501     // Add CTR register as callee so a bctr can be emitted later.
5502     if (CFlags.IsTailCall)
5503       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5504   }
5505 
5506   // If this is a tail call add stack pointer delta.
5507   if (CFlags.IsTailCall)
5508     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5509 
5510   // Add argument registers to the end of the list so that they are known live
5511   // into the call.
5512   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5513     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5514                                   RegsToPass[i].second.getValueType()));
5515 
5516   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5517   // no way to mark dependencies as implicit here.
5518   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5519   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5520        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5521     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5522 
5523   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5524   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5525     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5526 
5527   // Add a register mask operand representing the call-preserved registers.
5528   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5529   const uint32_t *Mask =
5530       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5531   assert(Mask && "Missing call preserved mask for calling convention");
5532   Ops.push_back(DAG.getRegisterMask(Mask));
5533 
5534   // If the glue is valid, it is the last operand.
5535   if (Glue.getNode())
5536     Ops.push_back(Glue);
5537 }
5538 
5539 SDValue PPCTargetLowering::FinishCall(
5540     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5541     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5542     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5543     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5544     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5545 
5546   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5547       Subtarget.isAIXABI())
5548     setUsesTOCBasePtr(DAG);
5549 
5550   unsigned CallOpc =
5551       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5552                     Subtarget, DAG.getTarget());
5553 
5554   if (!CFlags.IsIndirect)
5555     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5556   else if (Subtarget.usesFunctionDescriptors())
5557     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5558                                   dl, CFlags.HasNest, Subtarget);
5559   else
5560     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5561 
5562   // Build the operand list for the call instruction.
5563   SmallVector<SDValue, 8> Ops;
5564   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5565                     SPDiff, Subtarget);
5566 
5567   // Emit tail call.
5568   if (CFlags.IsTailCall) {
5569     // Indirect tail call when using PC Relative calls do not have the same
5570     // constraints.
5571     assert(((Callee.getOpcode() == ISD::Register &&
5572              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5573             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5574             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5575             isa<ConstantSDNode>(Callee) ||
5576             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5577            "Expecting a global address, external symbol, absolute value, "
5578            "register or an indirect tail call when PC Relative calls are "
5579            "used.");
5580     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5581     assert(CallOpc == PPCISD::TC_RETURN &&
5582            "Unexpected call opcode for a tail call.");
5583     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5584     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5585   }
5586 
5587   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5588   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5589   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5590   Glue = Chain.getValue(1);
5591 
5592   // When performing tail call optimization the callee pops its arguments off
5593   // the stack. Account for this here so these bytes can be pushed back on in
5594   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5595   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5596                          getTargetMachine().Options.GuaranteedTailCallOpt)
5597                             ? NumBytes
5598                             : 0;
5599 
5600   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5601                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5602                              Glue, dl);
5603   Glue = Chain.getValue(1);
5604 
5605   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5606                          DAG, InVals);
5607 }
5608 
5609 SDValue
5610 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5611                              SmallVectorImpl<SDValue> &InVals) const {
5612   SelectionDAG &DAG                     = CLI.DAG;
5613   SDLoc &dl                             = CLI.DL;
5614   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5615   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5616   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5617   SDValue Chain                         = CLI.Chain;
5618   SDValue Callee                        = CLI.Callee;
5619   bool &isTailCall                      = CLI.IsTailCall;
5620   CallingConv::ID CallConv              = CLI.CallConv;
5621   bool isVarArg                         = CLI.IsVarArg;
5622   bool isPatchPoint                     = CLI.IsPatchPoint;
5623   const CallBase *CB                    = CLI.CB;
5624 
5625   if (isTailCall) {
5626     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5627       isTailCall = false;
5628     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5629       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5630           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5631     else
5632       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5633                                                      Ins, DAG);
5634     if (isTailCall) {
5635       ++NumTailCalls;
5636       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5637         ++NumSiblingCalls;
5638 
5639       // PC Relative calls no longer guarantee that the callee is a Global
5640       // Address Node. The callee could be an indirect tail call in which
5641       // case the SDValue for the callee could be a load (to load the address
5642       // of a function pointer) or it may be a register copy (to move the
5643       // address of the callee from a function parameter into a virtual
5644       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5645       assert((Subtarget.isUsingPCRelativeCalls() ||
5646               isa<GlobalAddressSDNode>(Callee)) &&
5647              "Callee should be an llvm::Function object.");
5648 
5649       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5650                         << "\nTCO callee: ");
5651       LLVM_DEBUG(Callee.dump());
5652     }
5653   }
5654 
5655   if (!isTailCall && CB && CB->isMustTailCall())
5656     report_fatal_error("failed to perform tail call elimination on a call "
5657                        "site marked musttail");
5658 
5659   // When long calls (i.e. indirect calls) are always used, calls are always
5660   // made via function pointer. If we have a function name, first translate it
5661   // into a pointer.
5662   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5663       !isTailCall)
5664     Callee = LowerGlobalAddress(Callee, DAG);
5665 
5666   CallFlags CFlags(
5667       CallConv, isTailCall, isVarArg, isPatchPoint,
5668       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5669       // hasNest
5670       Subtarget.is64BitELFABI() &&
5671           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5672       CLI.NoMerge);
5673 
5674   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5675     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5676                             InVals, CB);
5677 
5678   if (Subtarget.isSVR4ABI())
5679     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5680                             InVals, CB);
5681 
5682   if (Subtarget.isAIXABI())
5683     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5684                          InVals, CB);
5685 
5686   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5687                           InVals, CB);
5688 }
5689 
5690 SDValue PPCTargetLowering::LowerCall_32SVR4(
5691     SDValue Chain, SDValue Callee, CallFlags CFlags,
5692     const SmallVectorImpl<ISD::OutputArg> &Outs,
5693     const SmallVectorImpl<SDValue> &OutVals,
5694     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5695     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5696     const CallBase *CB) const {
5697   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5698   // of the 32-bit SVR4 ABI stack frame layout.
5699 
5700   const CallingConv::ID CallConv = CFlags.CallConv;
5701   const bool IsVarArg = CFlags.IsVarArg;
5702   const bool IsTailCall = CFlags.IsTailCall;
5703 
5704   assert((CallConv == CallingConv::C ||
5705           CallConv == CallingConv::Cold ||
5706           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5707 
5708   const Align PtrAlign(4);
5709 
5710   MachineFunction &MF = DAG.getMachineFunction();
5711 
5712   // Mark this function as potentially containing a function that contains a
5713   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5714   // and restoring the callers stack pointer in this functions epilog. This is
5715   // done because by tail calling the called function might overwrite the value
5716   // in this function's (MF) stack pointer stack slot 0(SP).
5717   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5718       CallConv == CallingConv::Fast)
5719     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5720 
5721   // Count how many bytes are to be pushed on the stack, including the linkage
5722   // area, parameter list area and the part of the local variable space which
5723   // contains copies of aggregates which are passed by value.
5724 
5725   // Assign locations to all of the outgoing arguments.
5726   SmallVector<CCValAssign, 16> ArgLocs;
5727   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5728 
5729   // Reserve space for the linkage area on the stack.
5730   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5731                        PtrAlign);
5732   if (useSoftFloat())
5733     CCInfo.PreAnalyzeCallOperands(Outs);
5734 
5735   if (IsVarArg) {
5736     // Handle fixed and variable vector arguments differently.
5737     // Fixed vector arguments go into registers as long as registers are
5738     // available. Variable vector arguments always go into memory.
5739     unsigned NumArgs = Outs.size();
5740 
5741     for (unsigned i = 0; i != NumArgs; ++i) {
5742       MVT ArgVT = Outs[i].VT;
5743       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5744       bool Result;
5745 
5746       if (Outs[i].IsFixed) {
5747         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5748                                CCInfo);
5749       } else {
5750         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5751                                       ArgFlags, CCInfo);
5752       }
5753 
5754       if (Result) {
5755 #ifndef NDEBUG
5756         errs() << "Call operand #" << i << " has unhandled type "
5757              << EVT(ArgVT).getEVTString() << "\n";
5758 #endif
5759         llvm_unreachable(nullptr);
5760       }
5761     }
5762   } else {
5763     // All arguments are treated the same.
5764     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5765   }
5766   CCInfo.clearWasPPCF128();
5767 
5768   // Assign locations to all of the outgoing aggregate by value arguments.
5769   SmallVector<CCValAssign, 16> ByValArgLocs;
5770   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5771 
5772   // Reserve stack space for the allocations in CCInfo.
5773   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5774 
5775   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5776 
5777   // Size of the linkage area, parameter list area and the part of the local
5778   // space variable where copies of aggregates which are passed by value are
5779   // stored.
5780   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5781 
5782   // Calculate by how many bytes the stack has to be adjusted in case of tail
5783   // call optimization.
5784   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5785 
5786   // Adjust the stack pointer for the new arguments...
5787   // These operations are automatically eliminated by the prolog/epilog pass
5788   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5789   SDValue CallSeqStart = Chain;
5790 
5791   // Load the return address and frame pointer so it can be moved somewhere else
5792   // later.
5793   SDValue LROp, FPOp;
5794   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5795 
5796   // Set up a copy of the stack pointer for use loading and storing any
5797   // arguments that may not fit in the registers available for argument
5798   // passing.
5799   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5800 
5801   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5802   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5803   SmallVector<SDValue, 8> MemOpChains;
5804 
5805   bool seenFloatArg = false;
5806   // Walk the register/memloc assignments, inserting copies/loads.
5807   // i - Tracks the index into the list of registers allocated for the call
5808   // RealArgIdx - Tracks the index into the list of actual function arguments
5809   // j - Tracks the index into the list of byval arguments
5810   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5811        i != e;
5812        ++i, ++RealArgIdx) {
5813     CCValAssign &VA = ArgLocs[i];
5814     SDValue Arg = OutVals[RealArgIdx];
5815     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5816 
5817     if (Flags.isByVal()) {
5818       // Argument is an aggregate which is passed by value, thus we need to
5819       // create a copy of it in the local variable space of the current stack
5820       // frame (which is the stack frame of the caller) and pass the address of
5821       // this copy to the callee.
5822       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5823       CCValAssign &ByValVA = ByValArgLocs[j++];
5824       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5825 
5826       // Memory reserved in the local variable space of the callers stack frame.
5827       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5828 
5829       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5830       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5831                            StackPtr, PtrOff);
5832 
5833       // Create a copy of the argument in the local area of the current
5834       // stack frame.
5835       SDValue MemcpyCall =
5836         CreateCopyOfByValArgument(Arg, PtrOff,
5837                                   CallSeqStart.getNode()->getOperand(0),
5838                                   Flags, DAG, dl);
5839 
5840       // This must go outside the CALLSEQ_START..END.
5841       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5842                                                      SDLoc(MemcpyCall));
5843       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5844                              NewCallSeqStart.getNode());
5845       Chain = CallSeqStart = NewCallSeqStart;
5846 
5847       // Pass the address of the aggregate copy on the stack either in a
5848       // physical register or in the parameter list area of the current stack
5849       // frame to the callee.
5850       Arg = PtrOff;
5851     }
5852 
5853     // When useCRBits() is true, there can be i1 arguments.
5854     // It is because getRegisterType(MVT::i1) => MVT::i1,
5855     // and for other integer types getRegisterType() => MVT::i32.
5856     // Extend i1 and ensure callee will get i32.
5857     if (Arg.getValueType() == MVT::i1)
5858       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5859                         dl, MVT::i32, Arg);
5860 
5861     if (VA.isRegLoc()) {
5862       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5863       // Put argument in a physical register.
5864       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5865         bool IsLE = Subtarget.isLittleEndian();
5866         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5867                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5868         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5869         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5870                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5871         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5872                              SVal.getValue(0)));
5873       } else
5874         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5875     } else {
5876       // Put argument in the parameter list area of the current stack frame.
5877       assert(VA.isMemLoc());
5878       unsigned LocMemOffset = VA.getLocMemOffset();
5879 
5880       if (!IsTailCall) {
5881         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5882         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5883                              StackPtr, PtrOff);
5884 
5885         MemOpChains.push_back(
5886             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5887       } else {
5888         // Calculate and remember argument location.
5889         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5890                                  TailCallArguments);
5891       }
5892     }
5893   }
5894 
5895   if (!MemOpChains.empty())
5896     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5897 
5898   // Build a sequence of copy-to-reg nodes chained together with token chain
5899   // and flag operands which copy the outgoing args into the appropriate regs.
5900   SDValue InFlag;
5901   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5902     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5903                              RegsToPass[i].second, InFlag);
5904     InFlag = Chain.getValue(1);
5905   }
5906 
5907   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5908   // registers.
5909   if (IsVarArg) {
5910     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5911     SDValue Ops[] = { Chain, InFlag };
5912 
5913     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5914                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5915 
5916     InFlag = Chain.getValue(1);
5917   }
5918 
5919   if (IsTailCall)
5920     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5921                     TailCallArguments);
5922 
5923   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5924                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5925 }
5926 
5927 // Copy an argument into memory, being careful to do this outside the
5928 // call sequence for the call to which the argument belongs.
5929 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5930     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5931     SelectionDAG &DAG, const SDLoc &dl) const {
5932   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5933                         CallSeqStart.getNode()->getOperand(0),
5934                         Flags, DAG, dl);
5935   // The MEMCPY must go outside the CALLSEQ_START..END.
5936   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5937   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5938                                                  SDLoc(MemcpyCall));
5939   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5940                          NewCallSeqStart.getNode());
5941   return NewCallSeqStart;
5942 }
5943 
5944 SDValue PPCTargetLowering::LowerCall_64SVR4(
5945     SDValue Chain, SDValue Callee, CallFlags CFlags,
5946     const SmallVectorImpl<ISD::OutputArg> &Outs,
5947     const SmallVectorImpl<SDValue> &OutVals,
5948     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5949     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5950     const CallBase *CB) const {
5951   bool isELFv2ABI = Subtarget.isELFv2ABI();
5952   bool isLittleEndian = Subtarget.isLittleEndian();
5953   unsigned NumOps = Outs.size();
5954   bool IsSibCall = false;
5955   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5956 
5957   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5958   unsigned PtrByteSize = 8;
5959 
5960   MachineFunction &MF = DAG.getMachineFunction();
5961 
5962   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5963     IsSibCall = true;
5964 
5965   // Mark this function as potentially containing a function that contains a
5966   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5967   // and restoring the callers stack pointer in this functions epilog. This is
5968   // done because by tail calling the called function might overwrite the value
5969   // in this function's (MF) stack pointer stack slot 0(SP).
5970   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5971     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5972 
5973   assert(!(IsFastCall && CFlags.IsVarArg) &&
5974          "fastcc not supported on varargs functions");
5975 
5976   // Count how many bytes are to be pushed on the stack, including the linkage
5977   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5978   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5979   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5980   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5981   unsigned NumBytes = LinkageSize;
5982   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5983   unsigned &QFPR_idx = FPR_idx;
5984 
5985   static const MCPhysReg GPR[] = {
5986     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5987     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5988   };
5989   static const MCPhysReg VR[] = {
5990     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5991     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5992   };
5993 
5994   const unsigned NumGPRs = array_lengthof(GPR);
5995   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5996   const unsigned NumVRs  = array_lengthof(VR);
5997   const unsigned NumQFPRs = NumFPRs;
5998 
5999   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6000   // can be passed to the callee in registers.
6001   // For the fast calling convention, there is another check below.
6002   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6003   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6004   if (!HasParameterArea) {
6005     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6006     unsigned AvailableFPRs = NumFPRs;
6007     unsigned AvailableVRs = NumVRs;
6008     unsigned NumBytesTmp = NumBytes;
6009     for (unsigned i = 0; i != NumOps; ++i) {
6010       if (Outs[i].Flags.isNest()) continue;
6011       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6012                                 PtrByteSize, LinkageSize, ParamAreaSize,
6013                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
6014                                 Subtarget.hasQPX()))
6015         HasParameterArea = true;
6016     }
6017   }
6018 
6019   // When using the fast calling convention, we don't provide backing for
6020   // arguments that will be in registers.
6021   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6022 
6023   // Avoid allocating parameter area for fastcc functions if all the arguments
6024   // can be passed in the registers.
6025   if (IsFastCall)
6026     HasParameterArea = false;
6027 
6028   // Add up all the space actually used.
6029   for (unsigned i = 0; i != NumOps; ++i) {
6030     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6031     EVT ArgVT = Outs[i].VT;
6032     EVT OrigVT = Outs[i].ArgVT;
6033 
6034     if (Flags.isNest())
6035       continue;
6036 
6037     if (IsFastCall) {
6038       if (Flags.isByVal()) {
6039         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6040         if (NumGPRsUsed > NumGPRs)
6041           HasParameterArea = true;
6042       } else {
6043         switch (ArgVT.getSimpleVT().SimpleTy) {
6044         default: llvm_unreachable("Unexpected ValueType for argument!");
6045         case MVT::i1:
6046         case MVT::i32:
6047         case MVT::i64:
6048           if (++NumGPRsUsed <= NumGPRs)
6049             continue;
6050           break;
6051         case MVT::v4i32:
6052         case MVT::v8i16:
6053         case MVT::v16i8:
6054         case MVT::v2f64:
6055         case MVT::v2i64:
6056         case MVT::v1i128:
6057         case MVT::f128:
6058           if (++NumVRsUsed <= NumVRs)
6059             continue;
6060           break;
6061         case MVT::v4f32:
6062           // When using QPX, this is handled like a FP register, otherwise, it
6063           // is an Altivec register.
6064           if (Subtarget.hasQPX()) {
6065             if (++NumFPRsUsed <= NumFPRs)
6066               continue;
6067           } else {
6068             if (++NumVRsUsed <= NumVRs)
6069               continue;
6070           }
6071           break;
6072         case MVT::f32:
6073         case MVT::f64:
6074         case MVT::v4f64: // QPX
6075         case MVT::v4i1:  // QPX
6076           if (++NumFPRsUsed <= NumFPRs)
6077             continue;
6078           break;
6079         }
6080         HasParameterArea = true;
6081       }
6082     }
6083 
6084     /* Respect alignment of argument on the stack.  */
6085     auto Alignement =
6086         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6087     NumBytes = alignTo(NumBytes, Alignement);
6088 
6089     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6090     if (Flags.isInConsecutiveRegsLast())
6091       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6092   }
6093 
6094   unsigned NumBytesActuallyUsed = NumBytes;
6095 
6096   // In the old ELFv1 ABI,
6097   // the prolog code of the callee may store up to 8 GPR argument registers to
6098   // the stack, allowing va_start to index over them in memory if its varargs.
6099   // Because we cannot tell if this is needed on the caller side, we have to
6100   // conservatively assume that it is needed.  As such, make sure we have at
6101   // least enough stack space for the caller to store the 8 GPRs.
6102   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6103   // really requires memory operands, e.g. a vararg function.
6104   if (HasParameterArea)
6105     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6106   else
6107     NumBytes = LinkageSize;
6108 
6109   // Tail call needs the stack to be aligned.
6110   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6111     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6112 
6113   int SPDiff = 0;
6114 
6115   // Calculate by how many bytes the stack has to be adjusted in case of tail
6116   // call optimization.
6117   if (!IsSibCall)
6118     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6119 
6120   // To protect arguments on the stack from being clobbered in a tail call,
6121   // force all the loads to happen before doing any other lowering.
6122   if (CFlags.IsTailCall)
6123     Chain = DAG.getStackArgumentTokenFactor(Chain);
6124 
6125   // Adjust the stack pointer for the new arguments...
6126   // These operations are automatically eliminated by the prolog/epilog pass
6127   if (!IsSibCall)
6128     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6129   SDValue CallSeqStart = Chain;
6130 
6131   // Load the return address and frame pointer so it can be move somewhere else
6132   // later.
6133   SDValue LROp, FPOp;
6134   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6135 
6136   // Set up a copy of the stack pointer for use loading and storing any
6137   // arguments that may not fit in the registers available for argument
6138   // passing.
6139   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6140 
6141   // Figure out which arguments are going to go in registers, and which in
6142   // memory.  Also, if this is a vararg function, floating point operations
6143   // must be stored to our stack, and loaded into integer regs as well, if
6144   // any integer regs are available for argument passing.
6145   unsigned ArgOffset = LinkageSize;
6146 
6147   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6148   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6149 
6150   SmallVector<SDValue, 8> MemOpChains;
6151   for (unsigned i = 0; i != NumOps; ++i) {
6152     SDValue Arg = OutVals[i];
6153     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6154     EVT ArgVT = Outs[i].VT;
6155     EVT OrigVT = Outs[i].ArgVT;
6156 
6157     // PtrOff will be used to store the current argument to the stack if a
6158     // register cannot be found for it.
6159     SDValue PtrOff;
6160 
6161     // We re-align the argument offset for each argument, except when using the
6162     // fast calling convention, when we need to make sure we do that only when
6163     // we'll actually use a stack slot.
6164     auto ComputePtrOff = [&]() {
6165       /* Respect alignment of argument on the stack.  */
6166       auto Alignment =
6167           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6168       ArgOffset = alignTo(ArgOffset, Alignment);
6169 
6170       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6171 
6172       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6173     };
6174 
6175     if (!IsFastCall) {
6176       ComputePtrOff();
6177 
6178       /* Compute GPR index associated with argument offset.  */
6179       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6180       GPR_idx = std::min(GPR_idx, NumGPRs);
6181     }
6182 
6183     // Promote integers to 64-bit values.
6184     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6185       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6186       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6187       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6188     }
6189 
6190     // FIXME memcpy is used way more than necessary.  Correctness first.
6191     // Note: "by value" is code for passing a structure by value, not
6192     // basic types.
6193     if (Flags.isByVal()) {
6194       // Note: Size includes alignment padding, so
6195       //   struct x { short a; char b; }
6196       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6197       // These are the proper values we need for right-justifying the
6198       // aggregate in a parameter register.
6199       unsigned Size = Flags.getByValSize();
6200 
6201       // An empty aggregate parameter takes up no storage and no
6202       // registers.
6203       if (Size == 0)
6204         continue;
6205 
6206       if (IsFastCall)
6207         ComputePtrOff();
6208 
6209       // All aggregates smaller than 8 bytes must be passed right-justified.
6210       if (Size==1 || Size==2 || Size==4) {
6211         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6212         if (GPR_idx != NumGPRs) {
6213           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6214                                         MachinePointerInfo(), VT);
6215           MemOpChains.push_back(Load.getValue(1));
6216           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6217 
6218           ArgOffset += PtrByteSize;
6219           continue;
6220         }
6221       }
6222 
6223       if (GPR_idx == NumGPRs && Size < 8) {
6224         SDValue AddPtr = PtrOff;
6225         if (!isLittleEndian) {
6226           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6227                                           PtrOff.getValueType());
6228           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6229         }
6230         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6231                                                           CallSeqStart,
6232                                                           Flags, DAG, dl);
6233         ArgOffset += PtrByteSize;
6234         continue;
6235       }
6236       // Copy entire object into memory.  There are cases where gcc-generated
6237       // code assumes it is there, even if it could be put entirely into
6238       // registers.  (This is not what the doc says.)
6239 
6240       // FIXME: The above statement is likely due to a misunderstanding of the
6241       // documents.  All arguments must be copied into the parameter area BY
6242       // THE CALLEE in the event that the callee takes the address of any
6243       // formal argument.  That has not yet been implemented.  However, it is
6244       // reasonable to use the stack area as a staging area for the register
6245       // load.
6246 
6247       // Skip this for small aggregates, as we will use the same slot for a
6248       // right-justified copy, below.
6249       if (Size >= 8)
6250         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6251                                                           CallSeqStart,
6252                                                           Flags, DAG, dl);
6253 
6254       // When a register is available, pass a small aggregate right-justified.
6255       if (Size < 8 && GPR_idx != NumGPRs) {
6256         // The easiest way to get this right-justified in a register
6257         // is to copy the structure into the rightmost portion of a
6258         // local variable slot, then load the whole slot into the
6259         // register.
6260         // FIXME: The memcpy seems to produce pretty awful code for
6261         // small aggregates, particularly for packed ones.
6262         // FIXME: It would be preferable to use the slot in the
6263         // parameter save area instead of a new local variable.
6264         SDValue AddPtr = PtrOff;
6265         if (!isLittleEndian) {
6266           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6267           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6268         }
6269         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6270                                                           CallSeqStart,
6271                                                           Flags, DAG, dl);
6272 
6273         // Load the slot into the register.
6274         SDValue Load =
6275             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6276         MemOpChains.push_back(Load.getValue(1));
6277         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6278 
6279         // Done with this argument.
6280         ArgOffset += PtrByteSize;
6281         continue;
6282       }
6283 
6284       // For aggregates larger than PtrByteSize, copy the pieces of the
6285       // object that fit into registers from the parameter save area.
6286       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6287         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6288         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6289         if (GPR_idx != NumGPRs) {
6290           SDValue Load =
6291               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6292           MemOpChains.push_back(Load.getValue(1));
6293           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6294           ArgOffset += PtrByteSize;
6295         } else {
6296           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6297           break;
6298         }
6299       }
6300       continue;
6301     }
6302 
6303     switch (Arg.getSimpleValueType().SimpleTy) {
6304     default: llvm_unreachable("Unexpected ValueType for argument!");
6305     case MVT::i1:
6306     case MVT::i32:
6307     case MVT::i64:
6308       if (Flags.isNest()) {
6309         // The 'nest' parameter, if any, is passed in R11.
6310         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6311         break;
6312       }
6313 
6314       // These can be scalar arguments or elements of an integer array type
6315       // passed directly.  Clang may use those instead of "byval" aggregate
6316       // types to avoid forcing arguments to memory unnecessarily.
6317       if (GPR_idx != NumGPRs) {
6318         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6319       } else {
6320         if (IsFastCall)
6321           ComputePtrOff();
6322 
6323         assert(HasParameterArea &&
6324                "Parameter area must exist to pass an argument in memory.");
6325         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6326                          true, CFlags.IsTailCall, false, MemOpChains,
6327                          TailCallArguments, dl);
6328         if (IsFastCall)
6329           ArgOffset += PtrByteSize;
6330       }
6331       if (!IsFastCall)
6332         ArgOffset += PtrByteSize;
6333       break;
6334     case MVT::f32:
6335     case MVT::f64: {
6336       // These can be scalar arguments or elements of a float array type
6337       // passed directly.  The latter are used to implement ELFv2 homogenous
6338       // float aggregates.
6339 
6340       // Named arguments go into FPRs first, and once they overflow, the
6341       // remaining arguments go into GPRs and then the parameter save area.
6342       // Unnamed arguments for vararg functions always go to GPRs and
6343       // then the parameter save area.  For now, put all arguments to vararg
6344       // routines always in both locations (FPR *and* GPR or stack slot).
6345       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6346       bool NeededLoad = false;
6347 
6348       // First load the argument into the next available FPR.
6349       if (FPR_idx != NumFPRs)
6350         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6351 
6352       // Next, load the argument into GPR or stack slot if needed.
6353       if (!NeedGPROrStack)
6354         ;
6355       else if (GPR_idx != NumGPRs && !IsFastCall) {
6356         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6357         // once we support fp <-> gpr moves.
6358 
6359         // In the non-vararg case, this can only ever happen in the
6360         // presence of f32 array types, since otherwise we never run
6361         // out of FPRs before running out of GPRs.
6362         SDValue ArgVal;
6363 
6364         // Double values are always passed in a single GPR.
6365         if (Arg.getValueType() != MVT::f32) {
6366           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6367 
6368         // Non-array float values are extended and passed in a GPR.
6369         } else if (!Flags.isInConsecutiveRegs()) {
6370           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6371           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6372 
6373         // If we have an array of floats, we collect every odd element
6374         // together with its predecessor into one GPR.
6375         } else if (ArgOffset % PtrByteSize != 0) {
6376           SDValue Lo, Hi;
6377           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6378           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6379           if (!isLittleEndian)
6380             std::swap(Lo, Hi);
6381           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6382 
6383         // The final element, if even, goes into the first half of a GPR.
6384         } else if (Flags.isInConsecutiveRegsLast()) {
6385           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6386           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6387           if (!isLittleEndian)
6388             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6389                                  DAG.getConstant(32, dl, MVT::i32));
6390 
6391         // Non-final even elements are skipped; they will be handled
6392         // together the with subsequent argument on the next go-around.
6393         } else
6394           ArgVal = SDValue();
6395 
6396         if (ArgVal.getNode())
6397           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6398       } else {
6399         if (IsFastCall)
6400           ComputePtrOff();
6401 
6402         // Single-precision floating-point values are mapped to the
6403         // second (rightmost) word of the stack doubleword.
6404         if (Arg.getValueType() == MVT::f32 &&
6405             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6406           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6407           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6408         }
6409 
6410         assert(HasParameterArea &&
6411                "Parameter area must exist to pass an argument in memory.");
6412         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6413                          true, CFlags.IsTailCall, false, MemOpChains,
6414                          TailCallArguments, dl);
6415 
6416         NeededLoad = true;
6417       }
6418       // When passing an array of floats, the array occupies consecutive
6419       // space in the argument area; only round up to the next doubleword
6420       // at the end of the array.  Otherwise, each float takes 8 bytes.
6421       if (!IsFastCall || NeededLoad) {
6422         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6423                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6424         if (Flags.isInConsecutiveRegsLast())
6425           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6426       }
6427       break;
6428     }
6429     case MVT::v4f32:
6430     case MVT::v4i32:
6431     case MVT::v8i16:
6432     case MVT::v16i8:
6433     case MVT::v2f64:
6434     case MVT::v2i64:
6435     case MVT::v1i128:
6436     case MVT::f128:
6437       if (!Subtarget.hasQPX()) {
6438       // These can be scalar arguments or elements of a vector array type
6439       // passed directly.  The latter are used to implement ELFv2 homogenous
6440       // vector aggregates.
6441 
6442       // For a varargs call, named arguments go into VRs or on the stack as
6443       // usual; unnamed arguments always go to the stack or the corresponding
6444       // GPRs when within range.  For now, we always put the value in both
6445       // locations (or even all three).
6446       if (CFlags.IsVarArg) {
6447         assert(HasParameterArea &&
6448                "Parameter area must exist if we have a varargs call.");
6449         // We could elide this store in the case where the object fits
6450         // entirely in R registers.  Maybe later.
6451         SDValue Store =
6452             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6453         MemOpChains.push_back(Store);
6454         if (VR_idx != NumVRs) {
6455           SDValue Load =
6456               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6457           MemOpChains.push_back(Load.getValue(1));
6458           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6459         }
6460         ArgOffset += 16;
6461         for (unsigned i=0; i<16; i+=PtrByteSize) {
6462           if (GPR_idx == NumGPRs)
6463             break;
6464           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6465                                    DAG.getConstant(i, dl, PtrVT));
6466           SDValue Load =
6467               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6468           MemOpChains.push_back(Load.getValue(1));
6469           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6470         }
6471         break;
6472       }
6473 
6474       // Non-varargs Altivec params go into VRs or on the stack.
6475       if (VR_idx != NumVRs) {
6476         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6477       } else {
6478         if (IsFastCall)
6479           ComputePtrOff();
6480 
6481         assert(HasParameterArea &&
6482                "Parameter area must exist to pass an argument in memory.");
6483         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6484                          true, CFlags.IsTailCall, true, MemOpChains,
6485                          TailCallArguments, dl);
6486         if (IsFastCall)
6487           ArgOffset += 16;
6488       }
6489 
6490       if (!IsFastCall)
6491         ArgOffset += 16;
6492       break;
6493       } // not QPX
6494 
6495       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6496              "Invalid QPX parameter type");
6497 
6498       LLVM_FALLTHROUGH;
6499     case MVT::v4f64:
6500     case MVT::v4i1: {
6501       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6502       if (CFlags.IsVarArg) {
6503         assert(HasParameterArea &&
6504                "Parameter area must exist if we have a varargs call.");
6505         // We could elide this store in the case where the object fits
6506         // entirely in R registers.  Maybe later.
6507         SDValue Store =
6508             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6509         MemOpChains.push_back(Store);
6510         if (QFPR_idx != NumQFPRs) {
6511           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6512                                      PtrOff, MachinePointerInfo());
6513           MemOpChains.push_back(Load.getValue(1));
6514           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6515         }
6516         ArgOffset += (IsF32 ? 16 : 32);
6517         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6518           if (GPR_idx == NumGPRs)
6519             break;
6520           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6521                                    DAG.getConstant(i, dl, PtrVT));
6522           SDValue Load =
6523               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6524           MemOpChains.push_back(Load.getValue(1));
6525           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6526         }
6527         break;
6528       }
6529 
6530       // Non-varargs QPX params go into registers or on the stack.
6531       if (QFPR_idx != NumQFPRs) {
6532         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6533       } else {
6534         if (IsFastCall)
6535           ComputePtrOff();
6536 
6537         assert(HasParameterArea &&
6538                "Parameter area must exist to pass an argument in memory.");
6539         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6540                          true, CFlags.IsTailCall, true, MemOpChains,
6541                          TailCallArguments, dl);
6542         if (IsFastCall)
6543           ArgOffset += (IsF32 ? 16 : 32);
6544       }
6545 
6546       if (!IsFastCall)
6547         ArgOffset += (IsF32 ? 16 : 32);
6548       break;
6549       }
6550     }
6551   }
6552 
6553   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6554          "mismatch in size of parameter area");
6555   (void)NumBytesActuallyUsed;
6556 
6557   if (!MemOpChains.empty())
6558     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6559 
6560   // Check if this is an indirect call (MTCTR/BCTRL).
6561   // See prepareDescriptorIndirectCall and buildCallOperands for more
6562   // information about calls through function pointers in the 64-bit SVR4 ABI.
6563   if (CFlags.IsIndirect) {
6564     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6565     // caller in the TOC save area.
6566     if (isTOCSaveRestoreRequired(Subtarget)) {
6567       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6568       // Load r2 into a virtual register and store it to the TOC save area.
6569       setUsesTOCBasePtr(DAG);
6570       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6571       // TOC save area offset.
6572       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6573       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6574       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6575       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6576                            MachinePointerInfo::getStack(
6577                                DAG.getMachineFunction(), TOCSaveOffset));
6578     }
6579     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6580     // This does not mean the MTCTR instruction must use R12; it's easier
6581     // to model this as an extra parameter, so do that.
6582     if (isELFv2ABI && !CFlags.IsPatchPoint)
6583       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6584   }
6585 
6586   // Build a sequence of copy-to-reg nodes chained together with token chain
6587   // and flag operands which copy the outgoing args into the appropriate regs.
6588   SDValue InFlag;
6589   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6590     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6591                              RegsToPass[i].second, InFlag);
6592     InFlag = Chain.getValue(1);
6593   }
6594 
6595   if (CFlags.IsTailCall && !IsSibCall)
6596     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6597                     TailCallArguments);
6598 
6599   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6600                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6601 }
6602 
6603 SDValue PPCTargetLowering::LowerCall_Darwin(
6604     SDValue Chain, SDValue Callee, CallFlags CFlags,
6605     const SmallVectorImpl<ISD::OutputArg> &Outs,
6606     const SmallVectorImpl<SDValue> &OutVals,
6607     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6608     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6609     const CallBase *CB) const {
6610   unsigned NumOps = Outs.size();
6611 
6612   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6613   bool isPPC64 = PtrVT == MVT::i64;
6614   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6615 
6616   MachineFunction &MF = DAG.getMachineFunction();
6617 
6618   // Mark this function as potentially containing a function that contains a
6619   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6620   // and restoring the callers stack pointer in this functions epilog. This is
6621   // done because by tail calling the called function might overwrite the value
6622   // in this function's (MF) stack pointer stack slot 0(SP).
6623   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6624       CFlags.CallConv == CallingConv::Fast)
6625     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6626 
6627   // Count how many bytes are to be pushed on the stack, including the linkage
6628   // area, and parameter passing area.  We start with 24/48 bytes, which is
6629   // prereserved space for [SP][CR][LR][3 x unused].
6630   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6631   unsigned NumBytes = LinkageSize;
6632 
6633   // Add up all the space actually used.
6634   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6635   // they all go in registers, but we must reserve stack space for them for
6636   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6637   // assigned stack space in order, with padding so Altivec parameters are
6638   // 16-byte aligned.
6639   unsigned nAltivecParamsAtEnd = 0;
6640   for (unsigned i = 0; i != NumOps; ++i) {
6641     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6642     EVT ArgVT = Outs[i].VT;
6643     // Varargs Altivec parameters are padded to a 16 byte boundary.
6644     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6645         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6646         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6647       if (!CFlags.IsVarArg && !isPPC64) {
6648         // Non-varargs Altivec parameters go after all the non-Altivec
6649         // parameters; handle those later so we know how much padding we need.
6650         nAltivecParamsAtEnd++;
6651         continue;
6652       }
6653       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6654       NumBytes = ((NumBytes+15)/16)*16;
6655     }
6656     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6657   }
6658 
6659   // Allow for Altivec parameters at the end, if needed.
6660   if (nAltivecParamsAtEnd) {
6661     NumBytes = ((NumBytes+15)/16)*16;
6662     NumBytes += 16*nAltivecParamsAtEnd;
6663   }
6664 
6665   // The prolog code of the callee may store up to 8 GPR argument registers to
6666   // the stack, allowing va_start to index over them in memory if its varargs.
6667   // Because we cannot tell if this is needed on the caller side, we have to
6668   // conservatively assume that it is needed.  As such, make sure we have at
6669   // least enough stack space for the caller to store the 8 GPRs.
6670   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6671 
6672   // Tail call needs the stack to be aligned.
6673   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6674       CFlags.CallConv == CallingConv::Fast)
6675     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6676 
6677   // Calculate by how many bytes the stack has to be adjusted in case of tail
6678   // call optimization.
6679   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6680 
6681   // To protect arguments on the stack from being clobbered in a tail call,
6682   // force all the loads to happen before doing any other lowering.
6683   if (CFlags.IsTailCall)
6684     Chain = DAG.getStackArgumentTokenFactor(Chain);
6685 
6686   // Adjust the stack pointer for the new arguments...
6687   // These operations are automatically eliminated by the prolog/epilog pass
6688   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6689   SDValue CallSeqStart = Chain;
6690 
6691   // Load the return address and frame pointer so it can be move somewhere else
6692   // later.
6693   SDValue LROp, FPOp;
6694   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6695 
6696   // Set up a copy of the stack pointer for use loading and storing any
6697   // arguments that may not fit in the registers available for argument
6698   // passing.
6699   SDValue StackPtr;
6700   if (isPPC64)
6701     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6702   else
6703     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6704 
6705   // Figure out which arguments are going to go in registers, and which in
6706   // memory.  Also, if this is a vararg function, floating point operations
6707   // must be stored to our stack, and loaded into integer regs as well, if
6708   // any integer regs are available for argument passing.
6709   unsigned ArgOffset = LinkageSize;
6710   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6711 
6712   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6713     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6714     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6715   };
6716   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6717     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6718     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6719   };
6720   static const MCPhysReg VR[] = {
6721     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6722     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6723   };
6724   const unsigned NumGPRs = array_lengthof(GPR_32);
6725   const unsigned NumFPRs = 13;
6726   const unsigned NumVRs  = array_lengthof(VR);
6727 
6728   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6729 
6730   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6731   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6732 
6733   SmallVector<SDValue, 8> MemOpChains;
6734   for (unsigned i = 0; i != NumOps; ++i) {
6735     SDValue Arg = OutVals[i];
6736     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6737 
6738     // PtrOff will be used to store the current argument to the stack if a
6739     // register cannot be found for it.
6740     SDValue PtrOff;
6741 
6742     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6743 
6744     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6745 
6746     // On PPC64, promote integers to 64-bit values.
6747     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6748       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6749       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6750       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6751     }
6752 
6753     // FIXME memcpy is used way more than necessary.  Correctness first.
6754     // Note: "by value" is code for passing a structure by value, not
6755     // basic types.
6756     if (Flags.isByVal()) {
6757       unsigned Size = Flags.getByValSize();
6758       // Very small objects are passed right-justified.  Everything else is
6759       // passed left-justified.
6760       if (Size==1 || Size==2) {
6761         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6762         if (GPR_idx != NumGPRs) {
6763           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6764                                         MachinePointerInfo(), VT);
6765           MemOpChains.push_back(Load.getValue(1));
6766           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6767 
6768           ArgOffset += PtrByteSize;
6769         } else {
6770           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6771                                           PtrOff.getValueType());
6772           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6773           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6774                                                             CallSeqStart,
6775                                                             Flags, DAG, dl);
6776           ArgOffset += PtrByteSize;
6777         }
6778         continue;
6779       }
6780       // Copy entire object into memory.  There are cases where gcc-generated
6781       // code assumes it is there, even if it could be put entirely into
6782       // registers.  (This is not what the doc says.)
6783       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6784                                                         CallSeqStart,
6785                                                         Flags, DAG, dl);
6786 
6787       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6788       // copy the pieces of the object that fit into registers from the
6789       // parameter save area.
6790       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6791         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6792         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6793         if (GPR_idx != NumGPRs) {
6794           SDValue Load =
6795               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6796           MemOpChains.push_back(Load.getValue(1));
6797           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6798           ArgOffset += PtrByteSize;
6799         } else {
6800           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6801           break;
6802         }
6803       }
6804       continue;
6805     }
6806 
6807     switch (Arg.getSimpleValueType().SimpleTy) {
6808     default: llvm_unreachable("Unexpected ValueType for argument!");
6809     case MVT::i1:
6810     case MVT::i32:
6811     case MVT::i64:
6812       if (GPR_idx != NumGPRs) {
6813         if (Arg.getValueType() == MVT::i1)
6814           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6815 
6816         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6817       } else {
6818         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6819                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6820                          TailCallArguments, dl);
6821       }
6822       ArgOffset += PtrByteSize;
6823       break;
6824     case MVT::f32:
6825     case MVT::f64:
6826       if (FPR_idx != NumFPRs) {
6827         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6828 
6829         if (CFlags.IsVarArg) {
6830           SDValue Store =
6831               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6832           MemOpChains.push_back(Store);
6833 
6834           // Float varargs are always shadowed in available integer registers
6835           if (GPR_idx != NumGPRs) {
6836             SDValue Load =
6837                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6838             MemOpChains.push_back(Load.getValue(1));
6839             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6840           }
6841           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6842             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6843             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6844             SDValue Load =
6845                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6846             MemOpChains.push_back(Load.getValue(1));
6847             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6848           }
6849         } else {
6850           // If we have any FPRs remaining, we may also have GPRs remaining.
6851           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6852           // GPRs.
6853           if (GPR_idx != NumGPRs)
6854             ++GPR_idx;
6855           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6856               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6857             ++GPR_idx;
6858         }
6859       } else
6860         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6861                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6862                          TailCallArguments, dl);
6863       if (isPPC64)
6864         ArgOffset += 8;
6865       else
6866         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6867       break;
6868     case MVT::v4f32:
6869     case MVT::v4i32:
6870     case MVT::v8i16:
6871     case MVT::v16i8:
6872       if (CFlags.IsVarArg) {
6873         // These go aligned on the stack, or in the corresponding R registers
6874         // when within range.  The Darwin PPC ABI doc claims they also go in
6875         // V registers; in fact gcc does this only for arguments that are
6876         // prototyped, not for those that match the ...  We do it for all
6877         // arguments, seems to work.
6878         while (ArgOffset % 16 !=0) {
6879           ArgOffset += PtrByteSize;
6880           if (GPR_idx != NumGPRs)
6881             GPR_idx++;
6882         }
6883         // We could elide this store in the case where the object fits
6884         // entirely in R registers.  Maybe later.
6885         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6886                              DAG.getConstant(ArgOffset, dl, PtrVT));
6887         SDValue Store =
6888             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6889         MemOpChains.push_back(Store);
6890         if (VR_idx != NumVRs) {
6891           SDValue Load =
6892               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6893           MemOpChains.push_back(Load.getValue(1));
6894           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6895         }
6896         ArgOffset += 16;
6897         for (unsigned i=0; i<16; i+=PtrByteSize) {
6898           if (GPR_idx == NumGPRs)
6899             break;
6900           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6901                                    DAG.getConstant(i, dl, PtrVT));
6902           SDValue Load =
6903               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6904           MemOpChains.push_back(Load.getValue(1));
6905           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6906         }
6907         break;
6908       }
6909 
6910       // Non-varargs Altivec params generally go in registers, but have
6911       // stack space allocated at the end.
6912       if (VR_idx != NumVRs) {
6913         // Doesn't have GPR space allocated.
6914         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6915       } else if (nAltivecParamsAtEnd==0) {
6916         // We are emitting Altivec params in order.
6917         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6918                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6919                          TailCallArguments, dl);
6920         ArgOffset += 16;
6921       }
6922       break;
6923     }
6924   }
6925   // If all Altivec parameters fit in registers, as they usually do,
6926   // they get stack space following the non-Altivec parameters.  We
6927   // don't track this here because nobody below needs it.
6928   // If there are more Altivec parameters than fit in registers emit
6929   // the stores here.
6930   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6931     unsigned j = 0;
6932     // Offset is aligned; skip 1st 12 params which go in V registers.
6933     ArgOffset = ((ArgOffset+15)/16)*16;
6934     ArgOffset += 12*16;
6935     for (unsigned i = 0; i != NumOps; ++i) {
6936       SDValue Arg = OutVals[i];
6937       EVT ArgType = Outs[i].VT;
6938       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6939           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6940         if (++j > NumVRs) {
6941           SDValue PtrOff;
6942           // We are emitting Altivec params in order.
6943           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6944                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6945                            TailCallArguments, dl);
6946           ArgOffset += 16;
6947         }
6948       }
6949     }
6950   }
6951 
6952   if (!MemOpChains.empty())
6953     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6954 
6955   // On Darwin, R12 must contain the address of an indirect callee.  This does
6956   // not mean the MTCTR instruction must use R12; it's easier to model this as
6957   // an extra parameter, so do that.
6958   if (CFlags.IsIndirect) {
6959     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6960     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6961                                                    PPC::R12), Callee));
6962   }
6963 
6964   // Build a sequence of copy-to-reg nodes chained together with token chain
6965   // and flag operands which copy the outgoing args into the appropriate regs.
6966   SDValue InFlag;
6967   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6968     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6969                              RegsToPass[i].second, InFlag);
6970     InFlag = Chain.getValue(1);
6971   }
6972 
6973   if (CFlags.IsTailCall)
6974     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6975                     TailCallArguments);
6976 
6977   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6978                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6979 }
6980 
6981 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6982                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6983                    CCState &State) {
6984 
6985   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6986       State.getMachineFunction().getSubtarget());
6987   const bool IsPPC64 = Subtarget.isPPC64();
6988   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6989   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6990 
6991   assert((!ValVT.isInteger() ||
6992           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6993          "Integer argument exceeds register size: should have been legalized");
6994 
6995   if (ValVT == MVT::f128)
6996     report_fatal_error("f128 is unimplemented on AIX.");
6997 
6998   if (ArgFlags.isNest())
6999     report_fatal_error("Nest arguments are unimplemented.");
7000 
7001   if (ValVT.isVector() || LocVT.isVector())
7002     report_fatal_error("Vector arguments are unimplemented on AIX.");
7003 
7004   static const MCPhysReg GPR_32[] = {// 32-bit registers.
7005                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7006                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7007   static const MCPhysReg GPR_64[] = {// 64-bit registers.
7008                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7009                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7010 
7011   if (ArgFlags.isByVal()) {
7012     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
7013       report_fatal_error("Pass-by-value arguments with alignment greater than "
7014                          "register width are not supported.");
7015 
7016     const unsigned ByValSize = ArgFlags.getByValSize();
7017 
7018     // An empty aggregate parameter takes up no storage and no registers,
7019     // but needs a MemLoc for a stack slot for the formal arguments side.
7020     if (ByValSize == 0) {
7021       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7022                                        State.getNextStackOffset(), RegVT,
7023                                        LocInfo));
7024       return false;
7025     }
7026 
7027     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
7028     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
7029     for (const unsigned E = Offset + StackSize; Offset < E;
7030          Offset += PtrAlign.value()) {
7031       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7032         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7033       else {
7034         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
7035                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
7036                                          LocInfo));
7037         break;
7038       }
7039     }
7040     return false;
7041   }
7042 
7043   // Arguments always reserve parameter save area.
7044   switch (ValVT.SimpleTy) {
7045   default:
7046     report_fatal_error("Unhandled value type for argument.");
7047   case MVT::i64:
7048     // i64 arguments should have been split to i32 for PPC32.
7049     assert(IsPPC64 && "PPC32 should have split i64 values.");
7050     LLVM_FALLTHROUGH;
7051   case MVT::i1:
7052   case MVT::i32: {
7053     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
7054     // AIX integer arguments are always passed in register width.
7055     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
7056       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
7057                                   : CCValAssign::LocInfo::ZExt;
7058     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
7059       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7060     else
7061       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
7062 
7063     return false;
7064   }
7065   case MVT::f32:
7066   case MVT::f64: {
7067     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7068     const unsigned StoreSize = LocVT.getStoreSize();
7069     // Floats are always 4-byte aligned in the PSA on AIX.
7070     // This includes f64 in 64-bit mode for ABI compatibility.
7071     const unsigned Offset =
7072         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
7073     unsigned FReg = State.AllocateReg(FPR);
7074     if (FReg)
7075       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7076 
7077     // Reserve and initialize GPRs or initialize the PSA as required.
7078     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
7079       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7080         assert(FReg && "An FPR should be available when a GPR is reserved.");
7081         if (State.isVarArg()) {
7082           // Successfully reserved GPRs are only initialized for vararg calls.
7083           // Custom handling is required for:
7084           //   f64 in PPC32 needs to be split into 2 GPRs.
7085           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7086           State.addLoc(
7087               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7088         }
7089       } else {
7090         // If there are insufficient GPRs, the PSA needs to be initialized.
7091         // Initialization occurs even if an FPR was initialized for
7092         // compatibility with the AIX XL compiler. The full memory for the
7093         // argument will be initialized even if a prior word is saved in GPR.
7094         // A custom memLoc is used when the argument also passes in FPR so
7095         // that the callee handling can skip over it easily.
7096         State.addLoc(
7097             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7098                                              LocInfo)
7099                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7100         break;
7101       }
7102     }
7103 
7104     return false;
7105   }
7106   }
7107   return true;
7108 }
7109 
7110 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7111                                                     bool IsPPC64) {
7112   assert((IsPPC64 || SVT != MVT::i64) &&
7113          "i64 should have been split for 32-bit codegen.");
7114 
7115   switch (SVT) {
7116   default:
7117     report_fatal_error("Unexpected value type for formal argument");
7118   case MVT::i1:
7119   case MVT::i32:
7120   case MVT::i64:
7121     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7122   case MVT::f32:
7123     return &PPC::F4RCRegClass;
7124   case MVT::f64:
7125     return &PPC::F8RCRegClass;
7126   }
7127 }
7128 
7129 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7130                                         SelectionDAG &DAG, SDValue ArgValue,
7131                                         MVT LocVT, const SDLoc &dl) {
7132   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7133   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7134 
7135   if (Flags.isSExt())
7136     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7137                            DAG.getValueType(ValVT));
7138   else if (Flags.isZExt())
7139     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7140                            DAG.getValueType(ValVT));
7141 
7142   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7143 }
7144 
7145 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7146   const unsigned LASize = FL->getLinkageSize();
7147 
7148   if (PPC::GPRCRegClass.contains(Reg)) {
7149     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7150            "Reg must be a valid argument register!");
7151     return LASize + 4 * (Reg - PPC::R3);
7152   }
7153 
7154   if (PPC::G8RCRegClass.contains(Reg)) {
7155     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7156            "Reg must be a valid argument register!");
7157     return LASize + 8 * (Reg - PPC::X3);
7158   }
7159 
7160   llvm_unreachable("Only general purpose registers expected.");
7161 }
7162 
7163 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7164     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7165     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7166     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7167 
7168   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7169           CallConv == CallingConv::Fast) &&
7170          "Unexpected calling convention!");
7171 
7172   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7173     report_fatal_error("Tail call support is unimplemented on AIX.");
7174 
7175   if (useSoftFloat())
7176     report_fatal_error("Soft float support is unimplemented on AIX.");
7177 
7178   const PPCSubtarget &Subtarget =
7179       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7180   if (Subtarget.hasQPX())
7181     report_fatal_error("QPX support is not supported on AIX.");
7182 
7183   const bool IsPPC64 = Subtarget.isPPC64();
7184   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7185 
7186   // Assign locations to all of the incoming arguments.
7187   SmallVector<CCValAssign, 16> ArgLocs;
7188   MachineFunction &MF = DAG.getMachineFunction();
7189   MachineFrameInfo &MFI = MF.getFrameInfo();
7190   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7191 
7192   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7193   // Reserve space for the linkage area on the stack.
7194   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7195   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7196   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7197 
7198   SmallVector<SDValue, 8> MemOps;
7199 
7200   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7201     CCValAssign &VA = ArgLocs[I++];
7202     MVT LocVT = VA.getLocVT();
7203     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7204 
7205     // For compatibility with the AIX XL compiler, the float args in the
7206     // parameter save area are initialized even if the argument is available
7207     // in register.  The caller is required to initialize both the register
7208     // and memory, however, the callee can choose to expect it in either.
7209     // The memloc is dismissed here because the argument is retrieved from
7210     // the register.
7211     if (VA.isMemLoc() && VA.needsCustom())
7212       continue;
7213 
7214     if (Flags.isByVal() && VA.isMemLoc()) {
7215       const unsigned Size =
7216           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7217                   PtrByteSize);
7218       const int FI = MF.getFrameInfo().CreateFixedObject(
7219           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7220           /* IsAliased */ true);
7221       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7222       InVals.push_back(FIN);
7223 
7224       continue;
7225     }
7226 
7227     if (Flags.isByVal()) {
7228       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7229 
7230       const MCPhysReg ArgReg = VA.getLocReg();
7231       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7232 
7233       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7234         report_fatal_error("Over aligned byvals not supported yet.");
7235 
7236       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7237       const int FI = MF.getFrameInfo().CreateFixedObject(
7238           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7239           /* IsAliased */ true);
7240       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7241       InVals.push_back(FIN);
7242 
7243       // Add live ins for all the RegLocs for the same ByVal.
7244       const TargetRegisterClass *RegClass =
7245           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7246 
7247       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7248                                                unsigned Offset) {
7249         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7250         // Since the callers side has left justified the aggregate in the
7251         // register, we can simply store the entire register into the stack
7252         // slot.
7253         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7254         // The store to the fixedstack object is needed becuase accessing a
7255         // field of the ByVal will use a gep and load. Ideally we will optimize
7256         // to extracting the value from the register directly, and elide the
7257         // stores when the arguments address is not taken, but that will need to
7258         // be future work.
7259         SDValue Store =
7260             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7261                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7262                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7263 
7264         MemOps.push_back(Store);
7265       };
7266 
7267       unsigned Offset = 0;
7268       HandleRegLoc(VA.getLocReg(), Offset);
7269       Offset += PtrByteSize;
7270       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7271            Offset += PtrByteSize) {
7272         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7273                "RegLocs should be for ByVal argument.");
7274 
7275         const CCValAssign RL = ArgLocs[I++];
7276         HandleRegLoc(RL.getLocReg(), Offset);
7277       }
7278 
7279       if (Offset != StackSize) {
7280         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7281                "Expected MemLoc for remaining bytes.");
7282         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7283         // Consume the MemLoc.The InVal has already been emitted, so nothing
7284         // more needs to be done.
7285         ++I;
7286       }
7287 
7288       continue;
7289     }
7290 
7291     EVT ValVT = VA.getValVT();
7292     if (VA.isRegLoc() && !VA.needsCustom()) {
7293       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7294       unsigned VReg =
7295           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7296       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7297       if (ValVT.isScalarInteger() &&
7298           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7299         ArgValue =
7300             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7301       }
7302       InVals.push_back(ArgValue);
7303       continue;
7304     }
7305     if (VA.isMemLoc()) {
7306       const unsigned LocSize = LocVT.getStoreSize();
7307       const unsigned ValSize = ValVT.getStoreSize();
7308       assert((ValSize <= LocSize) &&
7309              "Object size is larger than size of MemLoc");
7310       int CurArgOffset = VA.getLocMemOffset();
7311       // Objects are right-justified because AIX is big-endian.
7312       if (LocSize > ValSize)
7313         CurArgOffset += LocSize - ValSize;
7314       // Potential tail calls could cause overwriting of argument stack slots.
7315       const bool IsImmutable =
7316           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7317             (CallConv == CallingConv::Fast));
7318       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7319       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7320       SDValue ArgValue =
7321           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7322       InVals.push_back(ArgValue);
7323       continue;
7324     }
7325   }
7326 
7327   // On AIX a minimum of 8 words is saved to the parameter save area.
7328   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7329   // Area that is at least reserved in the caller of this function.
7330   unsigned CallerReservedArea =
7331       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7332 
7333   // Set the size that is at least reserved in caller of this function. Tail
7334   // call optimized function's reserved stack space needs to be aligned so
7335   // that taking the difference between two stack areas will result in an
7336   // aligned stack.
7337   CallerReservedArea =
7338       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7339   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7340   FuncInfo->setMinReservedArea(CallerReservedArea);
7341 
7342   if (isVarArg) {
7343     FuncInfo->setVarArgsFrameIndex(
7344         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7345     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7346 
7347     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7348                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7349 
7350     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7351                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7352     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7353 
7354     // The fixed integer arguments of a variadic function are stored to the
7355     // VarArgsFrameIndex on the stack so that they may be loaded by
7356     // dereferencing the result of va_next.
7357     for (unsigned GPRIndex =
7358              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7359          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7360 
7361       const unsigned VReg =
7362           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7363                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7364 
7365       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7366       SDValue Store =
7367           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7368       MemOps.push_back(Store);
7369       // Increment the address for the next argument to store.
7370       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7371       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7372     }
7373   }
7374 
7375   if (!MemOps.empty())
7376     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7377 
7378   return Chain;
7379 }
7380 
7381 SDValue PPCTargetLowering::LowerCall_AIX(
7382     SDValue Chain, SDValue Callee, CallFlags CFlags,
7383     const SmallVectorImpl<ISD::OutputArg> &Outs,
7384     const SmallVectorImpl<SDValue> &OutVals,
7385     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7386     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7387     const CallBase *CB) const {
7388 
7389   assert((CFlags.CallConv == CallingConv::C ||
7390           CFlags.CallConv == CallingConv::Cold ||
7391           CFlags.CallConv == CallingConv::Fast) &&
7392          "Unexpected calling convention!");
7393 
7394   if (CFlags.IsPatchPoint)
7395     report_fatal_error("This call type is unimplemented on AIX.");
7396 
7397   const PPCSubtarget& Subtarget =
7398       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7399   if (Subtarget.hasQPX())
7400     report_fatal_error("QPX is not supported on AIX.");
7401   if (Subtarget.hasAltivec())
7402     report_fatal_error("Altivec support is unimplemented on AIX.");
7403 
7404   MachineFunction &MF = DAG.getMachineFunction();
7405   SmallVector<CCValAssign, 16> ArgLocs;
7406   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7407                  *DAG.getContext());
7408 
7409   // Reserve space for the linkage save area (LSA) on the stack.
7410   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7411   //   [SP][CR][LR][2 x reserved][TOC].
7412   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7413   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7414   const bool IsPPC64 = Subtarget.isPPC64();
7415   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7416   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7417   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7418   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7419 
7420   // The prolog code of the callee may store up to 8 GPR argument registers to
7421   // the stack, allowing va_start to index over them in memory if the callee
7422   // is variadic.
7423   // Because we cannot tell if this is needed on the caller side, we have to
7424   // conservatively assume that it is needed.  As such, make sure we have at
7425   // least enough stack space for the caller to store the 8 GPRs.
7426   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7427   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7428                                      CCInfo.getNextStackOffset());
7429 
7430   // Adjust the stack pointer for the new arguments...
7431   // These operations are automatically eliminated by the prolog/epilog pass.
7432   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7433   SDValue CallSeqStart = Chain;
7434 
7435   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7436   SmallVector<SDValue, 8> MemOpChains;
7437 
7438   // Set up a copy of the stack pointer for loading and storing any
7439   // arguments that may not fit in the registers available for argument
7440   // passing.
7441   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7442                                    : DAG.getRegister(PPC::R1, MVT::i32);
7443 
7444   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7445     const unsigned ValNo = ArgLocs[I].getValNo();
7446     SDValue Arg = OutVals[ValNo];
7447     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7448 
7449     if (Flags.isByVal()) {
7450       const unsigned ByValSize = Flags.getByValSize();
7451 
7452       // Nothing to do for zero-sized ByVals on the caller side.
7453       if (!ByValSize) {
7454         ++I;
7455         continue;
7456       }
7457 
7458       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7459         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7460                               (LoadOffset != 0)
7461                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7462                                   : Arg,
7463                               MachinePointerInfo(), VT);
7464       };
7465 
7466       unsigned LoadOffset = 0;
7467 
7468       // Initialize registers, which are fully occupied by the by-val argument.
7469       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7470         SDValue Load = GetLoad(PtrVT, LoadOffset);
7471         MemOpChains.push_back(Load.getValue(1));
7472         LoadOffset += PtrByteSize;
7473         const CCValAssign &ByValVA = ArgLocs[I++];
7474         assert(ByValVA.getValNo() == ValNo &&
7475                "Unexpected location for pass-by-value argument.");
7476         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7477       }
7478 
7479       if (LoadOffset == ByValSize)
7480         continue;
7481 
7482       // There must be one more loc to handle the remainder.
7483       assert(ArgLocs[I].getValNo() == ValNo &&
7484              "Expected additional location for by-value argument.");
7485 
7486       if (ArgLocs[I].isMemLoc()) {
7487         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7488         const CCValAssign &ByValVA = ArgLocs[I++];
7489         ISD::ArgFlagsTy MemcpyFlags = Flags;
7490         // Only memcpy the bytes that don't pass in register.
7491         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7492         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7493             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7494                               : Arg,
7495             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7496             CallSeqStart, MemcpyFlags, DAG, dl);
7497         continue;
7498       }
7499 
7500       // Initialize the final register residue.
7501       // Any residue that occupies the final by-val arg register must be
7502       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7503       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7504       // 2 and 1 byte loads.
7505       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7506       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7507              "Unexpected register residue for by-value argument.");
7508       SDValue ResidueVal;
7509       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7510         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7511         const MVT VT =
7512             N == 1 ? MVT::i8
7513                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7514         SDValue Load = GetLoad(VT, LoadOffset);
7515         MemOpChains.push_back(Load.getValue(1));
7516         LoadOffset += N;
7517         Bytes += N;
7518 
7519         // By-val arguments are passed left-justfied in register.
7520         // Every load here needs to be shifted, otherwise a full register load
7521         // should have been used.
7522         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7523                "Unexpected load emitted during handling of pass-by-value "
7524                "argument.");
7525         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7526         EVT ShiftAmountTy =
7527             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7528         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7529         SDValue ShiftedLoad =
7530             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7531         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7532                                               ShiftedLoad)
7533                                 : ShiftedLoad;
7534       }
7535 
7536       const CCValAssign &ByValVA = ArgLocs[I++];
7537       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7538       continue;
7539     }
7540 
7541     CCValAssign &VA = ArgLocs[I++];
7542     const MVT LocVT = VA.getLocVT();
7543     const MVT ValVT = VA.getValVT();
7544 
7545     switch (VA.getLocInfo()) {
7546     default:
7547       report_fatal_error("Unexpected argument extension type.");
7548     case CCValAssign::Full:
7549       break;
7550     case CCValAssign::ZExt:
7551       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7552       break;
7553     case CCValAssign::SExt:
7554       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7555       break;
7556     }
7557 
7558     if (VA.isRegLoc() && !VA.needsCustom()) {
7559       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7560       continue;
7561     }
7562 
7563     if (VA.isMemLoc()) {
7564       SDValue PtrOff =
7565           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7566       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7567       MemOpChains.push_back(
7568           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7569 
7570       continue;
7571     }
7572 
7573     // Custom handling is used for GPR initializations for vararg float
7574     // arguments.
7575     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7576            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7577            "Unexpected register handling for calling convention.");
7578 
7579     SDValue ArgAsInt =
7580         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7581 
7582     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7583       // f32 in 32-bit GPR
7584       // f64 in 64-bit GPR
7585       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7586     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7587       // f32 in 64-bit GPR.
7588       RegsToPass.push_back(std::make_pair(
7589           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7590     else {
7591       // f64 in two 32-bit GPRs
7592       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7593       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7594              "Unexpected custom register for argument!");
7595       CCValAssign &GPR1 = VA;
7596       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7597                                      DAG.getConstant(32, dl, MVT::i8));
7598       RegsToPass.push_back(std::make_pair(
7599           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7600 
7601       if (I != E) {
7602         // If only 1 GPR was available, there will only be one custom GPR and
7603         // the argument will also pass in memory.
7604         CCValAssign &PeekArg = ArgLocs[I];
7605         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7606           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7607           CCValAssign &GPR2 = ArgLocs[I++];
7608           RegsToPass.push_back(std::make_pair(
7609               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7610         }
7611       }
7612     }
7613   }
7614 
7615   if (!MemOpChains.empty())
7616     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7617 
7618   // For indirect calls, we need to save the TOC base to the stack for
7619   // restoration after the call.
7620   if (CFlags.IsIndirect) {
7621     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7622     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7623     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7624     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7625     const unsigned TOCSaveOffset =
7626         Subtarget.getFrameLowering()->getTOCSaveOffset();
7627 
7628     setUsesTOCBasePtr(DAG);
7629     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7630     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7631     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7632     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7633     Chain = DAG.getStore(
7634         Val.getValue(1), dl, Val, AddPtr,
7635         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7636   }
7637 
7638   // Build a sequence of copy-to-reg nodes chained together with token chain
7639   // and flag operands which copy the outgoing args into the appropriate regs.
7640   SDValue InFlag;
7641   for (auto Reg : RegsToPass) {
7642     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7643     InFlag = Chain.getValue(1);
7644   }
7645 
7646   const int SPDiff = 0;
7647   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7648                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7649 }
7650 
7651 bool
7652 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7653                                   MachineFunction &MF, bool isVarArg,
7654                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7655                                   LLVMContext &Context) const {
7656   SmallVector<CCValAssign, 16> RVLocs;
7657   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7658   return CCInfo.CheckReturn(
7659       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7660                 ? RetCC_PPC_Cold
7661                 : RetCC_PPC);
7662 }
7663 
7664 SDValue
7665 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7666                                bool isVarArg,
7667                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7668                                const SmallVectorImpl<SDValue> &OutVals,
7669                                const SDLoc &dl, SelectionDAG &DAG) const {
7670   SmallVector<CCValAssign, 16> RVLocs;
7671   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7672                  *DAG.getContext());
7673   CCInfo.AnalyzeReturn(Outs,
7674                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7675                            ? RetCC_PPC_Cold
7676                            : RetCC_PPC);
7677 
7678   SDValue Flag;
7679   SmallVector<SDValue, 4> RetOps(1, Chain);
7680 
7681   // Copy the result values into the output registers.
7682   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7683     CCValAssign &VA = RVLocs[i];
7684     assert(VA.isRegLoc() && "Can only return in registers!");
7685 
7686     SDValue Arg = OutVals[RealResIdx];
7687 
7688     switch (VA.getLocInfo()) {
7689     default: llvm_unreachable("Unknown loc info!");
7690     case CCValAssign::Full: break;
7691     case CCValAssign::AExt:
7692       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7693       break;
7694     case CCValAssign::ZExt:
7695       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7696       break;
7697     case CCValAssign::SExt:
7698       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7699       break;
7700     }
7701     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7702       bool isLittleEndian = Subtarget.isLittleEndian();
7703       // Legalize ret f64 -> ret 2 x i32.
7704       SDValue SVal =
7705           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7706                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7707       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7708       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7709       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7710                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7711       Flag = Chain.getValue(1);
7712       VA = RVLocs[++i]; // skip ahead to next loc
7713       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7714     } else
7715       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7716     Flag = Chain.getValue(1);
7717     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7718   }
7719 
7720   RetOps[0] = Chain;  // Update chain.
7721 
7722   // Add the flag if we have it.
7723   if (Flag.getNode())
7724     RetOps.push_back(Flag);
7725 
7726   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7727 }
7728 
7729 SDValue
7730 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7731                                                 SelectionDAG &DAG) const {
7732   SDLoc dl(Op);
7733 
7734   // Get the correct type for integers.
7735   EVT IntVT = Op.getValueType();
7736 
7737   // Get the inputs.
7738   SDValue Chain = Op.getOperand(0);
7739   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7740   // Build a DYNAREAOFFSET node.
7741   SDValue Ops[2] = {Chain, FPSIdx};
7742   SDVTList VTs = DAG.getVTList(IntVT);
7743   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7744 }
7745 
7746 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7747                                              SelectionDAG &DAG) const {
7748   // When we pop the dynamic allocation we need to restore the SP link.
7749   SDLoc dl(Op);
7750 
7751   // Get the correct type for pointers.
7752   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7753 
7754   // Construct the stack pointer operand.
7755   bool isPPC64 = Subtarget.isPPC64();
7756   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7757   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7758 
7759   // Get the operands for the STACKRESTORE.
7760   SDValue Chain = Op.getOperand(0);
7761   SDValue SaveSP = Op.getOperand(1);
7762 
7763   // Load the old link SP.
7764   SDValue LoadLinkSP =
7765       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7766 
7767   // Restore the stack pointer.
7768   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7769 
7770   // Store the old link SP.
7771   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7772 }
7773 
7774 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7775   MachineFunction &MF = DAG.getMachineFunction();
7776   bool isPPC64 = Subtarget.isPPC64();
7777   EVT PtrVT = getPointerTy(MF.getDataLayout());
7778 
7779   // Get current frame pointer save index.  The users of this index will be
7780   // primarily DYNALLOC instructions.
7781   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7782   int RASI = FI->getReturnAddrSaveIndex();
7783 
7784   // If the frame pointer save index hasn't been defined yet.
7785   if (!RASI) {
7786     // Find out what the fix offset of the frame pointer save area.
7787     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7788     // Allocate the frame index for frame pointer save area.
7789     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7790     // Save the result.
7791     FI->setReturnAddrSaveIndex(RASI);
7792   }
7793   return DAG.getFrameIndex(RASI, PtrVT);
7794 }
7795 
7796 SDValue
7797 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7798   MachineFunction &MF = DAG.getMachineFunction();
7799   bool isPPC64 = Subtarget.isPPC64();
7800   EVT PtrVT = getPointerTy(MF.getDataLayout());
7801 
7802   // Get current frame pointer save index.  The users of this index will be
7803   // primarily DYNALLOC instructions.
7804   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7805   int FPSI = FI->getFramePointerSaveIndex();
7806 
7807   // If the frame pointer save index hasn't been defined yet.
7808   if (!FPSI) {
7809     // Find out what the fix offset of the frame pointer save area.
7810     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7811     // Allocate the frame index for frame pointer save area.
7812     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7813     // Save the result.
7814     FI->setFramePointerSaveIndex(FPSI);
7815   }
7816   return DAG.getFrameIndex(FPSI, PtrVT);
7817 }
7818 
7819 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7820                                                    SelectionDAG &DAG) const {
7821   // Get the inputs.
7822   SDValue Chain = Op.getOperand(0);
7823   SDValue Size  = Op.getOperand(1);
7824   SDLoc dl(Op);
7825 
7826   // Get the correct type for pointers.
7827   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7828   // Negate the size.
7829   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7830                                 DAG.getConstant(0, dl, PtrVT), Size);
7831   // Construct a node for the frame pointer save index.
7832   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7833   // Build a DYNALLOC node.
7834   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7835   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7836   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7837 }
7838 
7839 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7840                                                      SelectionDAG &DAG) const {
7841   MachineFunction &MF = DAG.getMachineFunction();
7842 
7843   bool isPPC64 = Subtarget.isPPC64();
7844   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7845 
7846   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7847   return DAG.getFrameIndex(FI, PtrVT);
7848 }
7849 
7850 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7851                                                SelectionDAG &DAG) const {
7852   SDLoc DL(Op);
7853   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7854                      DAG.getVTList(MVT::i32, MVT::Other),
7855                      Op.getOperand(0), Op.getOperand(1));
7856 }
7857 
7858 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7859                                                 SelectionDAG &DAG) const {
7860   SDLoc DL(Op);
7861   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7862                      Op.getOperand(0), Op.getOperand(1));
7863 }
7864 
7865 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7866   if (Op.getValueType().isVector())
7867     return LowerVectorLoad(Op, DAG);
7868 
7869   assert(Op.getValueType() == MVT::i1 &&
7870          "Custom lowering only for i1 loads");
7871 
7872   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7873 
7874   SDLoc dl(Op);
7875   LoadSDNode *LD = cast<LoadSDNode>(Op);
7876 
7877   SDValue Chain = LD->getChain();
7878   SDValue BasePtr = LD->getBasePtr();
7879   MachineMemOperand *MMO = LD->getMemOperand();
7880 
7881   SDValue NewLD =
7882       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7883                      BasePtr, MVT::i8, MMO);
7884   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7885 
7886   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7887   return DAG.getMergeValues(Ops, dl);
7888 }
7889 
7890 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7891   if (Op.getOperand(1).getValueType().isVector())
7892     return LowerVectorStore(Op, DAG);
7893 
7894   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7895          "Custom lowering only for i1 stores");
7896 
7897   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7898 
7899   SDLoc dl(Op);
7900   StoreSDNode *ST = cast<StoreSDNode>(Op);
7901 
7902   SDValue Chain = ST->getChain();
7903   SDValue BasePtr = ST->getBasePtr();
7904   SDValue Value = ST->getValue();
7905   MachineMemOperand *MMO = ST->getMemOperand();
7906 
7907   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7908                       Value);
7909   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7910 }
7911 
7912 // FIXME: Remove this once the ANDI glue bug is fixed:
7913 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7914   assert(Op.getValueType() == MVT::i1 &&
7915          "Custom lowering only for i1 results");
7916 
7917   SDLoc DL(Op);
7918   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7919 }
7920 
7921 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7922                                                SelectionDAG &DAG) const {
7923 
7924   // Implements a vector truncate that fits in a vector register as a shuffle.
7925   // We want to legalize vector truncates down to where the source fits in
7926   // a vector register (and target is therefore smaller than vector register
7927   // size).  At that point legalization will try to custom lower the sub-legal
7928   // result and get here - where we can contain the truncate as a single target
7929   // operation.
7930 
7931   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7932   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7933   //
7934   // We will implement it for big-endian ordering as this (where x denotes
7935   // undefined):
7936   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7937   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7938   //
7939   // The same operation in little-endian ordering will be:
7940   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7941   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7942 
7943   assert(Op.getValueType().isVector() && "Vector type expected.");
7944 
7945   SDLoc DL(Op);
7946   SDValue N1 = Op.getOperand(0);
7947   unsigned SrcSize = N1.getValueType().getSizeInBits();
7948   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7949   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7950 
7951   EVT TrgVT = Op.getValueType();
7952   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7953   EVT EltVT = TrgVT.getVectorElementType();
7954   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7955   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7956 
7957   // First list the elements we want to keep.
7958   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7959   SmallVector<int, 16> ShuffV;
7960   if (Subtarget.isLittleEndian())
7961     for (unsigned i = 0; i < TrgNumElts; ++i)
7962       ShuffV.push_back(i * SizeMult);
7963   else
7964     for (unsigned i = 1; i <= TrgNumElts; ++i)
7965       ShuffV.push_back(i * SizeMult - 1);
7966 
7967   // Populate the remaining elements with undefs.
7968   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7969     // ShuffV.push_back(i + WideNumElts);
7970     ShuffV.push_back(WideNumElts + 1);
7971 
7972   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7973   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7974 }
7975 
7976 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7977 /// possible.
7978 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7979   // Not FP? Not a fsel.
7980   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7981       !Op.getOperand(2).getValueType().isFloatingPoint())
7982     return Op;
7983 
7984   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7985 
7986   EVT ResVT = Op.getValueType();
7987   EVT CmpVT = Op.getOperand(0).getValueType();
7988   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7989   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7990   SDLoc dl(Op);
7991   SDNodeFlags Flags = Op.getNode()->getFlags();
7992 
7993   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7994   // presence of infinities.
7995   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7996     switch (CC) {
7997     default:
7998       break;
7999     case ISD::SETOGT:
8000     case ISD::SETGT:
8001       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
8002     case ISD::SETOLT:
8003     case ISD::SETLT:
8004       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
8005     }
8006   }
8007 
8008   // We might be able to do better than this under some circumstances, but in
8009   // general, fsel-based lowering of select is a finite-math-only optimization.
8010   // For more information, see section F.3 of the 2.06 ISA specification.
8011   // With ISA 3.0
8012   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
8013       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
8014     return Op;
8015 
8016   // If the RHS of the comparison is a 0.0, we don't need to do the
8017   // subtraction at all.
8018   SDValue Sel1;
8019   if (isFloatingPointZero(RHS))
8020     switch (CC) {
8021     default: break;       // SETUO etc aren't handled by fsel.
8022     case ISD::SETNE:
8023       std::swap(TV, FV);
8024       LLVM_FALLTHROUGH;
8025     case ISD::SETEQ:
8026       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8027         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8028       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8029       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8030         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8031       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8032                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8033     case ISD::SETULT:
8034     case ISD::SETLT:
8035       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8036       LLVM_FALLTHROUGH;
8037     case ISD::SETOGE:
8038     case ISD::SETGE:
8039       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8040         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8041       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8042     case ISD::SETUGT:
8043     case ISD::SETGT:
8044       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
8045       LLVM_FALLTHROUGH;
8046     case ISD::SETOLE:
8047     case ISD::SETLE:
8048       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
8049         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8050       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8051                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8052     }
8053 
8054   SDValue Cmp;
8055   switch (CC) {
8056   default: break;       // SETUO etc aren't handled by fsel.
8057   case ISD::SETNE:
8058     std::swap(TV, FV);
8059     LLVM_FALLTHROUGH;
8060   case ISD::SETEQ:
8061     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8062     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8063       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8064     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8065     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8066       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8067     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8068                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8069   case ISD::SETULT:
8070   case ISD::SETLT:
8071     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8072     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8073       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8074     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8075   case ISD::SETOGE:
8076   case ISD::SETGE:
8077     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8078     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8079       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8080     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8081   case ISD::SETUGT:
8082   case ISD::SETGT:
8083     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8084     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8085       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8086     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8087   case ISD::SETOLE:
8088   case ISD::SETLE:
8089     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8090     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8091       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8092     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8093   }
8094   return Op;
8095 }
8096 
8097 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8098                                                SelectionDAG &DAG,
8099                                                const SDLoc &dl) const {
8100   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8101   SDValue Src = Op.getOperand(0);
8102   if (Src.getValueType() == MVT::f32)
8103     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8104 
8105   SDValue Tmp;
8106   switch (Op.getSimpleValueType().SimpleTy) {
8107   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8108   case MVT::i32:
8109     Tmp = DAG.getNode(
8110         Op.getOpcode() == ISD::FP_TO_SINT
8111             ? PPCISD::FCTIWZ
8112             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8113         dl, MVT::f64, Src);
8114     break;
8115   case MVT::i64:
8116     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8117            "i64 FP_TO_UINT is supported only with FPCVT");
8118     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8119                                                         PPCISD::FCTIDUZ,
8120                       dl, MVT::f64, Src);
8121     break;
8122   }
8123 
8124   // Convert the FP value to an int value through memory.
8125   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8126     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8127   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8128   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8129   MachinePointerInfo MPI =
8130       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8131 
8132   // Emit a store to the stack slot.
8133   SDValue Chain;
8134   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8135   if (i32Stack) {
8136     MachineFunction &MF = DAG.getMachineFunction();
8137     Alignment = Align(4);
8138     MachineMemOperand *MMO =
8139         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8140     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8141     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8142               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8143   } else
8144     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8145 
8146   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8147   // add in a bias on big endian.
8148   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8149     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8150                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8151     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8152   }
8153 
8154   RLI.Chain = Chain;
8155   RLI.Ptr = FIPtr;
8156   RLI.MPI = MPI;
8157   RLI.Alignment = Alignment;
8158 }
8159 
8160 /// Custom lowers floating point to integer conversions to use
8161 /// the direct move instructions available in ISA 2.07 to avoid the
8162 /// need for load/store combinations.
8163 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8164                                                     SelectionDAG &DAG,
8165                                                     const SDLoc &dl) const {
8166   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8167   SDValue Src = Op.getOperand(0);
8168 
8169   if (Src.getValueType() == MVT::f32)
8170     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8171 
8172   SDValue Tmp;
8173   switch (Op.getSimpleValueType().SimpleTy) {
8174   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8175   case MVT::i32:
8176     Tmp = DAG.getNode(
8177         Op.getOpcode() == ISD::FP_TO_SINT
8178             ? PPCISD::FCTIWZ
8179             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8180         dl, MVT::f64, Src);
8181     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8182     break;
8183   case MVT::i64:
8184     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8185            "i64 FP_TO_UINT is supported only with FPCVT");
8186     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8187                                                         PPCISD::FCTIDUZ,
8188                       dl, MVT::f64, Src);
8189     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8190     break;
8191   }
8192   return Tmp;
8193 }
8194 
8195 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8196                                           const SDLoc &dl) const {
8197 
8198   // FP to INT conversions are legal for f128.
8199   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8200     return Op;
8201 
8202   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8203   // PPC (the libcall is not available).
8204   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8205     if (Op.getValueType() == MVT::i32) {
8206       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8207         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8208                                  MVT::f64, Op.getOperand(0),
8209                                  DAG.getIntPtrConstant(0, dl));
8210         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8211                                  MVT::f64, Op.getOperand(0),
8212                                  DAG.getIntPtrConstant(1, dl));
8213 
8214         // Add the two halves of the long double in round-to-zero mode.
8215         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8216 
8217         // Now use a smaller FP_TO_SINT.
8218         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8219       }
8220       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8221         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8222         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8223         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8224         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8225         // FIXME: generated code sucks.
8226         // TODO: Are there fast-math-flags to propagate to this FSUB?
8227         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8228                                    Op.getOperand(0), Tmp);
8229         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8230         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8231                            DAG.getConstant(0x80000000, dl, MVT::i32));
8232         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8233                                     Op.getOperand(0));
8234         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8235                                ISD::SETGE);
8236       }
8237     }
8238 
8239     return SDValue();
8240   }
8241 
8242   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8243     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8244 
8245   ReuseLoadInfo RLI;
8246   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8247 
8248   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8249                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8250 }
8251 
8252 // We're trying to insert a regular store, S, and then a load, L. If the
8253 // incoming value, O, is a load, we might just be able to have our load use the
8254 // address used by O. However, we don't know if anything else will store to
8255 // that address before we can load from it. To prevent this situation, we need
8256 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8257 // the same chain operand as O, we create a token factor from the chain results
8258 // of O and L, and we replace all uses of O's chain result with that token
8259 // factor (see spliceIntoChain below for this last part).
8260 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8261                                             ReuseLoadInfo &RLI,
8262                                             SelectionDAG &DAG,
8263                                             ISD::LoadExtType ET) const {
8264   SDLoc dl(Op);
8265   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8266                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8267   if (ET == ISD::NON_EXTLOAD &&
8268       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8269       isOperationLegalOrCustom(Op.getOpcode(),
8270                                Op.getOperand(0).getValueType())) {
8271 
8272     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8273     return true;
8274   }
8275 
8276   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8277   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8278       LD->isNonTemporal())
8279     return false;
8280   if (LD->getMemoryVT() != MemVT)
8281     return false;
8282 
8283   RLI.Ptr = LD->getBasePtr();
8284   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8285     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8286            "Non-pre-inc AM on PPC?");
8287     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8288                           LD->getOffset());
8289   }
8290 
8291   RLI.Chain = LD->getChain();
8292   RLI.MPI = LD->getPointerInfo();
8293   RLI.IsDereferenceable = LD->isDereferenceable();
8294   RLI.IsInvariant = LD->isInvariant();
8295   RLI.Alignment = LD->getAlign();
8296   RLI.AAInfo = LD->getAAInfo();
8297   RLI.Ranges = LD->getRanges();
8298 
8299   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8300   return true;
8301 }
8302 
8303 // Given the head of the old chain, ResChain, insert a token factor containing
8304 // it and NewResChain, and make users of ResChain now be users of that token
8305 // factor.
8306 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8307 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8308                                         SDValue NewResChain,
8309                                         SelectionDAG &DAG) const {
8310   if (!ResChain)
8311     return;
8312 
8313   SDLoc dl(NewResChain);
8314 
8315   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8316                            NewResChain, DAG.getUNDEF(MVT::Other));
8317   assert(TF.getNode() != NewResChain.getNode() &&
8318          "A new TF really is required here");
8319 
8320   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8321   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8322 }
8323 
8324 /// Analyze profitability of direct move
8325 /// prefer float load to int load plus direct move
8326 /// when there is no integer use of int load
8327 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8328   SDNode *Origin = Op.getOperand(0).getNode();
8329   if (Origin->getOpcode() != ISD::LOAD)
8330     return true;
8331 
8332   // If there is no LXSIBZX/LXSIHZX, like Power8,
8333   // prefer direct move if the memory size is 1 or 2 bytes.
8334   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8335   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8336     return true;
8337 
8338   for (SDNode::use_iterator UI = Origin->use_begin(),
8339                             UE = Origin->use_end();
8340        UI != UE; ++UI) {
8341 
8342     // Only look at the users of the loaded value.
8343     if (UI.getUse().get().getResNo() != 0)
8344       continue;
8345 
8346     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8347         UI->getOpcode() != ISD::UINT_TO_FP)
8348       return true;
8349   }
8350 
8351   return false;
8352 }
8353 
8354 /// Custom lowers integer to floating point conversions to use
8355 /// the direct move instructions available in ISA 2.07 to avoid the
8356 /// need for load/store combinations.
8357 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8358                                                     SelectionDAG &DAG,
8359                                                     const SDLoc &dl) const {
8360   assert((Op.getValueType() == MVT::f32 ||
8361           Op.getValueType() == MVT::f64) &&
8362          "Invalid floating point type as target of conversion");
8363   assert(Subtarget.hasFPCVT() &&
8364          "Int to FP conversions with direct moves require FPCVT");
8365   SDValue FP;
8366   SDValue Src = Op.getOperand(0);
8367   bool SinglePrec = Op.getValueType() == MVT::f32;
8368   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8369   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8370   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8371                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8372 
8373   if (WordInt) {
8374     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8375                      dl, MVT::f64, Src);
8376     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8377   }
8378   else {
8379     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8380     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8381   }
8382 
8383   return FP;
8384 }
8385 
8386 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8387 
8388   EVT VecVT = Vec.getValueType();
8389   assert(VecVT.isVector() && "Expected a vector type.");
8390   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8391 
8392   EVT EltVT = VecVT.getVectorElementType();
8393   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8394   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8395 
8396   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8397   SmallVector<SDValue, 16> Ops(NumConcat);
8398   Ops[0] = Vec;
8399   SDValue UndefVec = DAG.getUNDEF(VecVT);
8400   for (unsigned i = 1; i < NumConcat; ++i)
8401     Ops[i] = UndefVec;
8402 
8403   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8404 }
8405 
8406 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8407                                                 const SDLoc &dl) const {
8408 
8409   unsigned Opc = Op.getOpcode();
8410   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8411          "Unexpected conversion type");
8412   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8413          "Supports conversions to v2f64/v4f32 only.");
8414 
8415   bool SignedConv = Opc == ISD::SINT_TO_FP;
8416   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8417 
8418   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8419   EVT WideVT = Wide.getValueType();
8420   unsigned WideNumElts = WideVT.getVectorNumElements();
8421   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8422 
8423   SmallVector<int, 16> ShuffV;
8424   for (unsigned i = 0; i < WideNumElts; ++i)
8425     ShuffV.push_back(i + WideNumElts);
8426 
8427   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8428   int SaveElts = FourEltRes ? 4 : 2;
8429   if (Subtarget.isLittleEndian())
8430     for (int i = 0; i < SaveElts; i++)
8431       ShuffV[i * Stride] = i;
8432   else
8433     for (int i = 1; i <= SaveElts; i++)
8434       ShuffV[i * Stride - 1] = i - 1;
8435 
8436   SDValue ShuffleSrc2 =
8437       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8438   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8439 
8440   SDValue Extend;
8441   if (SignedConv) {
8442     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8443     EVT ExtVT = Op.getOperand(0).getValueType();
8444     if (Subtarget.hasP9Altivec())
8445       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8446                                IntermediateVT.getVectorNumElements());
8447 
8448     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8449                          DAG.getValueType(ExtVT));
8450   } else
8451     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8452 
8453   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8454 }
8455 
8456 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8457                                           SelectionDAG &DAG) const {
8458   SDLoc dl(Op);
8459 
8460   EVT InVT = Op.getOperand(0).getValueType();
8461   EVT OutVT = Op.getValueType();
8462   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8463       isOperationCustom(Op.getOpcode(), InVT))
8464     return LowerINT_TO_FPVector(Op, DAG, dl);
8465 
8466   // Conversions to f128 are legal.
8467   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8468     return Op;
8469 
8470   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8471     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8472       return SDValue();
8473 
8474     SDValue Value = Op.getOperand(0);
8475     // The values are now known to be -1 (false) or 1 (true). To convert this
8476     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8477     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8478     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8479 
8480     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8481 
8482     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8483 
8484     if (Op.getValueType() != MVT::v4f64)
8485       Value = DAG.getNode(ISD::FP_ROUND, dl,
8486                           Op.getValueType(), Value,
8487                           DAG.getIntPtrConstant(1, dl));
8488     return Value;
8489   }
8490 
8491   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8492   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8493     return SDValue();
8494 
8495   if (Op.getOperand(0).getValueType() == MVT::i1)
8496     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8497                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8498                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8499 
8500   // If we have direct moves, we can do all the conversion, skip the store/load
8501   // however, without FPCVT we can't do most conversions.
8502   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8503       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8504     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8505 
8506   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8507          "UINT_TO_FP is supported only with FPCVT");
8508 
8509   // If we have FCFIDS, then use it when converting to single-precision.
8510   // Otherwise, convert to double-precision and then round.
8511   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8512                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8513                                                             : PPCISD::FCFIDS)
8514                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8515                                                             : PPCISD::FCFID);
8516   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8517                   ? MVT::f32
8518                   : MVT::f64;
8519 
8520   if (Op.getOperand(0).getValueType() == MVT::i64) {
8521     SDValue SINT = Op.getOperand(0);
8522     // When converting to single-precision, we actually need to convert
8523     // to double-precision first and then round to single-precision.
8524     // To avoid double-rounding effects during that operation, we have
8525     // to prepare the input operand.  Bits that might be truncated when
8526     // converting to double-precision are replaced by a bit that won't
8527     // be lost at this stage, but is below the single-precision rounding
8528     // position.
8529     //
8530     // However, if -enable-unsafe-fp-math is in effect, accept double
8531     // rounding to avoid the extra overhead.
8532     if (Op.getValueType() == MVT::f32 &&
8533         !Subtarget.hasFPCVT() &&
8534         !DAG.getTarget().Options.UnsafeFPMath) {
8535 
8536       // Twiddle input to make sure the low 11 bits are zero.  (If this
8537       // is the case, we are guaranteed the value will fit into the 53 bit
8538       // mantissa of an IEEE double-precision value without rounding.)
8539       // If any of those low 11 bits were not zero originally, make sure
8540       // bit 12 (value 2048) is set instead, so that the final rounding
8541       // to single-precision gets the correct result.
8542       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8543                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8544       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8545                           Round, DAG.getConstant(2047, dl, MVT::i64));
8546       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8547       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8548                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8549 
8550       // However, we cannot use that value unconditionally: if the magnitude
8551       // of the input value is small, the bit-twiddling we did above might
8552       // end up visibly changing the output.  Fortunately, in that case, we
8553       // don't need to twiddle bits since the original input will convert
8554       // exactly to double-precision floating-point already.  Therefore,
8555       // construct a conditional to use the original value if the top 11
8556       // bits are all sign-bit copies, and use the rounded value computed
8557       // above otherwise.
8558       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8559                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8560       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8561                          Cond, DAG.getConstant(1, dl, MVT::i64));
8562       Cond = DAG.getSetCC(
8563           dl,
8564           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8565           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8566 
8567       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8568     }
8569 
8570     ReuseLoadInfo RLI;
8571     SDValue Bits;
8572 
8573     MachineFunction &MF = DAG.getMachineFunction();
8574     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8575       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8576                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8577       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8578     } else if (Subtarget.hasLFIWAX() &&
8579                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8580       MachineMemOperand *MMO =
8581         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8582                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8583       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8584       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8585                                      DAG.getVTList(MVT::f64, MVT::Other),
8586                                      Ops, MVT::i32, MMO);
8587       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8588     } else if (Subtarget.hasFPCVT() &&
8589                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8590       MachineMemOperand *MMO =
8591         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8592                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8593       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8594       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8595                                      DAG.getVTList(MVT::f64, MVT::Other),
8596                                      Ops, MVT::i32, MMO);
8597       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8598     } else if (((Subtarget.hasLFIWAX() &&
8599                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8600                 (Subtarget.hasFPCVT() &&
8601                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8602                SINT.getOperand(0).getValueType() == MVT::i32) {
8603       MachineFrameInfo &MFI = MF.getFrameInfo();
8604       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8605 
8606       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8607       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8608 
8609       SDValue Store =
8610           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8611                        MachinePointerInfo::getFixedStack(
8612                            DAG.getMachineFunction(), FrameIdx));
8613 
8614       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8615              "Expected an i32 store");
8616 
8617       RLI.Ptr = FIdx;
8618       RLI.Chain = Store;
8619       RLI.MPI =
8620           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8621       RLI.Alignment = Align(4);
8622 
8623       MachineMemOperand *MMO =
8624         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8625                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8626       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8627       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8628                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8629                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8630                                      Ops, MVT::i32, MMO);
8631     } else
8632       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8633 
8634     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8635 
8636     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8637       FP = DAG.getNode(ISD::FP_ROUND, dl,
8638                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8639     return FP;
8640   }
8641 
8642   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8643          "Unhandled INT_TO_FP type in custom expander!");
8644   // Since we only generate this in 64-bit mode, we can take advantage of
8645   // 64-bit registers.  In particular, sign extend the input value into the
8646   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8647   // then lfd it and fcfid it.
8648   MachineFunction &MF = DAG.getMachineFunction();
8649   MachineFrameInfo &MFI = MF.getFrameInfo();
8650   EVT PtrVT = getPointerTy(MF.getDataLayout());
8651 
8652   SDValue Ld;
8653   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8654     ReuseLoadInfo RLI;
8655     bool ReusingLoad;
8656     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8657                                             DAG))) {
8658       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8659       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8660 
8661       SDValue Store =
8662           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8663                        MachinePointerInfo::getFixedStack(
8664                            DAG.getMachineFunction(), FrameIdx));
8665 
8666       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8667              "Expected an i32 store");
8668 
8669       RLI.Ptr = FIdx;
8670       RLI.Chain = Store;
8671       RLI.MPI =
8672           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8673       RLI.Alignment = Align(4);
8674     }
8675 
8676     MachineMemOperand *MMO =
8677       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8678                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8679     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8680     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8681                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8682                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8683                                  Ops, MVT::i32, MMO);
8684     if (ReusingLoad)
8685       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8686   } else {
8687     assert(Subtarget.isPPC64() &&
8688            "i32->FP without LFIWAX supported only on PPC64");
8689 
8690     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8691     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8692 
8693     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8694                                 Op.getOperand(0));
8695 
8696     // STD the extended value into the stack slot.
8697     SDValue Store = DAG.getStore(
8698         DAG.getEntryNode(), dl, Ext64, FIdx,
8699         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8700 
8701     // Load the value as a double.
8702     Ld = DAG.getLoad(
8703         MVT::f64, dl, Store, FIdx,
8704         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8705   }
8706 
8707   // FCFID it and return it.
8708   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8709   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8710     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8711                      DAG.getIntPtrConstant(0, dl));
8712   return FP;
8713 }
8714 
8715 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8716                                             SelectionDAG &DAG) const {
8717   SDLoc dl(Op);
8718   /*
8719    The rounding mode is in bits 30:31 of FPSR, and has the following
8720    settings:
8721      00 Round to nearest
8722      01 Round to 0
8723      10 Round to +inf
8724      11 Round to -inf
8725 
8726   FLT_ROUNDS, on the other hand, expects the following:
8727     -1 Undefined
8728      0 Round to 0
8729      1 Round to nearest
8730      2 Round to +inf
8731      3 Round to -inf
8732 
8733   To perform the conversion, we do:
8734     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8735   */
8736 
8737   MachineFunction &MF = DAG.getMachineFunction();
8738   EVT VT = Op.getValueType();
8739   EVT PtrVT = getPointerTy(MF.getDataLayout());
8740 
8741   // Save FP Control Word to register
8742   SDValue Chain = Op.getOperand(0);
8743   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8744   Chain = MFFS.getValue(1);
8745 
8746   // Save FP register to stack slot
8747   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8748   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8749   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8750 
8751   // Load FP Control Word from low 32 bits of stack slot.
8752   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8753   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8754   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8755   Chain = CWD.getValue(1);
8756 
8757   // Transform as necessary
8758   SDValue CWD1 =
8759     DAG.getNode(ISD::AND, dl, MVT::i32,
8760                 CWD, DAG.getConstant(3, dl, MVT::i32));
8761   SDValue CWD2 =
8762     DAG.getNode(ISD::SRL, dl, MVT::i32,
8763                 DAG.getNode(ISD::AND, dl, MVT::i32,
8764                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8765                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8766                             DAG.getConstant(3, dl, MVT::i32)),
8767                 DAG.getConstant(1, dl, MVT::i32));
8768 
8769   SDValue RetVal =
8770     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8771 
8772   RetVal =
8773       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8774                   dl, VT, RetVal);
8775 
8776   return DAG.getMergeValues({RetVal, Chain}, dl);
8777 }
8778 
8779 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8780   EVT VT = Op.getValueType();
8781   unsigned BitWidth = VT.getSizeInBits();
8782   SDLoc dl(Op);
8783   assert(Op.getNumOperands() == 3 &&
8784          VT == Op.getOperand(1).getValueType() &&
8785          "Unexpected SHL!");
8786 
8787   // Expand into a bunch of logical ops.  Note that these ops
8788   // depend on the PPC behavior for oversized shift amounts.
8789   SDValue Lo = Op.getOperand(0);
8790   SDValue Hi = Op.getOperand(1);
8791   SDValue Amt = Op.getOperand(2);
8792   EVT AmtVT = Amt.getValueType();
8793 
8794   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8795                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8796   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8797   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8798   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8799   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8800                              DAG.getConstant(-BitWidth, dl, AmtVT));
8801   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8802   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8803   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8804   SDValue OutOps[] = { OutLo, OutHi };
8805   return DAG.getMergeValues(OutOps, dl);
8806 }
8807 
8808 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8809   EVT VT = Op.getValueType();
8810   SDLoc dl(Op);
8811   unsigned BitWidth = VT.getSizeInBits();
8812   assert(Op.getNumOperands() == 3 &&
8813          VT == Op.getOperand(1).getValueType() &&
8814          "Unexpected SRL!");
8815 
8816   // Expand into a bunch of logical ops.  Note that these ops
8817   // depend on the PPC behavior for oversized shift amounts.
8818   SDValue Lo = Op.getOperand(0);
8819   SDValue Hi = Op.getOperand(1);
8820   SDValue Amt = Op.getOperand(2);
8821   EVT AmtVT = Amt.getValueType();
8822 
8823   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8824                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8825   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8826   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8827   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8828   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8829                              DAG.getConstant(-BitWidth, dl, AmtVT));
8830   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8831   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8832   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8833   SDValue OutOps[] = { OutLo, OutHi };
8834   return DAG.getMergeValues(OutOps, dl);
8835 }
8836 
8837 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8838   SDLoc dl(Op);
8839   EVT VT = Op.getValueType();
8840   unsigned BitWidth = VT.getSizeInBits();
8841   assert(Op.getNumOperands() == 3 &&
8842          VT == Op.getOperand(1).getValueType() &&
8843          "Unexpected SRA!");
8844 
8845   // Expand into a bunch of logical ops, followed by a select_cc.
8846   SDValue Lo = Op.getOperand(0);
8847   SDValue Hi = Op.getOperand(1);
8848   SDValue Amt = Op.getOperand(2);
8849   EVT AmtVT = Amt.getValueType();
8850 
8851   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8852                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8853   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8854   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8855   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8856   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8857                              DAG.getConstant(-BitWidth, dl, AmtVT));
8858   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8859   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8860   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8861                                   Tmp4, Tmp6, ISD::SETLE);
8862   SDValue OutOps[] = { OutLo, OutHi };
8863   return DAG.getMergeValues(OutOps, dl);
8864 }
8865 
8866 //===----------------------------------------------------------------------===//
8867 // Vector related lowering.
8868 //
8869 
8870 /// BuildSplatI - Build a canonical splati of Val with an element size of
8871 /// SplatSize.  Cast the result to VT.
8872 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8873                            SelectionDAG &DAG, const SDLoc &dl) {
8874   static const MVT VTys[] = { // canonical VT to use for each size.
8875     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8876   };
8877 
8878   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8879 
8880   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8881   if (Val == -1)
8882     SplatSize = 1;
8883 
8884   EVT CanonicalVT = VTys[SplatSize-1];
8885 
8886   // Build a canonical splat for this value.
8887   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8888 }
8889 
8890 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8891 /// specified intrinsic ID.
8892 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8893                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8894   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8895   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8896                      DAG.getConstant(IID, dl, MVT::i32), Op);
8897 }
8898 
8899 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8900 /// specified intrinsic ID.
8901 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8902                                 SelectionDAG &DAG, const SDLoc &dl,
8903                                 EVT DestVT = MVT::Other) {
8904   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8905   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8906                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8907 }
8908 
8909 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8910 /// specified intrinsic ID.
8911 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8912                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8913                                 EVT DestVT = MVT::Other) {
8914   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8915   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8916                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8917 }
8918 
8919 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8920 /// amount.  The result has the specified value type.
8921 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8922                            SelectionDAG &DAG, const SDLoc &dl) {
8923   // Force LHS/RHS to be the right type.
8924   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8925   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8926 
8927   int Ops[16];
8928   for (unsigned i = 0; i != 16; ++i)
8929     Ops[i] = i + Amt;
8930   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8931   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8932 }
8933 
8934 /// Do we have an efficient pattern in a .td file for this node?
8935 ///
8936 /// \param V - pointer to the BuildVectorSDNode being matched
8937 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8938 ///
8939 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8940 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8941 /// the opposite is true (expansion is beneficial) are:
8942 /// - The node builds a vector out of integers that are not 32 or 64-bits
8943 /// - The node builds a vector out of constants
8944 /// - The node is a "load-and-splat"
8945 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8946 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8947                                             bool HasDirectMove,
8948                                             bool HasP8Vector) {
8949   EVT VecVT = V->getValueType(0);
8950   bool RightType = VecVT == MVT::v2f64 ||
8951     (HasP8Vector && VecVT == MVT::v4f32) ||
8952     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8953   if (!RightType)
8954     return false;
8955 
8956   bool IsSplat = true;
8957   bool IsLoad = false;
8958   SDValue Op0 = V->getOperand(0);
8959 
8960   // This function is called in a block that confirms the node is not a constant
8961   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8962   // different constants.
8963   if (V->isConstant())
8964     return false;
8965   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8966     if (V->getOperand(i).isUndef())
8967       return false;
8968     // We want to expand nodes that represent load-and-splat even if the
8969     // loaded value is a floating point truncation or conversion to int.
8970     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8971         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8972          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8973         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8974          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8975         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8976          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8977       IsLoad = true;
8978     // If the operands are different or the input is not a load and has more
8979     // uses than just this BV node, then it isn't a splat.
8980     if (V->getOperand(i) != Op0 ||
8981         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8982       IsSplat = false;
8983   }
8984   return !(IsSplat && IsLoad);
8985 }
8986 
8987 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8988 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8989 
8990   SDLoc dl(Op);
8991   SDValue Op0 = Op->getOperand(0);
8992 
8993   if (!EnableQuadPrecision ||
8994       (Op.getValueType() != MVT::f128 ) ||
8995       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8996       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8997       (Op0.getOperand(1).getValueType() != MVT::i64))
8998     return SDValue();
8999 
9000   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9001                      Op0.getOperand(1));
9002 }
9003 
9004 static const SDValue *getNormalLoadInput(const SDValue &Op) {
9005   const SDValue *InputLoad = &Op;
9006   if (InputLoad->getOpcode() == ISD::BITCAST)
9007     InputLoad = &InputLoad->getOperand(0);
9008   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
9009     InputLoad = &InputLoad->getOperand(0);
9010   if (InputLoad->getOpcode() != ISD::LOAD)
9011     return nullptr;
9012   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9013   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9014 }
9015 
9016 // If this is a case we can't handle, return null and let the default
9017 // expansion code take care of it.  If we CAN select this case, and if it
9018 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9019 // this case more efficiently than a constant pool load, lower it to the
9020 // sequence of ops that should be used.
9021 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9022                                              SelectionDAG &DAG) const {
9023   SDLoc dl(Op);
9024   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9025   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9026 
9027   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
9028     // We first build an i32 vector, load it into a QPX register,
9029     // then convert it to a floating-point vector and compare it
9030     // to a zero vector to get the boolean result.
9031     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9032     int FrameIdx = MFI.CreateStackObject(16, 16, false);
9033     MachinePointerInfo PtrInfo =
9034         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9035     EVT PtrVT = getPointerTy(DAG.getDataLayout());
9036     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9037 
9038     assert(BVN->getNumOperands() == 4 &&
9039       "BUILD_VECTOR for v4i1 does not have 4 operands");
9040 
9041     bool IsConst = true;
9042     for (unsigned i = 0; i < 4; ++i) {
9043       if (BVN->getOperand(i).isUndef()) continue;
9044       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
9045         IsConst = false;
9046         break;
9047       }
9048     }
9049 
9050     if (IsConst) {
9051       Constant *One =
9052         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9053       Constant *NegOne =
9054         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9055 
9056       Constant *CV[4];
9057       for (unsigned i = 0; i < 4; ++i) {
9058         if (BVN->getOperand(i).isUndef())
9059           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9060         else if (isNullConstant(BVN->getOperand(i)))
9061           CV[i] = NegOne;
9062         else
9063           CV[i] = One;
9064       }
9065 
9066       Constant *CP = ConstantVector::get(CV);
9067       SDValue CPIdx =
9068           DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16));
9069 
9070       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9071       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9072       return DAG.getMemIntrinsicNode(
9073           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9074           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9075     }
9076 
9077     SmallVector<SDValue, 4> Stores;
9078     for (unsigned i = 0; i < 4; ++i) {
9079       if (BVN->getOperand(i).isUndef()) continue;
9080 
9081       unsigned Offset = 4*i;
9082       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9083       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9084 
9085       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9086       if (StoreSize > 4) {
9087         Stores.push_back(
9088             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9089                               PtrInfo.getWithOffset(Offset), MVT::i32));
9090       } else {
9091         SDValue StoreValue = BVN->getOperand(i);
9092         if (StoreSize < 4)
9093           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9094 
9095         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9096                                       PtrInfo.getWithOffset(Offset)));
9097       }
9098     }
9099 
9100     SDValue StoreChain;
9101     if (!Stores.empty())
9102       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9103     else
9104       StoreChain = DAG.getEntryNode();
9105 
9106     // Now load from v4i32 into the QPX register; this will extend it to
9107     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9108     // is typed as v4f64 because the QPX register integer states are not
9109     // explicitly represented.
9110 
9111     SDValue Ops[] = {StoreChain,
9112                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9113                      FIdx};
9114     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9115 
9116     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9117       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9118     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9119       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9120       LoadedVect);
9121 
9122     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9123 
9124     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9125   }
9126 
9127   // All other QPX vectors are handled by generic code.
9128   if (Subtarget.hasQPX())
9129     return SDValue();
9130 
9131   // Check if this is a splat of a constant value.
9132   APInt APSplatBits, APSplatUndef;
9133   unsigned SplatBitSize;
9134   bool HasAnyUndefs;
9135   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9136                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9137       SplatBitSize > 32) {
9138 
9139     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9140     // Handle load-and-splat patterns as we have instructions that will do this
9141     // in one go.
9142     if (InputLoad && DAG.isSplatValue(Op, true)) {
9143       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9144 
9145       // We have handling for 4 and 8 byte elements.
9146       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9147 
9148       // Checking for a single use of this load, we have to check for vector
9149       // width (128 bits) / ElementSize uses (since each operand of the
9150       // BUILD_VECTOR is a separate use of the value.
9151       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9152           ((Subtarget.hasVSX() && ElementSize == 64) ||
9153            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9154         SDValue Ops[] = {
9155           LD->getChain(),    // Chain
9156           LD->getBasePtr(),  // Ptr
9157           DAG.getValueType(Op.getValueType()) // VT
9158         };
9159         return
9160           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9161                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9162                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9163       }
9164     }
9165 
9166     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9167     // lowered to VSX instructions under certain conditions.
9168     // Without VSX, there is no pattern more efficient than expanding the node.
9169     if (Subtarget.hasVSX() &&
9170         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9171                                         Subtarget.hasP8Vector()))
9172       return Op;
9173     return SDValue();
9174   }
9175 
9176   unsigned SplatBits = APSplatBits.getZExtValue();
9177   unsigned SplatUndef = APSplatUndef.getZExtValue();
9178   unsigned SplatSize = SplatBitSize / 8;
9179 
9180   // First, handle single instruction cases.
9181 
9182   // All zeros?
9183   if (SplatBits == 0) {
9184     // Canonicalize all zero vectors to be v4i32.
9185     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9186       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9187       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9188     }
9189     return Op;
9190   }
9191 
9192   // We have XXSPLTIB for constant splats one byte wide
9193   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9194   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9195   if (Subtarget.hasP9Vector() && SplatSize == 1)
9196     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9197 
9198   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9199   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9200                     (32-SplatBitSize));
9201   if (SextVal >= -16 && SextVal <= 15)
9202     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9203 
9204   // Two instruction sequences.
9205 
9206   // If this value is in the range [-32,30] and is even, use:
9207   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9208   // If this value is in the range [17,31] and is odd, use:
9209   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9210   // If this value is in the range [-31,-17] and is odd, use:
9211   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9212   // Note the last two are three-instruction sequences.
9213   if (SextVal >= -32 && SextVal <= 31) {
9214     // To avoid having these optimizations undone by constant folding,
9215     // we convert to a pseudo that will be expanded later into one of
9216     // the above forms.
9217     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9218     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9219               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9220     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9221     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9222     if (VT == Op.getValueType())
9223       return RetVal;
9224     else
9225       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9226   }
9227 
9228   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9229   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9230   // for fneg/fabs.
9231   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9232     // Make -1 and vspltisw -1:
9233     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9234 
9235     // Make the VSLW intrinsic, computing 0x8000_0000.
9236     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9237                                    OnesV, DAG, dl);
9238 
9239     // xor by OnesV to invert it.
9240     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9241     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9242   }
9243 
9244   // Check to see if this is a wide variety of vsplti*, binop self cases.
9245   static const signed char SplatCsts[] = {
9246     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9247     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9248   };
9249 
9250   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9251     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9252     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9253     int i = SplatCsts[idx];
9254 
9255     // Figure out what shift amount will be used by altivec if shifted by i in
9256     // this splat size.
9257     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9258 
9259     // vsplti + shl self.
9260     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9261       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9262       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9263         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9264         Intrinsic::ppc_altivec_vslw
9265       };
9266       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9267       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9268     }
9269 
9270     // vsplti + srl self.
9271     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9272       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9273       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9274         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9275         Intrinsic::ppc_altivec_vsrw
9276       };
9277       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9278       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9279     }
9280 
9281     // vsplti + sra self.
9282     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9283       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9284       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9285         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9286         Intrinsic::ppc_altivec_vsraw
9287       };
9288       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9289       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9290     }
9291 
9292     // vsplti + rol self.
9293     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9294                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9295       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9296       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9297         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9298         Intrinsic::ppc_altivec_vrlw
9299       };
9300       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9301       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9302     }
9303 
9304     // t = vsplti c, result = vsldoi t, t, 1
9305     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9306       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9307       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9308       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9309     }
9310     // t = vsplti c, result = vsldoi t, t, 2
9311     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9312       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9313       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9314       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9315     }
9316     // t = vsplti c, result = vsldoi t, t, 3
9317     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9318       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9319       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9320       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9321     }
9322   }
9323 
9324   return SDValue();
9325 }
9326 
9327 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9328 /// the specified operations to build the shuffle.
9329 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9330                                       SDValue RHS, SelectionDAG &DAG,
9331                                       const SDLoc &dl) {
9332   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9333   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9334   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9335 
9336   enum {
9337     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9338     OP_VMRGHW,
9339     OP_VMRGLW,
9340     OP_VSPLTISW0,
9341     OP_VSPLTISW1,
9342     OP_VSPLTISW2,
9343     OP_VSPLTISW3,
9344     OP_VSLDOI4,
9345     OP_VSLDOI8,
9346     OP_VSLDOI12
9347   };
9348 
9349   if (OpNum == OP_COPY) {
9350     if (LHSID == (1*9+2)*9+3) return LHS;
9351     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9352     return RHS;
9353   }
9354 
9355   SDValue OpLHS, OpRHS;
9356   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9357   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9358 
9359   int ShufIdxs[16];
9360   switch (OpNum) {
9361   default: llvm_unreachable("Unknown i32 permute!");
9362   case OP_VMRGHW:
9363     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9364     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9365     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9366     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9367     break;
9368   case OP_VMRGLW:
9369     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9370     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9371     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9372     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9373     break;
9374   case OP_VSPLTISW0:
9375     for (unsigned i = 0; i != 16; ++i)
9376       ShufIdxs[i] = (i&3)+0;
9377     break;
9378   case OP_VSPLTISW1:
9379     for (unsigned i = 0; i != 16; ++i)
9380       ShufIdxs[i] = (i&3)+4;
9381     break;
9382   case OP_VSPLTISW2:
9383     for (unsigned i = 0; i != 16; ++i)
9384       ShufIdxs[i] = (i&3)+8;
9385     break;
9386   case OP_VSPLTISW3:
9387     for (unsigned i = 0; i != 16; ++i)
9388       ShufIdxs[i] = (i&3)+12;
9389     break;
9390   case OP_VSLDOI4:
9391     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9392   case OP_VSLDOI8:
9393     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9394   case OP_VSLDOI12:
9395     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9396   }
9397   EVT VT = OpLHS.getValueType();
9398   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9399   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9400   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9401   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9402 }
9403 
9404 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9405 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9406 /// SDValue.
9407 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9408                                            SelectionDAG &DAG) const {
9409   const unsigned BytesInVector = 16;
9410   bool IsLE = Subtarget.isLittleEndian();
9411   SDLoc dl(N);
9412   SDValue V1 = N->getOperand(0);
9413   SDValue V2 = N->getOperand(1);
9414   unsigned ShiftElts = 0, InsertAtByte = 0;
9415   bool Swap = false;
9416 
9417   // Shifts required to get the byte we want at element 7.
9418   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9419                                    0, 15, 14, 13, 12, 11, 10, 9};
9420   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9421                                 1, 2,  3,  4,  5,  6,  7,  8};
9422 
9423   ArrayRef<int> Mask = N->getMask();
9424   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9425 
9426   // For each mask element, find out if we're just inserting something
9427   // from V2 into V1 or vice versa.
9428   // Possible permutations inserting an element from V2 into V1:
9429   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9430   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9431   //   ...
9432   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9433   // Inserting from V1 into V2 will be similar, except mask range will be
9434   // [16,31].
9435 
9436   bool FoundCandidate = false;
9437   // If both vector operands for the shuffle are the same vector, the mask
9438   // will contain only elements from the first one and the second one will be
9439   // undef.
9440   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9441   // Go through the mask of half-words to find an element that's being moved
9442   // from one vector to the other.
9443   for (unsigned i = 0; i < BytesInVector; ++i) {
9444     unsigned CurrentElement = Mask[i];
9445     // If 2nd operand is undefined, we should only look for element 7 in the
9446     // Mask.
9447     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9448       continue;
9449 
9450     bool OtherElementsInOrder = true;
9451     // Examine the other elements in the Mask to see if they're in original
9452     // order.
9453     for (unsigned j = 0; j < BytesInVector; ++j) {
9454       if (j == i)
9455         continue;
9456       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9457       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9458       // in which we always assume we're always picking from the 1st operand.
9459       int MaskOffset =
9460           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9461       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9462         OtherElementsInOrder = false;
9463         break;
9464       }
9465     }
9466     // If other elements are in original order, we record the number of shifts
9467     // we need to get the element we want into element 7. Also record which byte
9468     // in the vector we should insert into.
9469     if (OtherElementsInOrder) {
9470       // If 2nd operand is undefined, we assume no shifts and no swapping.
9471       if (V2.isUndef()) {
9472         ShiftElts = 0;
9473         Swap = false;
9474       } else {
9475         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9476         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9477                          : BigEndianShifts[CurrentElement & 0xF];
9478         Swap = CurrentElement < BytesInVector;
9479       }
9480       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9481       FoundCandidate = true;
9482       break;
9483     }
9484   }
9485 
9486   if (!FoundCandidate)
9487     return SDValue();
9488 
9489   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9490   // optionally with VECSHL if shift is required.
9491   if (Swap)
9492     std::swap(V1, V2);
9493   if (V2.isUndef())
9494     V2 = V1;
9495   if (ShiftElts) {
9496     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9497                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9498     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9499                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9500   }
9501   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9502                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9503 }
9504 
9505 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9506 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9507 /// SDValue.
9508 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9509                                            SelectionDAG &DAG) const {
9510   const unsigned NumHalfWords = 8;
9511   const unsigned BytesInVector = NumHalfWords * 2;
9512   // Check that the shuffle is on half-words.
9513   if (!isNByteElemShuffleMask(N, 2, 1))
9514     return SDValue();
9515 
9516   bool IsLE = Subtarget.isLittleEndian();
9517   SDLoc dl(N);
9518   SDValue V1 = N->getOperand(0);
9519   SDValue V2 = N->getOperand(1);
9520   unsigned ShiftElts = 0, InsertAtByte = 0;
9521   bool Swap = false;
9522 
9523   // Shifts required to get the half-word we want at element 3.
9524   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9525   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9526 
9527   uint32_t Mask = 0;
9528   uint32_t OriginalOrderLow = 0x1234567;
9529   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9530   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9531   // 32-bit space, only need 4-bit nibbles per element.
9532   for (unsigned i = 0; i < NumHalfWords; ++i) {
9533     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9534     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9535   }
9536 
9537   // For each mask element, find out if we're just inserting something
9538   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9539   // from V2 into V1:
9540   //   X, 1, 2, 3, 4, 5, 6, 7
9541   //   0, X, 2, 3, 4, 5, 6, 7
9542   //   0, 1, X, 3, 4, 5, 6, 7
9543   //   0, 1, 2, X, 4, 5, 6, 7
9544   //   0, 1, 2, 3, X, 5, 6, 7
9545   //   0, 1, 2, 3, 4, X, 6, 7
9546   //   0, 1, 2, 3, 4, 5, X, 7
9547   //   0, 1, 2, 3, 4, 5, 6, X
9548   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9549 
9550   bool FoundCandidate = false;
9551   // Go through the mask of half-words to find an element that's being moved
9552   // from one vector to the other.
9553   for (unsigned i = 0; i < NumHalfWords; ++i) {
9554     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9555     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9556     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9557     uint32_t TargetOrder = 0x0;
9558 
9559     // If both vector operands for the shuffle are the same vector, the mask
9560     // will contain only elements from the first one and the second one will be
9561     // undef.
9562     if (V2.isUndef()) {
9563       ShiftElts = 0;
9564       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9565       TargetOrder = OriginalOrderLow;
9566       Swap = false;
9567       // Skip if not the correct element or mask of other elements don't equal
9568       // to our expected order.
9569       if (MaskOneElt == VINSERTHSrcElem &&
9570           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9571         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9572         FoundCandidate = true;
9573         break;
9574       }
9575     } else { // If both operands are defined.
9576       // Target order is [8,15] if the current mask is between [0,7].
9577       TargetOrder =
9578           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9579       // Skip if mask of other elements don't equal our expected order.
9580       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9581         // We only need the last 3 bits for the number of shifts.
9582         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9583                          : BigEndianShifts[MaskOneElt & 0x7];
9584         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9585         Swap = MaskOneElt < NumHalfWords;
9586         FoundCandidate = true;
9587         break;
9588       }
9589     }
9590   }
9591 
9592   if (!FoundCandidate)
9593     return SDValue();
9594 
9595   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9596   // optionally with VECSHL if shift is required.
9597   if (Swap)
9598     std::swap(V1, V2);
9599   if (V2.isUndef())
9600     V2 = V1;
9601   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9602   if (ShiftElts) {
9603     // Double ShiftElts because we're left shifting on v16i8 type.
9604     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9605                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9606     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9607     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9608                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9609     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9610   }
9611   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9612   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9613                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9614   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9615 }
9616 
9617 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9618 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9619 /// return the code it can be lowered into.  Worst case, it can always be
9620 /// lowered into a vperm.
9621 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9622                                                SelectionDAG &DAG) const {
9623   SDLoc dl(Op);
9624   SDValue V1 = Op.getOperand(0);
9625   SDValue V2 = Op.getOperand(1);
9626   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9627   EVT VT = Op.getValueType();
9628   bool isLittleEndian = Subtarget.isLittleEndian();
9629 
9630   unsigned ShiftElts, InsertAtByte;
9631   bool Swap = false;
9632 
9633   // If this is a load-and-splat, we can do that with a single instruction
9634   // in some cases. However if the load has multiple uses, we don't want to
9635   // combine it because that will just produce multiple loads.
9636   const SDValue *InputLoad = getNormalLoadInput(V1);
9637   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9638       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9639       InputLoad->hasOneUse()) {
9640     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9641     int SplatIdx =
9642       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9643 
9644     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9645     // For 4-byte load-and-splat, we need Power9.
9646     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9647       uint64_t Offset = 0;
9648       if (IsFourByte)
9649         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9650       else
9651         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9652       SDValue BasePtr = LD->getBasePtr();
9653       if (Offset != 0)
9654         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9655                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9656       SDValue Ops[] = {
9657         LD->getChain(),    // Chain
9658         BasePtr,           // BasePtr
9659         DAG.getValueType(Op.getValueType()) // VT
9660       };
9661       SDVTList VTL =
9662         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9663       SDValue LdSplt =
9664         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9665                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9666       if (LdSplt.getValueType() != SVOp->getValueType(0))
9667         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9668       return LdSplt;
9669     }
9670   }
9671   if (Subtarget.hasP9Vector() &&
9672       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9673                            isLittleEndian)) {
9674     if (Swap)
9675       std::swap(V1, V2);
9676     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9677     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9678     if (ShiftElts) {
9679       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9680                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9681       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9682                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9683       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9684     }
9685     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9686                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9687     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9688   }
9689 
9690   if (Subtarget.hasP9Altivec()) {
9691     SDValue NewISDNode;
9692     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9693       return NewISDNode;
9694 
9695     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9696       return NewISDNode;
9697   }
9698 
9699   if (Subtarget.hasVSX() &&
9700       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9701     if (Swap)
9702       std::swap(V1, V2);
9703     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9704     SDValue Conv2 =
9705         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9706 
9707     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9708                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9709     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9710   }
9711 
9712   if (Subtarget.hasVSX() &&
9713     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9714     if (Swap)
9715       std::swap(V1, V2);
9716     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9717     SDValue Conv2 =
9718         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9719 
9720     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9721                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9722     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9723   }
9724 
9725   if (Subtarget.hasP9Vector()) {
9726      if (PPC::isXXBRHShuffleMask(SVOp)) {
9727       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9728       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9729       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9730     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9731       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9732       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9733       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9734     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9735       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9736       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9737       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9738     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9739       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9740       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9741       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9742     }
9743   }
9744 
9745   if (Subtarget.hasVSX()) {
9746     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9747       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9748 
9749       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9750       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9751                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9752       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9753     }
9754 
9755     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9756     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9757       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9758       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9759       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9760     }
9761   }
9762 
9763   if (Subtarget.hasQPX()) {
9764     if (VT.getVectorNumElements() != 4)
9765       return SDValue();
9766 
9767     if (V2.isUndef()) V2 = V1;
9768 
9769     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9770     if (AlignIdx != -1) {
9771       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9772                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9773     } else if (SVOp->isSplat()) {
9774       int SplatIdx = SVOp->getSplatIndex();
9775       if (SplatIdx >= 4) {
9776         std::swap(V1, V2);
9777         SplatIdx -= 4;
9778       }
9779 
9780       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9781                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9782     }
9783 
9784     // Lower this into a qvgpci/qvfperm pair.
9785 
9786     // Compute the qvgpci literal
9787     unsigned idx = 0;
9788     for (unsigned i = 0; i < 4; ++i) {
9789       int m = SVOp->getMaskElt(i);
9790       unsigned mm = m >= 0 ? (unsigned) m : i;
9791       idx |= mm << (3-i)*3;
9792     }
9793 
9794     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9795                              DAG.getConstant(idx, dl, MVT::i32));
9796     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9797   }
9798 
9799   // Cases that are handled by instructions that take permute immediates
9800   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9801   // selected by the instruction selector.
9802   if (V2.isUndef()) {
9803     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9804         PPC::isSplatShuffleMask(SVOp, 2) ||
9805         PPC::isSplatShuffleMask(SVOp, 4) ||
9806         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9807         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9808         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9809         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9810         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9811         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9812         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9813         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9814         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9815         (Subtarget.hasP8Altivec() && (
9816          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9817          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9818          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9819       return Op;
9820     }
9821   }
9822 
9823   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9824   // and produce a fixed permutation.  If any of these match, do not lower to
9825   // VPERM.
9826   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9827   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9828       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9829       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9830       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9831       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9832       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9833       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9834       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9835       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9836       (Subtarget.hasP8Altivec() && (
9837        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9838        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9839        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9840     return Op;
9841 
9842   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9843   // perfect shuffle table to emit an optimal matching sequence.
9844   ArrayRef<int> PermMask = SVOp->getMask();
9845 
9846   unsigned PFIndexes[4];
9847   bool isFourElementShuffle = true;
9848   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9849     unsigned EltNo = 8;   // Start out undef.
9850     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9851       if (PermMask[i*4+j] < 0)
9852         continue;   // Undef, ignore it.
9853 
9854       unsigned ByteSource = PermMask[i*4+j];
9855       if ((ByteSource & 3) != j) {
9856         isFourElementShuffle = false;
9857         break;
9858       }
9859 
9860       if (EltNo == 8) {
9861         EltNo = ByteSource/4;
9862       } else if (EltNo != ByteSource/4) {
9863         isFourElementShuffle = false;
9864         break;
9865       }
9866     }
9867     PFIndexes[i] = EltNo;
9868   }
9869 
9870   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9871   // perfect shuffle vector to determine if it is cost effective to do this as
9872   // discrete instructions, or whether we should use a vperm.
9873   // For now, we skip this for little endian until such time as we have a
9874   // little-endian perfect shuffle table.
9875   if (isFourElementShuffle && !isLittleEndian) {
9876     // Compute the index in the perfect shuffle table.
9877     unsigned PFTableIndex =
9878       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9879 
9880     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9881     unsigned Cost  = (PFEntry >> 30);
9882 
9883     // Determining when to avoid vperm is tricky.  Many things affect the cost
9884     // of vperm, particularly how many times the perm mask needs to be computed.
9885     // For example, if the perm mask can be hoisted out of a loop or is already
9886     // used (perhaps because there are multiple permutes with the same shuffle
9887     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9888     // the loop requires an extra register.
9889     //
9890     // As a compromise, we only emit discrete instructions if the shuffle can be
9891     // generated in 3 or fewer operations.  When we have loop information
9892     // available, if this block is within a loop, we should avoid using vperm
9893     // for 3-operation perms and use a constant pool load instead.
9894     if (Cost < 3)
9895       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9896   }
9897 
9898   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9899   // vector that will get spilled to the constant pool.
9900   if (V2.isUndef()) V2 = V1;
9901 
9902   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9903   // that it is in input element units, not in bytes.  Convert now.
9904 
9905   // For little endian, the order of the input vectors is reversed, and
9906   // the permutation mask is complemented with respect to 31.  This is
9907   // necessary to produce proper semantics with the big-endian-biased vperm
9908   // instruction.
9909   EVT EltVT = V1.getValueType().getVectorElementType();
9910   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9911 
9912   SmallVector<SDValue, 16> ResultMask;
9913   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9914     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9915 
9916     for (unsigned j = 0; j != BytesPerElement; ++j)
9917       if (isLittleEndian)
9918         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9919                                              dl, MVT::i32));
9920       else
9921         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9922                                              MVT::i32));
9923   }
9924 
9925   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9926   if (isLittleEndian)
9927     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9928                        V2, V1, VPermMask);
9929   else
9930     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9931                        V1, V2, VPermMask);
9932 }
9933 
9934 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9935 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9936 /// information about the intrinsic.
9937 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9938                                  bool &isDot, const PPCSubtarget &Subtarget) {
9939   unsigned IntrinsicID =
9940       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9941   CompareOpc = -1;
9942   isDot = false;
9943   switch (IntrinsicID) {
9944   default:
9945     return false;
9946   // Comparison predicates.
9947   case Intrinsic::ppc_altivec_vcmpbfp_p:
9948     CompareOpc = 966;
9949     isDot = true;
9950     break;
9951   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9952     CompareOpc = 198;
9953     isDot = true;
9954     break;
9955   case Intrinsic::ppc_altivec_vcmpequb_p:
9956     CompareOpc = 6;
9957     isDot = true;
9958     break;
9959   case Intrinsic::ppc_altivec_vcmpequh_p:
9960     CompareOpc = 70;
9961     isDot = true;
9962     break;
9963   case Intrinsic::ppc_altivec_vcmpequw_p:
9964     CompareOpc = 134;
9965     isDot = true;
9966     break;
9967   case Intrinsic::ppc_altivec_vcmpequd_p:
9968     if (Subtarget.hasP8Altivec()) {
9969       CompareOpc = 199;
9970       isDot = true;
9971     } else
9972       return false;
9973     break;
9974   case Intrinsic::ppc_altivec_vcmpneb_p:
9975   case Intrinsic::ppc_altivec_vcmpneh_p:
9976   case Intrinsic::ppc_altivec_vcmpnew_p:
9977   case Intrinsic::ppc_altivec_vcmpnezb_p:
9978   case Intrinsic::ppc_altivec_vcmpnezh_p:
9979   case Intrinsic::ppc_altivec_vcmpnezw_p:
9980     if (Subtarget.hasP9Altivec()) {
9981       switch (IntrinsicID) {
9982       default:
9983         llvm_unreachable("Unknown comparison intrinsic.");
9984       case Intrinsic::ppc_altivec_vcmpneb_p:
9985         CompareOpc = 7;
9986         break;
9987       case Intrinsic::ppc_altivec_vcmpneh_p:
9988         CompareOpc = 71;
9989         break;
9990       case Intrinsic::ppc_altivec_vcmpnew_p:
9991         CompareOpc = 135;
9992         break;
9993       case Intrinsic::ppc_altivec_vcmpnezb_p:
9994         CompareOpc = 263;
9995         break;
9996       case Intrinsic::ppc_altivec_vcmpnezh_p:
9997         CompareOpc = 327;
9998         break;
9999       case Intrinsic::ppc_altivec_vcmpnezw_p:
10000         CompareOpc = 391;
10001         break;
10002       }
10003       isDot = true;
10004     } else
10005       return false;
10006     break;
10007   case Intrinsic::ppc_altivec_vcmpgefp_p:
10008     CompareOpc = 454;
10009     isDot = true;
10010     break;
10011   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10012     CompareOpc = 710;
10013     isDot = true;
10014     break;
10015   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10016     CompareOpc = 774;
10017     isDot = true;
10018     break;
10019   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10020     CompareOpc = 838;
10021     isDot = true;
10022     break;
10023   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10024     CompareOpc = 902;
10025     isDot = true;
10026     break;
10027   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10028     if (Subtarget.hasP8Altivec()) {
10029       CompareOpc = 967;
10030       isDot = true;
10031     } else
10032       return false;
10033     break;
10034   case Intrinsic::ppc_altivec_vcmpgtub_p:
10035     CompareOpc = 518;
10036     isDot = true;
10037     break;
10038   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10039     CompareOpc = 582;
10040     isDot = true;
10041     break;
10042   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10043     CompareOpc = 646;
10044     isDot = true;
10045     break;
10046   case Intrinsic::ppc_altivec_vcmpgtud_p:
10047     if (Subtarget.hasP8Altivec()) {
10048       CompareOpc = 711;
10049       isDot = true;
10050     } else
10051       return false;
10052     break;
10053 
10054   // VSX predicate comparisons use the same infrastructure
10055   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10056   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10057   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10058   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10059   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10060   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10061     if (Subtarget.hasVSX()) {
10062       switch (IntrinsicID) {
10063       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10064         CompareOpc = 99;
10065         break;
10066       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10067         CompareOpc = 115;
10068         break;
10069       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10070         CompareOpc = 107;
10071         break;
10072       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10073         CompareOpc = 67;
10074         break;
10075       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10076         CompareOpc = 83;
10077         break;
10078       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10079         CompareOpc = 75;
10080         break;
10081       }
10082       isDot = true;
10083     } else
10084       return false;
10085     break;
10086 
10087   // Normal Comparisons.
10088   case Intrinsic::ppc_altivec_vcmpbfp:
10089     CompareOpc = 966;
10090     break;
10091   case Intrinsic::ppc_altivec_vcmpeqfp:
10092     CompareOpc = 198;
10093     break;
10094   case Intrinsic::ppc_altivec_vcmpequb:
10095     CompareOpc = 6;
10096     break;
10097   case Intrinsic::ppc_altivec_vcmpequh:
10098     CompareOpc = 70;
10099     break;
10100   case Intrinsic::ppc_altivec_vcmpequw:
10101     CompareOpc = 134;
10102     break;
10103   case Intrinsic::ppc_altivec_vcmpequd:
10104     if (Subtarget.hasP8Altivec())
10105       CompareOpc = 199;
10106     else
10107       return false;
10108     break;
10109   case Intrinsic::ppc_altivec_vcmpneb:
10110   case Intrinsic::ppc_altivec_vcmpneh:
10111   case Intrinsic::ppc_altivec_vcmpnew:
10112   case Intrinsic::ppc_altivec_vcmpnezb:
10113   case Intrinsic::ppc_altivec_vcmpnezh:
10114   case Intrinsic::ppc_altivec_vcmpnezw:
10115     if (Subtarget.hasP9Altivec())
10116       switch (IntrinsicID) {
10117       default:
10118         llvm_unreachable("Unknown comparison intrinsic.");
10119       case Intrinsic::ppc_altivec_vcmpneb:
10120         CompareOpc = 7;
10121         break;
10122       case Intrinsic::ppc_altivec_vcmpneh:
10123         CompareOpc = 71;
10124         break;
10125       case Intrinsic::ppc_altivec_vcmpnew:
10126         CompareOpc = 135;
10127         break;
10128       case Intrinsic::ppc_altivec_vcmpnezb:
10129         CompareOpc = 263;
10130         break;
10131       case Intrinsic::ppc_altivec_vcmpnezh:
10132         CompareOpc = 327;
10133         break;
10134       case Intrinsic::ppc_altivec_vcmpnezw:
10135         CompareOpc = 391;
10136         break;
10137       }
10138     else
10139       return false;
10140     break;
10141   case Intrinsic::ppc_altivec_vcmpgefp:
10142     CompareOpc = 454;
10143     break;
10144   case Intrinsic::ppc_altivec_vcmpgtfp:
10145     CompareOpc = 710;
10146     break;
10147   case Intrinsic::ppc_altivec_vcmpgtsb:
10148     CompareOpc = 774;
10149     break;
10150   case Intrinsic::ppc_altivec_vcmpgtsh:
10151     CompareOpc = 838;
10152     break;
10153   case Intrinsic::ppc_altivec_vcmpgtsw:
10154     CompareOpc = 902;
10155     break;
10156   case Intrinsic::ppc_altivec_vcmpgtsd:
10157     if (Subtarget.hasP8Altivec())
10158       CompareOpc = 967;
10159     else
10160       return false;
10161     break;
10162   case Intrinsic::ppc_altivec_vcmpgtub:
10163     CompareOpc = 518;
10164     break;
10165   case Intrinsic::ppc_altivec_vcmpgtuh:
10166     CompareOpc = 582;
10167     break;
10168   case Intrinsic::ppc_altivec_vcmpgtuw:
10169     CompareOpc = 646;
10170     break;
10171   case Intrinsic::ppc_altivec_vcmpgtud:
10172     if (Subtarget.hasP8Altivec())
10173       CompareOpc = 711;
10174     else
10175       return false;
10176     break;
10177   }
10178   return true;
10179 }
10180 
10181 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10182 /// lower, do it, otherwise return null.
10183 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10184                                                    SelectionDAG &DAG) const {
10185   unsigned IntrinsicID =
10186     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10187 
10188   SDLoc dl(Op);
10189 
10190   if (IntrinsicID == Intrinsic::thread_pointer) {
10191     // Reads the thread pointer register, used for __builtin_thread_pointer.
10192     if (Subtarget.isPPC64())
10193       return DAG.getRegister(PPC::X13, MVT::i64);
10194     return DAG.getRegister(PPC::R2, MVT::i32);
10195   }
10196 
10197   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10198   // opcode number of the comparison.
10199   int CompareOpc;
10200   bool isDot;
10201   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10202     return SDValue();    // Don't custom lower most intrinsics.
10203 
10204   // If this is a non-dot comparison, make the VCMP node and we are done.
10205   if (!isDot) {
10206     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10207                               Op.getOperand(1), Op.getOperand(2),
10208                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10209     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10210   }
10211 
10212   // Create the PPCISD altivec 'dot' comparison node.
10213   SDValue Ops[] = {
10214     Op.getOperand(2),  // LHS
10215     Op.getOperand(3),  // RHS
10216     DAG.getConstant(CompareOpc, dl, MVT::i32)
10217   };
10218   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10219   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10220 
10221   // Now that we have the comparison, emit a copy from the CR to a GPR.
10222   // This is flagged to the above dot comparison.
10223   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10224                                 DAG.getRegister(PPC::CR6, MVT::i32),
10225                                 CompNode.getValue(1));
10226 
10227   // Unpack the result based on how the target uses it.
10228   unsigned BitNo;   // Bit # of CR6.
10229   bool InvertBit;   // Invert result?
10230   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10231   default:  // Can't happen, don't crash on invalid number though.
10232   case 0:   // Return the value of the EQ bit of CR6.
10233     BitNo = 0; InvertBit = false;
10234     break;
10235   case 1:   // Return the inverted value of the EQ bit of CR6.
10236     BitNo = 0; InvertBit = true;
10237     break;
10238   case 2:   // Return the value of the LT bit of CR6.
10239     BitNo = 2; InvertBit = false;
10240     break;
10241   case 3:   // Return the inverted value of the LT bit of CR6.
10242     BitNo = 2; InvertBit = true;
10243     break;
10244   }
10245 
10246   // Shift the bit into the low position.
10247   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10248                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10249   // Isolate the bit.
10250   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10251                       DAG.getConstant(1, dl, MVT::i32));
10252 
10253   // If we are supposed to, toggle the bit.
10254   if (InvertBit)
10255     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10256                         DAG.getConstant(1, dl, MVT::i32));
10257   return Flags;
10258 }
10259 
10260 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10261                                                SelectionDAG &DAG) const {
10262   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10263   // the beginning of the argument list.
10264   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10265   SDLoc DL(Op);
10266   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10267   case Intrinsic::ppc_cfence: {
10268     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10269     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10270     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10271                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10272                                                   Op.getOperand(ArgStart + 1)),
10273                                       Op.getOperand(0)),
10274                    0);
10275   }
10276   default:
10277     break;
10278   }
10279   return SDValue();
10280 }
10281 
10282 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10283   // Check for a DIV with the same operands as this REM.
10284   for (auto UI : Op.getOperand(1)->uses()) {
10285     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10286         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10287       if (UI->getOperand(0) == Op.getOperand(0) &&
10288           UI->getOperand(1) == Op.getOperand(1))
10289         return SDValue();
10290   }
10291   return Op;
10292 }
10293 
10294 // Lower scalar BSWAP64 to xxbrd.
10295 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10296   SDLoc dl(Op);
10297   // MTVSRDD
10298   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10299                    Op.getOperand(0));
10300   // XXBRD
10301   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10302   // MFVSRD
10303   int VectorIndex = 0;
10304   if (Subtarget.isLittleEndian())
10305     VectorIndex = 1;
10306   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10307                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10308   return Op;
10309 }
10310 
10311 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10312 // compared to a value that is atomically loaded (atomic loads zero-extend).
10313 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10314                                                 SelectionDAG &DAG) const {
10315   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10316          "Expecting an atomic compare-and-swap here.");
10317   SDLoc dl(Op);
10318   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10319   EVT MemVT = AtomicNode->getMemoryVT();
10320   if (MemVT.getSizeInBits() >= 32)
10321     return Op;
10322 
10323   SDValue CmpOp = Op.getOperand(2);
10324   // If this is already correctly zero-extended, leave it alone.
10325   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10326   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10327     return Op;
10328 
10329   // Clear the high bits of the compare operand.
10330   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10331   SDValue NewCmpOp =
10332     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10333                 DAG.getConstant(MaskVal, dl, MVT::i32));
10334 
10335   // Replace the existing compare operand with the properly zero-extended one.
10336   SmallVector<SDValue, 4> Ops;
10337   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10338     Ops.push_back(AtomicNode->getOperand(i));
10339   Ops[2] = NewCmpOp;
10340   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10341   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10342   auto NodeTy =
10343     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10344   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10345 }
10346 
10347 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10348                                                  SelectionDAG &DAG) const {
10349   SDLoc dl(Op);
10350   // Create a stack slot that is 16-byte aligned.
10351   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10352   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10353   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10354   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10355 
10356   // Store the input value into Value#0 of the stack slot.
10357   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10358                                MachinePointerInfo());
10359   // Load it out.
10360   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10361 }
10362 
10363 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10364                                                   SelectionDAG &DAG) const {
10365   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10366          "Should only be called for ISD::INSERT_VECTOR_ELT");
10367 
10368   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10369   // We have legal lowering for constant indices but not for variable ones.
10370   if (!C)
10371     return SDValue();
10372 
10373   EVT VT = Op.getValueType();
10374   SDLoc dl(Op);
10375   SDValue V1 = Op.getOperand(0);
10376   SDValue V2 = Op.getOperand(1);
10377   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10378   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10379     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10380     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10381     unsigned InsertAtElement = C->getZExtValue();
10382     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10383     if (Subtarget.isLittleEndian()) {
10384       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10385     }
10386     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10387                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10388   }
10389   return Op;
10390 }
10391 
10392 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10393                                                    SelectionDAG &DAG) const {
10394   SDLoc dl(Op);
10395   SDNode *N = Op.getNode();
10396 
10397   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10398          "Unknown extract_vector_elt type");
10399 
10400   SDValue Value = N->getOperand(0);
10401 
10402   // The first part of this is like the store lowering except that we don't
10403   // need to track the chain.
10404 
10405   // The values are now known to be -1 (false) or 1 (true). To convert this
10406   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10407   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10408   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10409 
10410   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10411   // understand how to form the extending load.
10412   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10413 
10414   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10415 
10416   // Now convert to an integer and store.
10417   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10418     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10419     Value);
10420 
10421   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10422   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10423   MachinePointerInfo PtrInfo =
10424       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10425   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10426   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10427 
10428   SDValue StoreChain = DAG.getEntryNode();
10429   SDValue Ops[] = {StoreChain,
10430                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10431                    Value, FIdx};
10432   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10433 
10434   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10435     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10436 
10437   // Extract the value requested.
10438   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10439   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10440   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10441 
10442   SDValue IntVal =
10443       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10444 
10445   if (!Subtarget.useCRBits())
10446     return IntVal;
10447 
10448   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10449 }
10450 
10451 /// Lowering for QPX v4i1 loads
10452 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10453                                            SelectionDAG &DAG) const {
10454   SDLoc dl(Op);
10455   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10456   SDValue LoadChain = LN->getChain();
10457   SDValue BasePtr = LN->getBasePtr();
10458 
10459   if (Op.getValueType() == MVT::v4f64 ||
10460       Op.getValueType() == MVT::v4f32) {
10461     EVT MemVT = LN->getMemoryVT();
10462     unsigned Alignment = LN->getAlignment();
10463 
10464     // If this load is properly aligned, then it is legal.
10465     if (Alignment >= MemVT.getStoreSize())
10466       return Op;
10467 
10468     EVT ScalarVT = Op.getValueType().getScalarType(),
10469         ScalarMemVT = MemVT.getScalarType();
10470     unsigned Stride = ScalarMemVT.getStoreSize();
10471 
10472     SDValue Vals[4], LoadChains[4];
10473     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10474       SDValue Load;
10475       if (ScalarVT != ScalarMemVT)
10476         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10477                               BasePtr,
10478                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10479                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10480                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10481       else
10482         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10483                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10484                            MinAlign(Alignment, Idx * Stride),
10485                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10486 
10487       if (Idx == 0 && LN->isIndexed()) {
10488         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10489                "Unknown addressing mode on vector load");
10490         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10491                                   LN->getAddressingMode());
10492       }
10493 
10494       Vals[Idx] = Load;
10495       LoadChains[Idx] = Load.getValue(1);
10496 
10497       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10498                             DAG.getConstant(Stride, dl,
10499                                             BasePtr.getValueType()));
10500     }
10501 
10502     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10503     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10504 
10505     if (LN->isIndexed()) {
10506       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10507       return DAG.getMergeValues(RetOps, dl);
10508     }
10509 
10510     SDValue RetOps[] = { Value, TF };
10511     return DAG.getMergeValues(RetOps, dl);
10512   }
10513 
10514   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10515   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10516 
10517   // To lower v4i1 from a byte array, we load the byte elements of the
10518   // vector and then reuse the BUILD_VECTOR logic.
10519 
10520   SDValue VectElmts[4], VectElmtChains[4];
10521   for (unsigned i = 0; i < 4; ++i) {
10522     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10523     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10524 
10525     VectElmts[i] = DAG.getExtLoad(
10526         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10527         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10528         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10529     VectElmtChains[i] = VectElmts[i].getValue(1);
10530   }
10531 
10532   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10533   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10534 
10535   SDValue RVals[] = { Value, LoadChain };
10536   return DAG.getMergeValues(RVals, dl);
10537 }
10538 
10539 /// Lowering for QPX v4i1 stores
10540 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10541                                             SelectionDAG &DAG) const {
10542   SDLoc dl(Op);
10543   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10544   SDValue StoreChain = SN->getChain();
10545   SDValue BasePtr = SN->getBasePtr();
10546   SDValue Value = SN->getValue();
10547 
10548   if (Value.getValueType() == MVT::v4f64 ||
10549       Value.getValueType() == MVT::v4f32) {
10550     EVT MemVT = SN->getMemoryVT();
10551     unsigned Alignment = SN->getAlignment();
10552 
10553     // If this store is properly aligned, then it is legal.
10554     if (Alignment >= MemVT.getStoreSize())
10555       return Op;
10556 
10557     EVT ScalarVT = Value.getValueType().getScalarType(),
10558         ScalarMemVT = MemVT.getScalarType();
10559     unsigned Stride = ScalarMemVT.getStoreSize();
10560 
10561     SDValue Stores[4];
10562     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10563       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10564                                DAG.getVectorIdxConstant(Idx, dl));
10565       SDValue Store;
10566       if (ScalarVT != ScalarMemVT)
10567         Store =
10568             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10569                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10570                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10571                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10572       else
10573         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10574                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10575                              MinAlign(Alignment, Idx * Stride),
10576                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10577 
10578       if (Idx == 0 && SN->isIndexed()) {
10579         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10580                "Unknown addressing mode on vector store");
10581         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10582                                     SN->getAddressingMode());
10583       }
10584 
10585       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10586                             DAG.getConstant(Stride, dl,
10587                                             BasePtr.getValueType()));
10588       Stores[Idx] = Store;
10589     }
10590 
10591     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10592 
10593     if (SN->isIndexed()) {
10594       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10595       return DAG.getMergeValues(RetOps, dl);
10596     }
10597 
10598     return TF;
10599   }
10600 
10601   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10602   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10603 
10604   // The values are now known to be -1 (false) or 1 (true). To convert this
10605   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10606   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10607   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10608 
10609   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10610   // understand how to form the extending load.
10611   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10612 
10613   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10614 
10615   // Now convert to an integer and store.
10616   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10617     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10618     Value);
10619 
10620   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10621   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10622   MachinePointerInfo PtrInfo =
10623       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10624   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10625   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10626 
10627   SDValue Ops[] = {StoreChain,
10628                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10629                    Value, FIdx};
10630   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10631 
10632   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10633     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10634 
10635   // Move data into the byte array.
10636   SDValue Loads[4], LoadChains[4];
10637   for (unsigned i = 0; i < 4; ++i) {
10638     unsigned Offset = 4*i;
10639     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10640     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10641 
10642     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10643                            PtrInfo.getWithOffset(Offset));
10644     LoadChains[i] = Loads[i].getValue(1);
10645   }
10646 
10647   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10648 
10649   SDValue Stores[4];
10650   for (unsigned i = 0; i < 4; ++i) {
10651     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10652     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10653 
10654     Stores[i] = DAG.getTruncStore(
10655         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10656         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10657         SN->getAAInfo());
10658   }
10659 
10660   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10661 
10662   return StoreChain;
10663 }
10664 
10665 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10666   SDLoc dl(Op);
10667   if (Op.getValueType() == MVT::v4i32) {
10668     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10669 
10670     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10671     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10672 
10673     SDValue RHSSwap =   // = vrlw RHS, 16
10674       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10675 
10676     // Shrinkify inputs to v8i16.
10677     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10678     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10679     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10680 
10681     // Low parts multiplied together, generating 32-bit results (we ignore the
10682     // top parts).
10683     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10684                                         LHS, RHS, DAG, dl, MVT::v4i32);
10685 
10686     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10687                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10688     // Shift the high parts up 16 bits.
10689     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10690                               Neg16, DAG, dl);
10691     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10692   } else if (Op.getValueType() == MVT::v16i8) {
10693     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10694     bool isLittleEndian = Subtarget.isLittleEndian();
10695 
10696     // Multiply the even 8-bit parts, producing 16-bit sums.
10697     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10698                                            LHS, RHS, DAG, dl, MVT::v8i16);
10699     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10700 
10701     // Multiply the odd 8-bit parts, producing 16-bit sums.
10702     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10703                                           LHS, RHS, DAG, dl, MVT::v8i16);
10704     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10705 
10706     // Merge the results together.  Because vmuleub and vmuloub are
10707     // instructions with a big-endian bias, we must reverse the
10708     // element numbering and reverse the meaning of "odd" and "even"
10709     // when generating little endian code.
10710     int Ops[16];
10711     for (unsigned i = 0; i != 8; ++i) {
10712       if (isLittleEndian) {
10713         Ops[i*2  ] = 2*i;
10714         Ops[i*2+1] = 2*i+16;
10715       } else {
10716         Ops[i*2  ] = 2*i+1;
10717         Ops[i*2+1] = 2*i+1+16;
10718       }
10719     }
10720     if (isLittleEndian)
10721       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10722     else
10723       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10724   } else {
10725     llvm_unreachable("Unknown mul to lower!");
10726   }
10727 }
10728 
10729 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10730 
10731   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10732 
10733   EVT VT = Op.getValueType();
10734   assert(VT.isVector() &&
10735          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10736   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10737           VT == MVT::v16i8) &&
10738          "Unexpected vector element type!");
10739   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10740          "Current subtarget doesn't support smax v2i64!");
10741 
10742   // For vector abs, it can be lowered to:
10743   // abs x
10744   // ==>
10745   // y = -x
10746   // smax(x, y)
10747 
10748   SDLoc dl(Op);
10749   SDValue X = Op.getOperand(0);
10750   SDValue Zero = DAG.getConstant(0, dl, VT);
10751   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10752 
10753   // SMAX patch https://reviews.llvm.org/D47332
10754   // hasn't landed yet, so use intrinsic first here.
10755   // TODO: Should use SMAX directly once SMAX patch landed
10756   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10757   if (VT == MVT::v2i64)
10758     BifID = Intrinsic::ppc_altivec_vmaxsd;
10759   else if (VT == MVT::v8i16)
10760     BifID = Intrinsic::ppc_altivec_vmaxsh;
10761   else if (VT == MVT::v16i8)
10762     BifID = Intrinsic::ppc_altivec_vmaxsb;
10763 
10764   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10765 }
10766 
10767 // Custom lowering for fpext vf32 to v2f64
10768 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10769 
10770   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10771          "Should only be called for ISD::FP_EXTEND");
10772 
10773   // FIXME: handle extends from half precision float vectors on P9.
10774   // We only want to custom lower an extend from v2f32 to v2f64.
10775   if (Op.getValueType() != MVT::v2f64 ||
10776       Op.getOperand(0).getValueType() != MVT::v2f32)
10777     return SDValue();
10778 
10779   SDLoc dl(Op);
10780   SDValue Op0 = Op.getOperand(0);
10781 
10782   switch (Op0.getOpcode()) {
10783   default:
10784     return SDValue();
10785   case ISD::EXTRACT_SUBVECTOR: {
10786     assert(Op0.getNumOperands() == 2 &&
10787            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10788            "Node should have 2 operands with second one being a constant!");
10789 
10790     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10791       return SDValue();
10792 
10793     // Custom lower is only done for high or low doubleword.
10794     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10795     if (Idx % 2 != 0)
10796       return SDValue();
10797 
10798     // Since input is v4f32, at this point Idx is either 0 or 2.
10799     // Shift to get the doubleword position we want.
10800     int DWord = Idx >> 1;
10801 
10802     // High and low word positions are different on little endian.
10803     if (Subtarget.isLittleEndian())
10804       DWord ^= 0x1;
10805 
10806     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10807                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10808   }
10809   case ISD::FADD:
10810   case ISD::FMUL:
10811   case ISD::FSUB: {
10812     SDValue NewLoad[2];
10813     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10814       // Ensure both input are loads.
10815       SDValue LdOp = Op0.getOperand(i);
10816       if (LdOp.getOpcode() != ISD::LOAD)
10817         return SDValue();
10818       // Generate new load node.
10819       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10820       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10821       NewLoad[i] = DAG.getMemIntrinsicNode(
10822           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10823           LD->getMemoryVT(), LD->getMemOperand());
10824     }
10825     SDValue NewOp =
10826         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10827                     NewLoad[1], Op0.getNode()->getFlags());
10828     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10829                        DAG.getConstant(0, dl, MVT::i32));
10830   }
10831   case ISD::LOAD: {
10832     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10833     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10834     SDValue NewLd = DAG.getMemIntrinsicNode(
10835         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10836         LD->getMemoryVT(), LD->getMemOperand());
10837     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10838                        DAG.getConstant(0, dl, MVT::i32));
10839   }
10840   }
10841   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10842 }
10843 
10844 /// LowerOperation - Provide custom lowering hooks for some operations.
10845 ///
10846 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10847   switch (Op.getOpcode()) {
10848   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10849   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10850   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10851   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10852   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10853   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10854   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10855   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10856   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10857 
10858   // Variable argument lowering.
10859   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10860   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10861   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10862 
10863   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10864   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10865   case ISD::GET_DYNAMIC_AREA_OFFSET:
10866     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10867 
10868   // Exception handling lowering.
10869   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10870   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10871   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10872 
10873   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10874   case ISD::STORE:              return LowerSTORE(Op, DAG);
10875   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10876   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10877   case ISD::FP_TO_UINT:
10878   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10879   case ISD::UINT_TO_FP:
10880   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10881   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10882 
10883   // Lower 64-bit shifts.
10884   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10885   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10886   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10887 
10888   // Vector-related lowering.
10889   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10890   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10891   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10892   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10893   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10894   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10895   case ISD::MUL:                return LowerMUL(Op, DAG);
10896   case ISD::ABS:                return LowerABS(Op, DAG);
10897   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10898 
10899   // For counter-based loop handling.
10900   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10901 
10902   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10903 
10904   // Frame & Return address.
10905   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10906   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10907 
10908   case ISD::INTRINSIC_VOID:
10909     return LowerINTRINSIC_VOID(Op, DAG);
10910   case ISD::SREM:
10911   case ISD::UREM:
10912     return LowerREM(Op, DAG);
10913   case ISD::BSWAP:
10914     return LowerBSWAP(Op, DAG);
10915   case ISD::ATOMIC_CMP_SWAP:
10916     return LowerATOMIC_CMP_SWAP(Op, DAG);
10917   }
10918 }
10919 
10920 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10921                                            SmallVectorImpl<SDValue>&Results,
10922                                            SelectionDAG &DAG) const {
10923   SDLoc dl(N);
10924   switch (N->getOpcode()) {
10925   default:
10926     llvm_unreachable("Do not know how to custom type legalize this operation!");
10927   case ISD::READCYCLECOUNTER: {
10928     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10929     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10930 
10931     Results.push_back(
10932         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10933     Results.push_back(RTB.getValue(2));
10934     break;
10935   }
10936   case ISD::INTRINSIC_W_CHAIN: {
10937     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10938         Intrinsic::loop_decrement)
10939       break;
10940 
10941     assert(N->getValueType(0) == MVT::i1 &&
10942            "Unexpected result type for CTR decrement intrinsic");
10943     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10944                                  N->getValueType(0));
10945     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10946     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10947                                  N->getOperand(1));
10948 
10949     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10950     Results.push_back(NewInt.getValue(1));
10951     break;
10952   }
10953   case ISD::VAARG: {
10954     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10955       return;
10956 
10957     EVT VT = N->getValueType(0);
10958 
10959     if (VT == MVT::i64) {
10960       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10961 
10962       Results.push_back(NewNode);
10963       Results.push_back(NewNode.getValue(1));
10964     }
10965     return;
10966   }
10967   case ISD::FP_TO_SINT:
10968   case ISD::FP_TO_UINT:
10969     // LowerFP_TO_INT() can only handle f32 and f64.
10970     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10971       return;
10972     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10973     return;
10974   case ISD::TRUNCATE: {
10975     EVT TrgVT = N->getValueType(0);
10976     EVT OpVT = N->getOperand(0).getValueType();
10977     if (TrgVT.isVector() &&
10978         isOperationCustom(N->getOpcode(), TrgVT) &&
10979         OpVT.getSizeInBits() <= 128 &&
10980         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10981       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10982     return;
10983   }
10984   case ISD::BITCAST:
10985     // Don't handle bitcast here.
10986     return;
10987   case ISD::FP_EXTEND:
10988     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10989     if (Lowered)
10990       Results.push_back(Lowered);
10991     return;
10992   }
10993 }
10994 
10995 //===----------------------------------------------------------------------===//
10996 //  Other Lowering Code
10997 //===----------------------------------------------------------------------===//
10998 
10999 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
11000   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11001   Function *Func = Intrinsic::getDeclaration(M, Id);
11002   return Builder.CreateCall(Func, {});
11003 }
11004 
11005 // The mappings for emitLeading/TrailingFence is taken from
11006 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11007 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11008                                                  Instruction *Inst,
11009                                                  AtomicOrdering Ord) const {
11010   if (Ord == AtomicOrdering::SequentiallyConsistent)
11011     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11012   if (isReleaseOrStronger(Ord))
11013     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11014   return nullptr;
11015 }
11016 
11017 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11018                                                   Instruction *Inst,
11019                                                   AtomicOrdering Ord) const {
11020   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11021     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11022     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11023     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11024     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11025       return Builder.CreateCall(
11026           Intrinsic::getDeclaration(
11027               Builder.GetInsertBlock()->getParent()->getParent(),
11028               Intrinsic::ppc_cfence, {Inst->getType()}),
11029           {Inst});
11030     // FIXME: Can use isync for rmw operation.
11031     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11032   }
11033   return nullptr;
11034 }
11035 
11036 MachineBasicBlock *
11037 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11038                                     unsigned AtomicSize,
11039                                     unsigned BinOpcode,
11040                                     unsigned CmpOpcode,
11041                                     unsigned CmpPred) const {
11042   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11043   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11044 
11045   auto LoadMnemonic = PPC::LDARX;
11046   auto StoreMnemonic = PPC::STDCX;
11047   switch (AtomicSize) {
11048   default:
11049     llvm_unreachable("Unexpected size of atomic entity");
11050   case 1:
11051     LoadMnemonic = PPC::LBARX;
11052     StoreMnemonic = PPC::STBCX;
11053     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11054     break;
11055   case 2:
11056     LoadMnemonic = PPC::LHARX;
11057     StoreMnemonic = PPC::STHCX;
11058     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11059     break;
11060   case 4:
11061     LoadMnemonic = PPC::LWARX;
11062     StoreMnemonic = PPC::STWCX;
11063     break;
11064   case 8:
11065     LoadMnemonic = PPC::LDARX;
11066     StoreMnemonic = PPC::STDCX;
11067     break;
11068   }
11069 
11070   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11071   MachineFunction *F = BB->getParent();
11072   MachineFunction::iterator It = ++BB->getIterator();
11073 
11074   Register dest = MI.getOperand(0).getReg();
11075   Register ptrA = MI.getOperand(1).getReg();
11076   Register ptrB = MI.getOperand(2).getReg();
11077   Register incr = MI.getOperand(3).getReg();
11078   DebugLoc dl = MI.getDebugLoc();
11079 
11080   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11081   MachineBasicBlock *loop2MBB =
11082     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11083   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11084   F->insert(It, loopMBB);
11085   if (CmpOpcode)
11086     F->insert(It, loop2MBB);
11087   F->insert(It, exitMBB);
11088   exitMBB->splice(exitMBB->begin(), BB,
11089                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11090   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11091 
11092   MachineRegisterInfo &RegInfo = F->getRegInfo();
11093   Register TmpReg = (!BinOpcode) ? incr :
11094     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11095                                            : &PPC::GPRCRegClass);
11096 
11097   //  thisMBB:
11098   //   ...
11099   //   fallthrough --> loopMBB
11100   BB->addSuccessor(loopMBB);
11101 
11102   //  loopMBB:
11103   //   l[wd]arx dest, ptr
11104   //   add r0, dest, incr
11105   //   st[wd]cx. r0, ptr
11106   //   bne- loopMBB
11107   //   fallthrough --> exitMBB
11108 
11109   // For max/min...
11110   //  loopMBB:
11111   //   l[wd]arx dest, ptr
11112   //   cmpl?[wd] incr, dest
11113   //   bgt exitMBB
11114   //  loop2MBB:
11115   //   st[wd]cx. dest, ptr
11116   //   bne- loopMBB
11117   //   fallthrough --> exitMBB
11118 
11119   BB = loopMBB;
11120   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11121     .addReg(ptrA).addReg(ptrB);
11122   if (BinOpcode)
11123     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11124   if (CmpOpcode) {
11125     // Signed comparisons of byte or halfword values must be sign-extended.
11126     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11127       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11128       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11129               ExtReg).addReg(dest);
11130       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11131         .addReg(incr).addReg(ExtReg);
11132     } else
11133       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11134         .addReg(incr).addReg(dest);
11135 
11136     BuildMI(BB, dl, TII->get(PPC::BCC))
11137       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11138     BB->addSuccessor(loop2MBB);
11139     BB->addSuccessor(exitMBB);
11140     BB = loop2MBB;
11141   }
11142   BuildMI(BB, dl, TII->get(StoreMnemonic))
11143     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11144   BuildMI(BB, dl, TII->get(PPC::BCC))
11145     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11146   BB->addSuccessor(loopMBB);
11147   BB->addSuccessor(exitMBB);
11148 
11149   //  exitMBB:
11150   //   ...
11151   BB = exitMBB;
11152   return BB;
11153 }
11154 
11155 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11156     MachineInstr &MI, MachineBasicBlock *BB,
11157     bool is8bit, // operation
11158     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11159   // If we support part-word atomic mnemonics, just use them
11160   if (Subtarget.hasPartwordAtomics())
11161     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11162                             CmpPred);
11163 
11164   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11165   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11166   // In 64 bit mode we have to use 64 bits for addresses, even though the
11167   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11168   // registers without caring whether they're 32 or 64, but here we're
11169   // doing actual arithmetic on the addresses.
11170   bool is64bit = Subtarget.isPPC64();
11171   bool isLittleEndian = Subtarget.isLittleEndian();
11172   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11173 
11174   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11175   MachineFunction *F = BB->getParent();
11176   MachineFunction::iterator It = ++BB->getIterator();
11177 
11178   Register dest = MI.getOperand(0).getReg();
11179   Register ptrA = MI.getOperand(1).getReg();
11180   Register ptrB = MI.getOperand(2).getReg();
11181   Register incr = MI.getOperand(3).getReg();
11182   DebugLoc dl = MI.getDebugLoc();
11183 
11184   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11185   MachineBasicBlock *loop2MBB =
11186       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11187   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11188   F->insert(It, loopMBB);
11189   if (CmpOpcode)
11190     F->insert(It, loop2MBB);
11191   F->insert(It, exitMBB);
11192   exitMBB->splice(exitMBB->begin(), BB,
11193                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11194   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11195 
11196   MachineRegisterInfo &RegInfo = F->getRegInfo();
11197   const TargetRegisterClass *RC =
11198       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11199   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11200 
11201   Register PtrReg = RegInfo.createVirtualRegister(RC);
11202   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11203   Register ShiftReg =
11204       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11205   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11206   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11207   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11208   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11209   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11210   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11211   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11212   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11213   Register Ptr1Reg;
11214   Register TmpReg =
11215       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11216 
11217   //  thisMBB:
11218   //   ...
11219   //   fallthrough --> loopMBB
11220   BB->addSuccessor(loopMBB);
11221 
11222   // The 4-byte load must be aligned, while a char or short may be
11223   // anywhere in the word.  Hence all this nasty bookkeeping code.
11224   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11225   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11226   //   xori shift, shift1, 24 [16]
11227   //   rlwinm ptr, ptr1, 0, 0, 29
11228   //   slw incr2, incr, shift
11229   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11230   //   slw mask, mask2, shift
11231   //  loopMBB:
11232   //   lwarx tmpDest, ptr
11233   //   add tmp, tmpDest, incr2
11234   //   andc tmp2, tmpDest, mask
11235   //   and tmp3, tmp, mask
11236   //   or tmp4, tmp3, tmp2
11237   //   stwcx. tmp4, ptr
11238   //   bne- loopMBB
11239   //   fallthrough --> exitMBB
11240   //   srw dest, tmpDest, shift
11241   if (ptrA != ZeroReg) {
11242     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11243     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11244         .addReg(ptrA)
11245         .addReg(ptrB);
11246   } else {
11247     Ptr1Reg = ptrB;
11248   }
11249   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11250   // mode.
11251   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11252       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11253       .addImm(3)
11254       .addImm(27)
11255       .addImm(is8bit ? 28 : 27);
11256   if (!isLittleEndian)
11257     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11258         .addReg(Shift1Reg)
11259         .addImm(is8bit ? 24 : 16);
11260   if (is64bit)
11261     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11262         .addReg(Ptr1Reg)
11263         .addImm(0)
11264         .addImm(61);
11265   else
11266     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11267         .addReg(Ptr1Reg)
11268         .addImm(0)
11269         .addImm(0)
11270         .addImm(29);
11271   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11272   if (is8bit)
11273     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11274   else {
11275     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11276     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11277         .addReg(Mask3Reg)
11278         .addImm(65535);
11279   }
11280   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11281       .addReg(Mask2Reg)
11282       .addReg(ShiftReg);
11283 
11284   BB = loopMBB;
11285   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11286       .addReg(ZeroReg)
11287       .addReg(PtrReg);
11288   if (BinOpcode)
11289     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11290         .addReg(Incr2Reg)
11291         .addReg(TmpDestReg);
11292   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11293       .addReg(TmpDestReg)
11294       .addReg(MaskReg);
11295   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11296   if (CmpOpcode) {
11297     // For unsigned comparisons, we can directly compare the shifted values.
11298     // For signed comparisons we shift and sign extend.
11299     Register SReg = RegInfo.createVirtualRegister(GPRC);
11300     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11301         .addReg(TmpDestReg)
11302         .addReg(MaskReg);
11303     unsigned ValueReg = SReg;
11304     unsigned CmpReg = Incr2Reg;
11305     if (CmpOpcode == PPC::CMPW) {
11306       ValueReg = RegInfo.createVirtualRegister(GPRC);
11307       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11308           .addReg(SReg)
11309           .addReg(ShiftReg);
11310       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11311       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11312           .addReg(ValueReg);
11313       ValueReg = ValueSReg;
11314       CmpReg = incr;
11315     }
11316     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11317         .addReg(CmpReg)
11318         .addReg(ValueReg);
11319     BuildMI(BB, dl, TII->get(PPC::BCC))
11320         .addImm(CmpPred)
11321         .addReg(PPC::CR0)
11322         .addMBB(exitMBB);
11323     BB->addSuccessor(loop2MBB);
11324     BB->addSuccessor(exitMBB);
11325     BB = loop2MBB;
11326   }
11327   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11328   BuildMI(BB, dl, TII->get(PPC::STWCX))
11329       .addReg(Tmp4Reg)
11330       .addReg(ZeroReg)
11331       .addReg(PtrReg);
11332   BuildMI(BB, dl, TII->get(PPC::BCC))
11333       .addImm(PPC::PRED_NE)
11334       .addReg(PPC::CR0)
11335       .addMBB(loopMBB);
11336   BB->addSuccessor(loopMBB);
11337   BB->addSuccessor(exitMBB);
11338 
11339   //  exitMBB:
11340   //   ...
11341   BB = exitMBB;
11342   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11343       .addReg(TmpDestReg)
11344       .addReg(ShiftReg);
11345   return BB;
11346 }
11347 
11348 llvm::MachineBasicBlock *
11349 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11350                                     MachineBasicBlock *MBB) const {
11351   DebugLoc DL = MI.getDebugLoc();
11352   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11353   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11354 
11355   MachineFunction *MF = MBB->getParent();
11356   MachineRegisterInfo &MRI = MF->getRegInfo();
11357 
11358   const BasicBlock *BB = MBB->getBasicBlock();
11359   MachineFunction::iterator I = ++MBB->getIterator();
11360 
11361   Register DstReg = MI.getOperand(0).getReg();
11362   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11363   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11364   Register mainDstReg = MRI.createVirtualRegister(RC);
11365   Register restoreDstReg = MRI.createVirtualRegister(RC);
11366 
11367   MVT PVT = getPointerTy(MF->getDataLayout());
11368   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11369          "Invalid Pointer Size!");
11370   // For v = setjmp(buf), we generate
11371   //
11372   // thisMBB:
11373   //  SjLjSetup mainMBB
11374   //  bl mainMBB
11375   //  v_restore = 1
11376   //  b sinkMBB
11377   //
11378   // mainMBB:
11379   //  buf[LabelOffset] = LR
11380   //  v_main = 0
11381   //
11382   // sinkMBB:
11383   //  v = phi(main, restore)
11384   //
11385 
11386   MachineBasicBlock *thisMBB = MBB;
11387   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11388   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11389   MF->insert(I, mainMBB);
11390   MF->insert(I, sinkMBB);
11391 
11392   MachineInstrBuilder MIB;
11393 
11394   // Transfer the remainder of BB and its successor edges to sinkMBB.
11395   sinkMBB->splice(sinkMBB->begin(), MBB,
11396                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11397   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11398 
11399   // Note that the structure of the jmp_buf used here is not compatible
11400   // with that used by libc, and is not designed to be. Specifically, it
11401   // stores only those 'reserved' registers that LLVM does not otherwise
11402   // understand how to spill. Also, by convention, by the time this
11403   // intrinsic is called, Clang has already stored the frame address in the
11404   // first slot of the buffer and stack address in the third. Following the
11405   // X86 target code, we'll store the jump address in the second slot. We also
11406   // need to save the TOC pointer (R2) to handle jumps between shared
11407   // libraries, and that will be stored in the fourth slot. The thread
11408   // identifier (R13) is not affected.
11409 
11410   // thisMBB:
11411   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11412   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11413   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11414 
11415   // Prepare IP either in reg.
11416   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11417   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11418   Register BufReg = MI.getOperand(1).getReg();
11419 
11420   if (Subtarget.is64BitELFABI()) {
11421     setUsesTOCBasePtr(*MBB->getParent());
11422     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11423               .addReg(PPC::X2)
11424               .addImm(TOCOffset)
11425               .addReg(BufReg)
11426               .cloneMemRefs(MI);
11427   }
11428 
11429   // Naked functions never have a base pointer, and so we use r1. For all
11430   // other functions, this decision must be delayed until during PEI.
11431   unsigned BaseReg;
11432   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11433     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11434   else
11435     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11436 
11437   MIB = BuildMI(*thisMBB, MI, DL,
11438                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11439             .addReg(BaseReg)
11440             .addImm(BPOffset)
11441             .addReg(BufReg)
11442             .cloneMemRefs(MI);
11443 
11444   // Setup
11445   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11446   MIB.addRegMask(TRI->getNoPreservedMask());
11447 
11448   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11449 
11450   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11451           .addMBB(mainMBB);
11452   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11453 
11454   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11455   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11456 
11457   // mainMBB:
11458   //  mainDstReg = 0
11459   MIB =
11460       BuildMI(mainMBB, DL,
11461               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11462 
11463   // Store IP
11464   if (Subtarget.isPPC64()) {
11465     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11466             .addReg(LabelReg)
11467             .addImm(LabelOffset)
11468             .addReg(BufReg);
11469   } else {
11470     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11471             .addReg(LabelReg)
11472             .addImm(LabelOffset)
11473             .addReg(BufReg);
11474   }
11475   MIB.cloneMemRefs(MI);
11476 
11477   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11478   mainMBB->addSuccessor(sinkMBB);
11479 
11480   // sinkMBB:
11481   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11482           TII->get(PPC::PHI), DstReg)
11483     .addReg(mainDstReg).addMBB(mainMBB)
11484     .addReg(restoreDstReg).addMBB(thisMBB);
11485 
11486   MI.eraseFromParent();
11487   return sinkMBB;
11488 }
11489 
11490 MachineBasicBlock *
11491 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11492                                      MachineBasicBlock *MBB) const {
11493   DebugLoc DL = MI.getDebugLoc();
11494   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11495 
11496   MachineFunction *MF = MBB->getParent();
11497   MachineRegisterInfo &MRI = MF->getRegInfo();
11498 
11499   MVT PVT = getPointerTy(MF->getDataLayout());
11500   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11501          "Invalid Pointer Size!");
11502 
11503   const TargetRegisterClass *RC =
11504     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11505   Register Tmp = MRI.createVirtualRegister(RC);
11506   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11507   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11508   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11509   unsigned BP =
11510       (PVT == MVT::i64)
11511           ? PPC::X30
11512           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11513                                                               : PPC::R30);
11514 
11515   MachineInstrBuilder MIB;
11516 
11517   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11518   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11519   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11520   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11521 
11522   Register BufReg = MI.getOperand(0).getReg();
11523 
11524   // Reload FP (the jumped-to function may not have had a
11525   // frame pointer, and if so, then its r31 will be restored
11526   // as necessary).
11527   if (PVT == MVT::i64) {
11528     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11529             .addImm(0)
11530             .addReg(BufReg);
11531   } else {
11532     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11533             .addImm(0)
11534             .addReg(BufReg);
11535   }
11536   MIB.cloneMemRefs(MI);
11537 
11538   // Reload IP
11539   if (PVT == MVT::i64) {
11540     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11541             .addImm(LabelOffset)
11542             .addReg(BufReg);
11543   } else {
11544     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11545             .addImm(LabelOffset)
11546             .addReg(BufReg);
11547   }
11548   MIB.cloneMemRefs(MI);
11549 
11550   // Reload SP
11551   if (PVT == MVT::i64) {
11552     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11553             .addImm(SPOffset)
11554             .addReg(BufReg);
11555   } else {
11556     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11557             .addImm(SPOffset)
11558             .addReg(BufReg);
11559   }
11560   MIB.cloneMemRefs(MI);
11561 
11562   // Reload BP
11563   if (PVT == MVT::i64) {
11564     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11565             .addImm(BPOffset)
11566             .addReg(BufReg);
11567   } else {
11568     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11569             .addImm(BPOffset)
11570             .addReg(BufReg);
11571   }
11572   MIB.cloneMemRefs(MI);
11573 
11574   // Reload TOC
11575   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11576     setUsesTOCBasePtr(*MBB->getParent());
11577     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11578               .addImm(TOCOffset)
11579               .addReg(BufReg)
11580               .cloneMemRefs(MI);
11581   }
11582 
11583   // Jump
11584   BuildMI(*MBB, MI, DL,
11585           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11586   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11587 
11588   MI.eraseFromParent();
11589   return MBB;
11590 }
11591 
11592 MachineBasicBlock *
11593 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11594                                                MachineBasicBlock *BB) const {
11595   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11596       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11597     if (Subtarget.is64BitELFABI() &&
11598         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11599         !Subtarget.isUsingPCRelativeCalls()) {
11600       // Call lowering should have added an r2 operand to indicate a dependence
11601       // on the TOC base pointer value. It can't however, because there is no
11602       // way to mark the dependence as implicit there, and so the stackmap code
11603       // will confuse it with a regular operand. Instead, add the dependence
11604       // here.
11605       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11606     }
11607 
11608     return emitPatchPoint(MI, BB);
11609   }
11610 
11611   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11612       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11613     return emitEHSjLjSetJmp(MI, BB);
11614   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11615              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11616     return emitEHSjLjLongJmp(MI, BB);
11617   }
11618 
11619   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11620 
11621   // To "insert" these instructions we actually have to insert their
11622   // control-flow patterns.
11623   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11624   MachineFunction::iterator It = ++BB->getIterator();
11625 
11626   MachineFunction *F = BB->getParent();
11627 
11628   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11629       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11630       MI.getOpcode() == PPC::SELECT_I8) {
11631     SmallVector<MachineOperand, 2> Cond;
11632     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11633         MI.getOpcode() == PPC::SELECT_CC_I8)
11634       Cond.push_back(MI.getOperand(4));
11635     else
11636       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11637     Cond.push_back(MI.getOperand(1));
11638 
11639     DebugLoc dl = MI.getDebugLoc();
11640     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11641                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11642   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11643              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11644              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11645              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11646              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11647              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11648              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11649              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11650              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11651              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11652              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11653              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11654              MI.getOpcode() == PPC::SELECT_F4 ||
11655              MI.getOpcode() == PPC::SELECT_F8 ||
11656              MI.getOpcode() == PPC::SELECT_F16 ||
11657              MI.getOpcode() == PPC::SELECT_QFRC ||
11658              MI.getOpcode() == PPC::SELECT_QSRC ||
11659              MI.getOpcode() == PPC::SELECT_QBRC ||
11660              MI.getOpcode() == PPC::SELECT_SPE ||
11661              MI.getOpcode() == PPC::SELECT_SPE4 ||
11662              MI.getOpcode() == PPC::SELECT_VRRC ||
11663              MI.getOpcode() == PPC::SELECT_VSFRC ||
11664              MI.getOpcode() == PPC::SELECT_VSSRC ||
11665              MI.getOpcode() == PPC::SELECT_VSRC) {
11666     // The incoming instruction knows the destination vreg to set, the
11667     // condition code register to branch on, the true/false values to
11668     // select between, and a branch opcode to use.
11669 
11670     //  thisMBB:
11671     //  ...
11672     //   TrueVal = ...
11673     //   cmpTY ccX, r1, r2
11674     //   bCC copy1MBB
11675     //   fallthrough --> copy0MBB
11676     MachineBasicBlock *thisMBB = BB;
11677     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11678     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11679     DebugLoc dl = MI.getDebugLoc();
11680     F->insert(It, copy0MBB);
11681     F->insert(It, sinkMBB);
11682 
11683     // Transfer the remainder of BB and its successor edges to sinkMBB.
11684     sinkMBB->splice(sinkMBB->begin(), BB,
11685                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11686     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11687 
11688     // Next, add the true and fallthrough blocks as its successors.
11689     BB->addSuccessor(copy0MBB);
11690     BB->addSuccessor(sinkMBB);
11691 
11692     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11693         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11694         MI.getOpcode() == PPC::SELECT_F16 ||
11695         MI.getOpcode() == PPC::SELECT_SPE4 ||
11696         MI.getOpcode() == PPC::SELECT_SPE ||
11697         MI.getOpcode() == PPC::SELECT_QFRC ||
11698         MI.getOpcode() == PPC::SELECT_QSRC ||
11699         MI.getOpcode() == PPC::SELECT_QBRC ||
11700         MI.getOpcode() == PPC::SELECT_VRRC ||
11701         MI.getOpcode() == PPC::SELECT_VSFRC ||
11702         MI.getOpcode() == PPC::SELECT_VSSRC ||
11703         MI.getOpcode() == PPC::SELECT_VSRC) {
11704       BuildMI(BB, dl, TII->get(PPC::BC))
11705           .addReg(MI.getOperand(1).getReg())
11706           .addMBB(sinkMBB);
11707     } else {
11708       unsigned SelectPred = MI.getOperand(4).getImm();
11709       BuildMI(BB, dl, TII->get(PPC::BCC))
11710           .addImm(SelectPred)
11711           .addReg(MI.getOperand(1).getReg())
11712           .addMBB(sinkMBB);
11713     }
11714 
11715     //  copy0MBB:
11716     //   %FalseValue = ...
11717     //   # fallthrough to sinkMBB
11718     BB = copy0MBB;
11719 
11720     // Update machine-CFG edges
11721     BB->addSuccessor(sinkMBB);
11722 
11723     //  sinkMBB:
11724     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11725     //  ...
11726     BB = sinkMBB;
11727     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11728         .addReg(MI.getOperand(3).getReg())
11729         .addMBB(copy0MBB)
11730         .addReg(MI.getOperand(2).getReg())
11731         .addMBB(thisMBB);
11732   } else if (MI.getOpcode() == PPC::ReadTB) {
11733     // To read the 64-bit time-base register on a 32-bit target, we read the
11734     // two halves. Should the counter have wrapped while it was being read, we
11735     // need to try again.
11736     // ...
11737     // readLoop:
11738     // mfspr Rx,TBU # load from TBU
11739     // mfspr Ry,TB  # load from TB
11740     // mfspr Rz,TBU # load from TBU
11741     // cmpw crX,Rx,Rz # check if 'old'='new'
11742     // bne readLoop   # branch if they're not equal
11743     // ...
11744 
11745     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11746     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11747     DebugLoc dl = MI.getDebugLoc();
11748     F->insert(It, readMBB);
11749     F->insert(It, sinkMBB);
11750 
11751     // Transfer the remainder of BB and its successor edges to sinkMBB.
11752     sinkMBB->splice(sinkMBB->begin(), BB,
11753                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11754     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11755 
11756     BB->addSuccessor(readMBB);
11757     BB = readMBB;
11758 
11759     MachineRegisterInfo &RegInfo = F->getRegInfo();
11760     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11761     Register LoReg = MI.getOperand(0).getReg();
11762     Register HiReg = MI.getOperand(1).getReg();
11763 
11764     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11765     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11766     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11767 
11768     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11769 
11770     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11771         .addReg(HiReg)
11772         .addReg(ReadAgainReg);
11773     BuildMI(BB, dl, TII->get(PPC::BCC))
11774         .addImm(PPC::PRED_NE)
11775         .addReg(CmpReg)
11776         .addMBB(readMBB);
11777 
11778     BB->addSuccessor(readMBB);
11779     BB->addSuccessor(sinkMBB);
11780   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11781     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11782   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11783     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11784   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11785     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11786   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11787     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11788 
11789   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11790     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11791   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11792     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11793   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11794     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11795   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11796     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11797 
11798   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11799     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11800   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11801     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11802   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11803     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11804   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11805     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11806 
11807   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11808     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11809   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11810     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11811   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11812     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11813   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11814     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11815 
11816   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11817     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11818   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11819     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11820   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11821     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11822   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11823     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11824 
11825   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11826     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11827   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11828     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11829   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11830     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11831   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11832     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11833 
11834   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11835     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11836   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11837     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11838   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11839     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11840   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11841     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11842 
11843   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11844     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11845   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11846     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11847   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11848     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11849   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11850     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11851 
11852   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11853     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11854   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11855     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11856   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11857     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11858   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11859     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11860 
11861   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11862     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11863   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11864     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11865   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11866     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11867   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11868     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11869 
11870   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11871     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11872   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11873     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11874   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11875     BB = EmitAtomicBinary(MI, BB, 4, 0);
11876   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11877     BB = EmitAtomicBinary(MI, BB, 8, 0);
11878   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11879            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11880            (Subtarget.hasPartwordAtomics() &&
11881             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11882            (Subtarget.hasPartwordAtomics() &&
11883             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11884     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11885 
11886     auto LoadMnemonic = PPC::LDARX;
11887     auto StoreMnemonic = PPC::STDCX;
11888     switch (MI.getOpcode()) {
11889     default:
11890       llvm_unreachable("Compare and swap of unknown size");
11891     case PPC::ATOMIC_CMP_SWAP_I8:
11892       LoadMnemonic = PPC::LBARX;
11893       StoreMnemonic = PPC::STBCX;
11894       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11895       break;
11896     case PPC::ATOMIC_CMP_SWAP_I16:
11897       LoadMnemonic = PPC::LHARX;
11898       StoreMnemonic = PPC::STHCX;
11899       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11900       break;
11901     case PPC::ATOMIC_CMP_SWAP_I32:
11902       LoadMnemonic = PPC::LWARX;
11903       StoreMnemonic = PPC::STWCX;
11904       break;
11905     case PPC::ATOMIC_CMP_SWAP_I64:
11906       LoadMnemonic = PPC::LDARX;
11907       StoreMnemonic = PPC::STDCX;
11908       break;
11909     }
11910     Register dest = MI.getOperand(0).getReg();
11911     Register ptrA = MI.getOperand(1).getReg();
11912     Register ptrB = MI.getOperand(2).getReg();
11913     Register oldval = MI.getOperand(3).getReg();
11914     Register newval = MI.getOperand(4).getReg();
11915     DebugLoc dl = MI.getDebugLoc();
11916 
11917     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11918     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11919     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11920     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11921     F->insert(It, loop1MBB);
11922     F->insert(It, loop2MBB);
11923     F->insert(It, midMBB);
11924     F->insert(It, exitMBB);
11925     exitMBB->splice(exitMBB->begin(), BB,
11926                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11927     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11928 
11929     //  thisMBB:
11930     //   ...
11931     //   fallthrough --> loopMBB
11932     BB->addSuccessor(loop1MBB);
11933 
11934     // loop1MBB:
11935     //   l[bhwd]arx dest, ptr
11936     //   cmp[wd] dest, oldval
11937     //   bne- midMBB
11938     // loop2MBB:
11939     //   st[bhwd]cx. newval, ptr
11940     //   bne- loopMBB
11941     //   b exitBB
11942     // midMBB:
11943     //   st[bhwd]cx. dest, ptr
11944     // exitBB:
11945     BB = loop1MBB;
11946     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11947     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11948         .addReg(oldval)
11949         .addReg(dest);
11950     BuildMI(BB, dl, TII->get(PPC::BCC))
11951         .addImm(PPC::PRED_NE)
11952         .addReg(PPC::CR0)
11953         .addMBB(midMBB);
11954     BB->addSuccessor(loop2MBB);
11955     BB->addSuccessor(midMBB);
11956 
11957     BB = loop2MBB;
11958     BuildMI(BB, dl, TII->get(StoreMnemonic))
11959         .addReg(newval)
11960         .addReg(ptrA)
11961         .addReg(ptrB);
11962     BuildMI(BB, dl, TII->get(PPC::BCC))
11963         .addImm(PPC::PRED_NE)
11964         .addReg(PPC::CR0)
11965         .addMBB(loop1MBB);
11966     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11967     BB->addSuccessor(loop1MBB);
11968     BB->addSuccessor(exitMBB);
11969 
11970     BB = midMBB;
11971     BuildMI(BB, dl, TII->get(StoreMnemonic))
11972         .addReg(dest)
11973         .addReg(ptrA)
11974         .addReg(ptrB);
11975     BB->addSuccessor(exitMBB);
11976 
11977     //  exitMBB:
11978     //   ...
11979     BB = exitMBB;
11980   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11981              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11982     // We must use 64-bit registers for addresses when targeting 64-bit,
11983     // since we're actually doing arithmetic on them.  Other registers
11984     // can be 32-bit.
11985     bool is64bit = Subtarget.isPPC64();
11986     bool isLittleEndian = Subtarget.isLittleEndian();
11987     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11988 
11989     Register dest = MI.getOperand(0).getReg();
11990     Register ptrA = MI.getOperand(1).getReg();
11991     Register ptrB = MI.getOperand(2).getReg();
11992     Register oldval = MI.getOperand(3).getReg();
11993     Register newval = MI.getOperand(4).getReg();
11994     DebugLoc dl = MI.getDebugLoc();
11995 
11996     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11997     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11998     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11999     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12000     F->insert(It, loop1MBB);
12001     F->insert(It, loop2MBB);
12002     F->insert(It, midMBB);
12003     F->insert(It, exitMBB);
12004     exitMBB->splice(exitMBB->begin(), BB,
12005                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12006     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12007 
12008     MachineRegisterInfo &RegInfo = F->getRegInfo();
12009     const TargetRegisterClass *RC =
12010         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12011     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12012 
12013     Register PtrReg = RegInfo.createVirtualRegister(RC);
12014     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12015     Register ShiftReg =
12016         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12017     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12018     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12019     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12020     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12021     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12022     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12023     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12024     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12025     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12026     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12027     Register Ptr1Reg;
12028     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12029     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12030     //  thisMBB:
12031     //   ...
12032     //   fallthrough --> loopMBB
12033     BB->addSuccessor(loop1MBB);
12034 
12035     // The 4-byte load must be aligned, while a char or short may be
12036     // anywhere in the word.  Hence all this nasty bookkeeping code.
12037     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12038     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12039     //   xori shift, shift1, 24 [16]
12040     //   rlwinm ptr, ptr1, 0, 0, 29
12041     //   slw newval2, newval, shift
12042     //   slw oldval2, oldval,shift
12043     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12044     //   slw mask, mask2, shift
12045     //   and newval3, newval2, mask
12046     //   and oldval3, oldval2, mask
12047     // loop1MBB:
12048     //   lwarx tmpDest, ptr
12049     //   and tmp, tmpDest, mask
12050     //   cmpw tmp, oldval3
12051     //   bne- midMBB
12052     // loop2MBB:
12053     //   andc tmp2, tmpDest, mask
12054     //   or tmp4, tmp2, newval3
12055     //   stwcx. tmp4, ptr
12056     //   bne- loop1MBB
12057     //   b exitBB
12058     // midMBB:
12059     //   stwcx. tmpDest, ptr
12060     // exitBB:
12061     //   srw dest, tmpDest, shift
12062     if (ptrA != ZeroReg) {
12063       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12064       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12065           .addReg(ptrA)
12066           .addReg(ptrB);
12067     } else {
12068       Ptr1Reg = ptrB;
12069     }
12070 
12071     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12072     // mode.
12073     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12074         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12075         .addImm(3)
12076         .addImm(27)
12077         .addImm(is8bit ? 28 : 27);
12078     if (!isLittleEndian)
12079       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12080           .addReg(Shift1Reg)
12081           .addImm(is8bit ? 24 : 16);
12082     if (is64bit)
12083       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12084           .addReg(Ptr1Reg)
12085           .addImm(0)
12086           .addImm(61);
12087     else
12088       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12089           .addReg(Ptr1Reg)
12090           .addImm(0)
12091           .addImm(0)
12092           .addImm(29);
12093     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12094         .addReg(newval)
12095         .addReg(ShiftReg);
12096     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12097         .addReg(oldval)
12098         .addReg(ShiftReg);
12099     if (is8bit)
12100       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12101     else {
12102       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12103       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12104           .addReg(Mask3Reg)
12105           .addImm(65535);
12106     }
12107     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12108         .addReg(Mask2Reg)
12109         .addReg(ShiftReg);
12110     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12111         .addReg(NewVal2Reg)
12112         .addReg(MaskReg);
12113     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12114         .addReg(OldVal2Reg)
12115         .addReg(MaskReg);
12116 
12117     BB = loop1MBB;
12118     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12119         .addReg(ZeroReg)
12120         .addReg(PtrReg);
12121     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12122         .addReg(TmpDestReg)
12123         .addReg(MaskReg);
12124     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12125         .addReg(TmpReg)
12126         .addReg(OldVal3Reg);
12127     BuildMI(BB, dl, TII->get(PPC::BCC))
12128         .addImm(PPC::PRED_NE)
12129         .addReg(PPC::CR0)
12130         .addMBB(midMBB);
12131     BB->addSuccessor(loop2MBB);
12132     BB->addSuccessor(midMBB);
12133 
12134     BB = loop2MBB;
12135     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12136         .addReg(TmpDestReg)
12137         .addReg(MaskReg);
12138     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12139         .addReg(Tmp2Reg)
12140         .addReg(NewVal3Reg);
12141     BuildMI(BB, dl, TII->get(PPC::STWCX))
12142         .addReg(Tmp4Reg)
12143         .addReg(ZeroReg)
12144         .addReg(PtrReg);
12145     BuildMI(BB, dl, TII->get(PPC::BCC))
12146         .addImm(PPC::PRED_NE)
12147         .addReg(PPC::CR0)
12148         .addMBB(loop1MBB);
12149     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12150     BB->addSuccessor(loop1MBB);
12151     BB->addSuccessor(exitMBB);
12152 
12153     BB = midMBB;
12154     BuildMI(BB, dl, TII->get(PPC::STWCX))
12155         .addReg(TmpDestReg)
12156         .addReg(ZeroReg)
12157         .addReg(PtrReg);
12158     BB->addSuccessor(exitMBB);
12159 
12160     //  exitMBB:
12161     //   ...
12162     BB = exitMBB;
12163     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12164         .addReg(TmpReg)
12165         .addReg(ShiftReg);
12166   } else if (MI.getOpcode() == PPC::FADDrtz) {
12167     // This pseudo performs an FADD with rounding mode temporarily forced
12168     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12169     // is not modeled at the SelectionDAG level.
12170     Register Dest = MI.getOperand(0).getReg();
12171     Register Src1 = MI.getOperand(1).getReg();
12172     Register Src2 = MI.getOperand(2).getReg();
12173     DebugLoc dl = MI.getDebugLoc();
12174 
12175     MachineRegisterInfo &RegInfo = F->getRegInfo();
12176     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12177 
12178     // Save FPSCR value.
12179     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12180 
12181     // Set rounding mode to round-to-zero.
12182     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12183     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12184 
12185     // Perform addition.
12186     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12187 
12188     // Restore FPSCR value.
12189     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12190   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12191              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12192              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12193              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12194     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12195                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12196                           ? PPC::ANDI8_rec
12197                           : PPC::ANDI_rec;
12198     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12199                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12200 
12201     MachineRegisterInfo &RegInfo = F->getRegInfo();
12202     Register Dest = RegInfo.createVirtualRegister(
12203         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12204 
12205     DebugLoc Dl = MI.getDebugLoc();
12206     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12207         .addReg(MI.getOperand(1).getReg())
12208         .addImm(1);
12209     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12210             MI.getOperand(0).getReg())
12211         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12212   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12213     DebugLoc Dl = MI.getDebugLoc();
12214     MachineRegisterInfo &RegInfo = F->getRegInfo();
12215     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12216     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12217     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12218             MI.getOperand(0).getReg())
12219         .addReg(CRReg);
12220   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12221     DebugLoc Dl = MI.getDebugLoc();
12222     unsigned Imm = MI.getOperand(1).getImm();
12223     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12224     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12225             MI.getOperand(0).getReg())
12226         .addReg(PPC::CR0EQ);
12227   } else if (MI.getOpcode() == PPC::SETRNDi) {
12228     DebugLoc dl = MI.getDebugLoc();
12229     Register OldFPSCRReg = MI.getOperand(0).getReg();
12230 
12231     // Save FPSCR value.
12232     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12233 
12234     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12235     // the following settings:
12236     //   00 Round to nearest
12237     //   01 Round to 0
12238     //   10 Round to +inf
12239     //   11 Round to -inf
12240 
12241     // When the operand is immediate, using the two least significant bits of
12242     // the immediate to set the bits 62:63 of FPSCR.
12243     unsigned Mode = MI.getOperand(1).getImm();
12244     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12245       .addImm(31);
12246 
12247     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12248       .addImm(30);
12249   } else if (MI.getOpcode() == PPC::SETRND) {
12250     DebugLoc dl = MI.getDebugLoc();
12251 
12252     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12253     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12254     // If the target doesn't have DirectMove, we should use stack to do the
12255     // conversion, because the target doesn't have the instructions like mtvsrd
12256     // or mfvsrd to do this conversion directly.
12257     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12258       if (Subtarget.hasDirectMove()) {
12259         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12260           .addReg(SrcReg);
12261       } else {
12262         // Use stack to do the register copy.
12263         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12264         MachineRegisterInfo &RegInfo = F->getRegInfo();
12265         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12266         if (RC == &PPC::F8RCRegClass) {
12267           // Copy register from F8RCRegClass to G8RCRegclass.
12268           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12269                  "Unsupported RegClass.");
12270 
12271           StoreOp = PPC::STFD;
12272           LoadOp = PPC::LD;
12273         } else {
12274           // Copy register from G8RCRegClass to F8RCRegclass.
12275           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12276                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12277                  "Unsupported RegClass.");
12278         }
12279 
12280         MachineFrameInfo &MFI = F->getFrameInfo();
12281         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12282 
12283         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12284             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12285             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12286             MFI.getObjectAlign(FrameIdx));
12287 
12288         // Store the SrcReg into the stack.
12289         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12290           .addReg(SrcReg)
12291           .addImm(0)
12292           .addFrameIndex(FrameIdx)
12293           .addMemOperand(MMOStore);
12294 
12295         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12296             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12297             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12298             MFI.getObjectAlign(FrameIdx));
12299 
12300         // Load from the stack where SrcReg is stored, and save to DestReg,
12301         // so we have done the RegClass conversion from RegClass::SrcReg to
12302         // RegClass::DestReg.
12303         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12304           .addImm(0)
12305           .addFrameIndex(FrameIdx)
12306           .addMemOperand(MMOLoad);
12307       }
12308     };
12309 
12310     Register OldFPSCRReg = MI.getOperand(0).getReg();
12311 
12312     // Save FPSCR value.
12313     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12314 
12315     // When the operand is gprc register, use two least significant bits of the
12316     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12317     //
12318     // copy OldFPSCRTmpReg, OldFPSCRReg
12319     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12320     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12321     // copy NewFPSCRReg, NewFPSCRTmpReg
12322     // mtfsf 255, NewFPSCRReg
12323     MachineOperand SrcOp = MI.getOperand(1);
12324     MachineRegisterInfo &RegInfo = F->getRegInfo();
12325     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12326 
12327     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12328 
12329     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12330     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12331 
12332     // The first operand of INSERT_SUBREG should be a register which has
12333     // subregisters, we only care about its RegClass, so we should use an
12334     // IMPLICIT_DEF register.
12335     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12336     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12337       .addReg(ImDefReg)
12338       .add(SrcOp)
12339       .addImm(1);
12340 
12341     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12342     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12343       .addReg(OldFPSCRTmpReg)
12344       .addReg(ExtSrcReg)
12345       .addImm(0)
12346       .addImm(62);
12347 
12348     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12349     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12350 
12351     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12352     // bits of FPSCR.
12353     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12354       .addImm(255)
12355       .addReg(NewFPSCRReg)
12356       .addImm(0)
12357       .addImm(0);
12358   } else {
12359     llvm_unreachable("Unexpected instr type to insert");
12360   }
12361 
12362   MI.eraseFromParent(); // The pseudo instruction is gone now.
12363   return BB;
12364 }
12365 
12366 //===----------------------------------------------------------------------===//
12367 // Target Optimization Hooks
12368 //===----------------------------------------------------------------------===//
12369 
12370 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12371   // For the estimates, convergence is quadratic, so we essentially double the
12372   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12373   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12374   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12375   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12376   if (VT.getScalarType() == MVT::f64)
12377     RefinementSteps++;
12378   return RefinementSteps;
12379 }
12380 
12381 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12382                                            int Enabled, int &RefinementSteps,
12383                                            bool &UseOneConstNR,
12384                                            bool Reciprocal) const {
12385   EVT VT = Operand.getValueType();
12386   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12387       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
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 
12395     // The Newton-Raphson computation with a single constant does not provide
12396     // enough accuracy on some CPUs.
12397     UseOneConstNR = !Subtarget.needsTwoConstNR();
12398     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12399   }
12400   return SDValue();
12401 }
12402 
12403 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12404                                             int Enabled,
12405                                             int &RefinementSteps) const {
12406   EVT VT = Operand.getValueType();
12407   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12408       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12409       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12410       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12411       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12412       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12413     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12414       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12415     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12416   }
12417   return SDValue();
12418 }
12419 
12420 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12421   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12422   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12423   // enabled for division), this functionality is redundant with the default
12424   // combiner logic (once the division -> reciprocal/multiply transformation
12425   // has taken place). As a result, this matters more for older cores than for
12426   // newer ones.
12427 
12428   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12429   // reciprocal if there are two or more FDIVs (for embedded cores with only
12430   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12431   switch (Subtarget.getCPUDirective()) {
12432   default:
12433     return 3;
12434   case PPC::DIR_440:
12435   case PPC::DIR_A2:
12436   case PPC::DIR_E500:
12437   case PPC::DIR_E500mc:
12438   case PPC::DIR_E5500:
12439     return 2;
12440   }
12441 }
12442 
12443 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12444 // collapsed, and so we need to look through chains of them.
12445 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12446                                      int64_t& Offset, SelectionDAG &DAG) {
12447   if (DAG.isBaseWithConstantOffset(Loc)) {
12448     Base = Loc.getOperand(0);
12449     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12450 
12451     // The base might itself be a base plus an offset, and if so, accumulate
12452     // that as well.
12453     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12454   }
12455 }
12456 
12457 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12458                             unsigned Bytes, int Dist,
12459                             SelectionDAG &DAG) {
12460   if (VT.getSizeInBits() / 8 != Bytes)
12461     return false;
12462 
12463   SDValue BaseLoc = Base->getBasePtr();
12464   if (Loc.getOpcode() == ISD::FrameIndex) {
12465     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12466       return false;
12467     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12468     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12469     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12470     int FS  = MFI.getObjectSize(FI);
12471     int BFS = MFI.getObjectSize(BFI);
12472     if (FS != BFS || FS != (int)Bytes) return false;
12473     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12474   }
12475 
12476   SDValue Base1 = Loc, Base2 = BaseLoc;
12477   int64_t Offset1 = 0, Offset2 = 0;
12478   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12479   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12480   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12481     return true;
12482 
12483   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12484   const GlobalValue *GV1 = nullptr;
12485   const GlobalValue *GV2 = nullptr;
12486   Offset1 = 0;
12487   Offset2 = 0;
12488   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12489   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12490   if (isGA1 && isGA2 && GV1 == GV2)
12491     return Offset1 == (Offset2 + Dist*Bytes);
12492   return false;
12493 }
12494 
12495 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12496 // not enforce equality of the chain operands.
12497 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12498                             unsigned Bytes, int Dist,
12499                             SelectionDAG &DAG) {
12500   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12501     EVT VT = LS->getMemoryVT();
12502     SDValue Loc = LS->getBasePtr();
12503     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12504   }
12505 
12506   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12507     EVT VT;
12508     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12509     default: return false;
12510     case Intrinsic::ppc_qpx_qvlfd:
12511     case Intrinsic::ppc_qpx_qvlfda:
12512       VT = MVT::v4f64;
12513       break;
12514     case Intrinsic::ppc_qpx_qvlfs:
12515     case Intrinsic::ppc_qpx_qvlfsa:
12516       VT = MVT::v4f32;
12517       break;
12518     case Intrinsic::ppc_qpx_qvlfcd:
12519     case Intrinsic::ppc_qpx_qvlfcda:
12520       VT = MVT::v2f64;
12521       break;
12522     case Intrinsic::ppc_qpx_qvlfcs:
12523     case Intrinsic::ppc_qpx_qvlfcsa:
12524       VT = MVT::v2f32;
12525       break;
12526     case Intrinsic::ppc_qpx_qvlfiwa:
12527     case Intrinsic::ppc_qpx_qvlfiwz:
12528     case Intrinsic::ppc_altivec_lvx:
12529     case Intrinsic::ppc_altivec_lvxl:
12530     case Intrinsic::ppc_vsx_lxvw4x:
12531     case Intrinsic::ppc_vsx_lxvw4x_be:
12532       VT = MVT::v4i32;
12533       break;
12534     case Intrinsic::ppc_vsx_lxvd2x:
12535     case Intrinsic::ppc_vsx_lxvd2x_be:
12536       VT = MVT::v2f64;
12537       break;
12538     case Intrinsic::ppc_altivec_lvebx:
12539       VT = MVT::i8;
12540       break;
12541     case Intrinsic::ppc_altivec_lvehx:
12542       VT = MVT::i16;
12543       break;
12544     case Intrinsic::ppc_altivec_lvewx:
12545       VT = MVT::i32;
12546       break;
12547     }
12548 
12549     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12550   }
12551 
12552   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12553     EVT VT;
12554     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12555     default: return false;
12556     case Intrinsic::ppc_qpx_qvstfd:
12557     case Intrinsic::ppc_qpx_qvstfda:
12558       VT = MVT::v4f64;
12559       break;
12560     case Intrinsic::ppc_qpx_qvstfs:
12561     case Intrinsic::ppc_qpx_qvstfsa:
12562       VT = MVT::v4f32;
12563       break;
12564     case Intrinsic::ppc_qpx_qvstfcd:
12565     case Intrinsic::ppc_qpx_qvstfcda:
12566       VT = MVT::v2f64;
12567       break;
12568     case Intrinsic::ppc_qpx_qvstfcs:
12569     case Intrinsic::ppc_qpx_qvstfcsa:
12570       VT = MVT::v2f32;
12571       break;
12572     case Intrinsic::ppc_qpx_qvstfiw:
12573     case Intrinsic::ppc_qpx_qvstfiwa:
12574     case Intrinsic::ppc_altivec_stvx:
12575     case Intrinsic::ppc_altivec_stvxl:
12576     case Intrinsic::ppc_vsx_stxvw4x:
12577       VT = MVT::v4i32;
12578       break;
12579     case Intrinsic::ppc_vsx_stxvd2x:
12580       VT = MVT::v2f64;
12581       break;
12582     case Intrinsic::ppc_vsx_stxvw4x_be:
12583       VT = MVT::v4i32;
12584       break;
12585     case Intrinsic::ppc_vsx_stxvd2x_be:
12586       VT = MVT::v2f64;
12587       break;
12588     case Intrinsic::ppc_altivec_stvebx:
12589       VT = MVT::i8;
12590       break;
12591     case Intrinsic::ppc_altivec_stvehx:
12592       VT = MVT::i16;
12593       break;
12594     case Intrinsic::ppc_altivec_stvewx:
12595       VT = MVT::i32;
12596       break;
12597     }
12598 
12599     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12600   }
12601 
12602   return false;
12603 }
12604 
12605 // Return true is there is a nearyby consecutive load to the one provided
12606 // (regardless of alignment). We search up and down the chain, looking though
12607 // token factors and other loads (but nothing else). As a result, a true result
12608 // indicates that it is safe to create a new consecutive load adjacent to the
12609 // load provided.
12610 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12611   SDValue Chain = LD->getChain();
12612   EVT VT = LD->getMemoryVT();
12613 
12614   SmallSet<SDNode *, 16> LoadRoots;
12615   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12616   SmallSet<SDNode *, 16> Visited;
12617 
12618   // First, search up the chain, branching to follow all token-factor operands.
12619   // If we find a consecutive load, then we're done, otherwise, record all
12620   // nodes just above the top-level loads and token factors.
12621   while (!Queue.empty()) {
12622     SDNode *ChainNext = Queue.pop_back_val();
12623     if (!Visited.insert(ChainNext).second)
12624       continue;
12625 
12626     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12627       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12628         return true;
12629 
12630       if (!Visited.count(ChainLD->getChain().getNode()))
12631         Queue.push_back(ChainLD->getChain().getNode());
12632     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12633       for (const SDUse &O : ChainNext->ops())
12634         if (!Visited.count(O.getNode()))
12635           Queue.push_back(O.getNode());
12636     } else
12637       LoadRoots.insert(ChainNext);
12638   }
12639 
12640   // Second, search down the chain, starting from the top-level nodes recorded
12641   // in the first phase. These top-level nodes are the nodes just above all
12642   // loads and token factors. Starting with their uses, recursively look though
12643   // all loads (just the chain uses) and token factors to find a consecutive
12644   // load.
12645   Visited.clear();
12646   Queue.clear();
12647 
12648   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12649        IE = LoadRoots.end(); I != IE; ++I) {
12650     Queue.push_back(*I);
12651 
12652     while (!Queue.empty()) {
12653       SDNode *LoadRoot = Queue.pop_back_val();
12654       if (!Visited.insert(LoadRoot).second)
12655         continue;
12656 
12657       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12658         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12659           return true;
12660 
12661       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12662            UE = LoadRoot->use_end(); UI != UE; ++UI)
12663         if (((isa<MemSDNode>(*UI) &&
12664             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12665             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12666           Queue.push_back(*UI);
12667     }
12668   }
12669 
12670   return false;
12671 }
12672 
12673 /// This function is called when we have proved that a SETCC node can be replaced
12674 /// by subtraction (and other supporting instructions) so that the result of
12675 /// comparison is kept in a GPR instead of CR. This function is purely for
12676 /// codegen purposes and has some flags to guide the codegen process.
12677 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12678                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12679   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12680 
12681   // Zero extend the operands to the largest legal integer. Originally, they
12682   // must be of a strictly smaller size.
12683   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12684                          DAG.getConstant(Size, DL, MVT::i32));
12685   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12686                          DAG.getConstant(Size, DL, MVT::i32));
12687 
12688   // Swap if needed. Depends on the condition code.
12689   if (Swap)
12690     std::swap(Op0, Op1);
12691 
12692   // Subtract extended integers.
12693   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12694 
12695   // Move the sign bit to the least significant position and zero out the rest.
12696   // Now the least significant bit carries the result of original comparison.
12697   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12698                              DAG.getConstant(Size - 1, DL, MVT::i32));
12699   auto Final = Shifted;
12700 
12701   // Complement the result if needed. Based on the condition code.
12702   if (Complement)
12703     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12704                         DAG.getConstant(1, DL, MVT::i64));
12705 
12706   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12707 }
12708 
12709 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12710                                                   DAGCombinerInfo &DCI) const {
12711   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12712 
12713   SelectionDAG &DAG = DCI.DAG;
12714   SDLoc DL(N);
12715 
12716   // Size of integers being compared has a critical role in the following
12717   // analysis, so we prefer to do this when all types are legal.
12718   if (!DCI.isAfterLegalizeDAG())
12719     return SDValue();
12720 
12721   // If all users of SETCC extend its value to a legal integer type
12722   // then we replace SETCC with a subtraction
12723   for (SDNode::use_iterator UI = N->use_begin(),
12724        UE = N->use_end(); UI != UE; ++UI) {
12725     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12726       return SDValue();
12727   }
12728 
12729   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12730   auto OpSize = N->getOperand(0).getValueSizeInBits();
12731 
12732   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12733 
12734   if (OpSize < Size) {
12735     switch (CC) {
12736     default: break;
12737     case ISD::SETULT:
12738       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12739     case ISD::SETULE:
12740       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12741     case ISD::SETUGT:
12742       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12743     case ISD::SETUGE:
12744       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12745     }
12746   }
12747 
12748   return SDValue();
12749 }
12750 
12751 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12752                                                   DAGCombinerInfo &DCI) const {
12753   SelectionDAG &DAG = DCI.DAG;
12754   SDLoc dl(N);
12755 
12756   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12757   // If we're tracking CR bits, we need to be careful that we don't have:
12758   //   trunc(binary-ops(zext(x), zext(y)))
12759   // or
12760   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12761   // such that we're unnecessarily moving things into GPRs when it would be
12762   // better to keep them in CR bits.
12763 
12764   // Note that trunc here can be an actual i1 trunc, or can be the effective
12765   // truncation that comes from a setcc or select_cc.
12766   if (N->getOpcode() == ISD::TRUNCATE &&
12767       N->getValueType(0) != MVT::i1)
12768     return SDValue();
12769 
12770   if (N->getOperand(0).getValueType() != MVT::i32 &&
12771       N->getOperand(0).getValueType() != MVT::i64)
12772     return SDValue();
12773 
12774   if (N->getOpcode() == ISD::SETCC ||
12775       N->getOpcode() == ISD::SELECT_CC) {
12776     // If we're looking at a comparison, then we need to make sure that the
12777     // high bits (all except for the first) don't matter the result.
12778     ISD::CondCode CC =
12779       cast<CondCodeSDNode>(N->getOperand(
12780         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12781     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12782 
12783     if (ISD::isSignedIntSetCC(CC)) {
12784       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12785           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12786         return SDValue();
12787     } else if (ISD::isUnsignedIntSetCC(CC)) {
12788       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12789                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12790           !DAG.MaskedValueIsZero(N->getOperand(1),
12791                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12792         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12793                                              : SDValue());
12794     } else {
12795       // This is neither a signed nor an unsigned comparison, just make sure
12796       // that the high bits are equal.
12797       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12798       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12799 
12800       // We don't really care about what is known about the first bit (if
12801       // anything), so clear it in all masks prior to comparing them.
12802       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12803       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12804 
12805       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12806         return SDValue();
12807     }
12808   }
12809 
12810   // We now know that the higher-order bits are irrelevant, we just need to
12811   // make sure that all of the intermediate operations are bit operations, and
12812   // all inputs are extensions.
12813   if (N->getOperand(0).getOpcode() != ISD::AND &&
12814       N->getOperand(0).getOpcode() != ISD::OR  &&
12815       N->getOperand(0).getOpcode() != ISD::XOR &&
12816       N->getOperand(0).getOpcode() != ISD::SELECT &&
12817       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12818       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12819       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12820       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12821       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12822     return SDValue();
12823 
12824   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12825       N->getOperand(1).getOpcode() != ISD::AND &&
12826       N->getOperand(1).getOpcode() != ISD::OR  &&
12827       N->getOperand(1).getOpcode() != ISD::XOR &&
12828       N->getOperand(1).getOpcode() != ISD::SELECT &&
12829       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12830       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12831       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12832       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12833       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12834     return SDValue();
12835 
12836   SmallVector<SDValue, 4> Inputs;
12837   SmallVector<SDValue, 8> BinOps, PromOps;
12838   SmallPtrSet<SDNode *, 16> Visited;
12839 
12840   for (unsigned i = 0; i < 2; ++i) {
12841     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12842           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12843           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12844           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12845         isa<ConstantSDNode>(N->getOperand(i)))
12846       Inputs.push_back(N->getOperand(i));
12847     else
12848       BinOps.push_back(N->getOperand(i));
12849 
12850     if (N->getOpcode() == ISD::TRUNCATE)
12851       break;
12852   }
12853 
12854   // Visit all inputs, collect all binary operations (and, or, xor and
12855   // select) that are all fed by extensions.
12856   while (!BinOps.empty()) {
12857     SDValue BinOp = BinOps.back();
12858     BinOps.pop_back();
12859 
12860     if (!Visited.insert(BinOp.getNode()).second)
12861       continue;
12862 
12863     PromOps.push_back(BinOp);
12864 
12865     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12866       // The condition of the select is not promoted.
12867       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12868         continue;
12869       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12870         continue;
12871 
12872       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12873             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12874             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12875            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12876           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12877         Inputs.push_back(BinOp.getOperand(i));
12878       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12879                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12880                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12881                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12882                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12883                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12884                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12885                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12886                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12887         BinOps.push_back(BinOp.getOperand(i));
12888       } else {
12889         // We have an input that is not an extension or another binary
12890         // operation; we'll abort this transformation.
12891         return SDValue();
12892       }
12893     }
12894   }
12895 
12896   // Make sure that this is a self-contained cluster of operations (which
12897   // is not quite the same thing as saying that everything has only one
12898   // use).
12899   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12900     if (isa<ConstantSDNode>(Inputs[i]))
12901       continue;
12902 
12903     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12904                               UE = Inputs[i].getNode()->use_end();
12905          UI != UE; ++UI) {
12906       SDNode *User = *UI;
12907       if (User != N && !Visited.count(User))
12908         return SDValue();
12909 
12910       // Make sure that we're not going to promote the non-output-value
12911       // operand(s) or SELECT or SELECT_CC.
12912       // FIXME: Although we could sometimes handle this, and it does occur in
12913       // practice that one of the condition inputs to the select is also one of
12914       // the outputs, we currently can't deal with this.
12915       if (User->getOpcode() == ISD::SELECT) {
12916         if (User->getOperand(0) == Inputs[i])
12917           return SDValue();
12918       } else if (User->getOpcode() == ISD::SELECT_CC) {
12919         if (User->getOperand(0) == Inputs[i] ||
12920             User->getOperand(1) == Inputs[i])
12921           return SDValue();
12922       }
12923     }
12924   }
12925 
12926   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12927     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12928                               UE = PromOps[i].getNode()->use_end();
12929          UI != UE; ++UI) {
12930       SDNode *User = *UI;
12931       if (User != N && !Visited.count(User))
12932         return SDValue();
12933 
12934       // Make sure that we're not going to promote the non-output-value
12935       // operand(s) or SELECT or SELECT_CC.
12936       // FIXME: Although we could sometimes handle this, and it does occur in
12937       // practice that one of the condition inputs to the select is also one of
12938       // the outputs, we currently can't deal with this.
12939       if (User->getOpcode() == ISD::SELECT) {
12940         if (User->getOperand(0) == PromOps[i])
12941           return SDValue();
12942       } else if (User->getOpcode() == ISD::SELECT_CC) {
12943         if (User->getOperand(0) == PromOps[i] ||
12944             User->getOperand(1) == PromOps[i])
12945           return SDValue();
12946       }
12947     }
12948   }
12949 
12950   // Replace all inputs with the extension operand.
12951   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12952     // Constants may have users outside the cluster of to-be-promoted nodes,
12953     // and so we need to replace those as we do the promotions.
12954     if (isa<ConstantSDNode>(Inputs[i]))
12955       continue;
12956     else
12957       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12958   }
12959 
12960   std::list<HandleSDNode> PromOpHandles;
12961   for (auto &PromOp : PromOps)
12962     PromOpHandles.emplace_back(PromOp);
12963 
12964   // Replace all operations (these are all the same, but have a different
12965   // (i1) return type). DAG.getNode will validate that the types of
12966   // a binary operator match, so go through the list in reverse so that
12967   // we've likely promoted both operands first. Any intermediate truncations or
12968   // extensions disappear.
12969   while (!PromOpHandles.empty()) {
12970     SDValue PromOp = PromOpHandles.back().getValue();
12971     PromOpHandles.pop_back();
12972 
12973     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12974         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12975         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12976         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12977       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12978           PromOp.getOperand(0).getValueType() != MVT::i1) {
12979         // The operand is not yet ready (see comment below).
12980         PromOpHandles.emplace_front(PromOp);
12981         continue;
12982       }
12983 
12984       SDValue RepValue = PromOp.getOperand(0);
12985       if (isa<ConstantSDNode>(RepValue))
12986         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12987 
12988       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12989       continue;
12990     }
12991 
12992     unsigned C;
12993     switch (PromOp.getOpcode()) {
12994     default:             C = 0; break;
12995     case ISD::SELECT:    C = 1; break;
12996     case ISD::SELECT_CC: C = 2; break;
12997     }
12998 
12999     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13000          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13001         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13002          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13003       // The to-be-promoted operands of this node have not yet been
13004       // promoted (this should be rare because we're going through the
13005       // list backward, but if one of the operands has several users in
13006       // this cluster of to-be-promoted nodes, it is possible).
13007       PromOpHandles.emplace_front(PromOp);
13008       continue;
13009     }
13010 
13011     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13012                                 PromOp.getNode()->op_end());
13013 
13014     // If there are any constant inputs, make sure they're replaced now.
13015     for (unsigned i = 0; i < 2; ++i)
13016       if (isa<ConstantSDNode>(Ops[C+i]))
13017         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13018 
13019     DAG.ReplaceAllUsesOfValueWith(PromOp,
13020       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13021   }
13022 
13023   // Now we're left with the initial truncation itself.
13024   if (N->getOpcode() == ISD::TRUNCATE)
13025     return N->getOperand(0);
13026 
13027   // Otherwise, this is a comparison. The operands to be compared have just
13028   // changed type (to i1), but everything else is the same.
13029   return SDValue(N, 0);
13030 }
13031 
13032 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13033                                                   DAGCombinerInfo &DCI) const {
13034   SelectionDAG &DAG = DCI.DAG;
13035   SDLoc dl(N);
13036 
13037   // If we're tracking CR bits, we need to be careful that we don't have:
13038   //   zext(binary-ops(trunc(x), trunc(y)))
13039   // or
13040   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13041   // such that we're unnecessarily moving things into CR bits that can more
13042   // efficiently stay in GPRs. Note that if we're not certain that the high
13043   // bits are set as required by the final extension, we still may need to do
13044   // some masking to get the proper behavior.
13045 
13046   // This same functionality is important on PPC64 when dealing with
13047   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13048   // the return values of functions. Because it is so similar, it is handled
13049   // here as well.
13050 
13051   if (N->getValueType(0) != MVT::i32 &&
13052       N->getValueType(0) != MVT::i64)
13053     return SDValue();
13054 
13055   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13056         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13057     return SDValue();
13058 
13059   if (N->getOperand(0).getOpcode() != ISD::AND &&
13060       N->getOperand(0).getOpcode() != ISD::OR  &&
13061       N->getOperand(0).getOpcode() != ISD::XOR &&
13062       N->getOperand(0).getOpcode() != ISD::SELECT &&
13063       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13064     return SDValue();
13065 
13066   SmallVector<SDValue, 4> Inputs;
13067   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13068   SmallPtrSet<SDNode *, 16> Visited;
13069 
13070   // Visit all inputs, collect all binary operations (and, or, xor and
13071   // select) that are all fed by truncations.
13072   while (!BinOps.empty()) {
13073     SDValue BinOp = BinOps.back();
13074     BinOps.pop_back();
13075 
13076     if (!Visited.insert(BinOp.getNode()).second)
13077       continue;
13078 
13079     PromOps.push_back(BinOp);
13080 
13081     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13082       // The condition of the select is not promoted.
13083       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13084         continue;
13085       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13086         continue;
13087 
13088       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13089           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13090         Inputs.push_back(BinOp.getOperand(i));
13091       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13092                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13093                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13094                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13095                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13096         BinOps.push_back(BinOp.getOperand(i));
13097       } else {
13098         // We have an input that is not a truncation or another binary
13099         // operation; we'll abort this transformation.
13100         return SDValue();
13101       }
13102     }
13103   }
13104 
13105   // The operands of a select that must be truncated when the select is
13106   // promoted because the operand is actually part of the to-be-promoted set.
13107   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13108 
13109   // Make sure that this is a self-contained cluster of operations (which
13110   // is not quite the same thing as saying that everything has only one
13111   // use).
13112   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13113     if (isa<ConstantSDNode>(Inputs[i]))
13114       continue;
13115 
13116     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13117                               UE = Inputs[i].getNode()->use_end();
13118          UI != UE; ++UI) {
13119       SDNode *User = *UI;
13120       if (User != N && !Visited.count(User))
13121         return SDValue();
13122 
13123       // If we're going to promote the non-output-value operand(s) or SELECT or
13124       // SELECT_CC, record them for truncation.
13125       if (User->getOpcode() == ISD::SELECT) {
13126         if (User->getOperand(0) == Inputs[i])
13127           SelectTruncOp[0].insert(std::make_pair(User,
13128                                     User->getOperand(0).getValueType()));
13129       } else if (User->getOpcode() == ISD::SELECT_CC) {
13130         if (User->getOperand(0) == Inputs[i])
13131           SelectTruncOp[0].insert(std::make_pair(User,
13132                                     User->getOperand(0).getValueType()));
13133         if (User->getOperand(1) == Inputs[i])
13134           SelectTruncOp[1].insert(std::make_pair(User,
13135                                     User->getOperand(1).getValueType()));
13136       }
13137     }
13138   }
13139 
13140   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13141     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13142                               UE = PromOps[i].getNode()->use_end();
13143          UI != UE; ++UI) {
13144       SDNode *User = *UI;
13145       if (User != N && !Visited.count(User))
13146         return SDValue();
13147 
13148       // If we're going to promote the non-output-value operand(s) or SELECT or
13149       // SELECT_CC, record them for truncation.
13150       if (User->getOpcode() == ISD::SELECT) {
13151         if (User->getOperand(0) == PromOps[i])
13152           SelectTruncOp[0].insert(std::make_pair(User,
13153                                     User->getOperand(0).getValueType()));
13154       } else if (User->getOpcode() == ISD::SELECT_CC) {
13155         if (User->getOperand(0) == PromOps[i])
13156           SelectTruncOp[0].insert(std::make_pair(User,
13157                                     User->getOperand(0).getValueType()));
13158         if (User->getOperand(1) == PromOps[i])
13159           SelectTruncOp[1].insert(std::make_pair(User,
13160                                     User->getOperand(1).getValueType()));
13161       }
13162     }
13163   }
13164 
13165   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13166   bool ReallyNeedsExt = false;
13167   if (N->getOpcode() != ISD::ANY_EXTEND) {
13168     // If all of the inputs are not already sign/zero extended, then
13169     // we'll still need to do that at the end.
13170     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13171       if (isa<ConstantSDNode>(Inputs[i]))
13172         continue;
13173 
13174       unsigned OpBits =
13175         Inputs[i].getOperand(0).getValueSizeInBits();
13176       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13177 
13178       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13179            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13180                                   APInt::getHighBitsSet(OpBits,
13181                                                         OpBits-PromBits))) ||
13182           (N->getOpcode() == ISD::SIGN_EXTEND &&
13183            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13184              (OpBits-(PromBits-1)))) {
13185         ReallyNeedsExt = true;
13186         break;
13187       }
13188     }
13189   }
13190 
13191   // Replace all inputs, either with the truncation operand, or a
13192   // truncation or extension to the final output type.
13193   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13194     // Constant inputs need to be replaced with the to-be-promoted nodes that
13195     // use them because they might have users outside of the cluster of
13196     // promoted nodes.
13197     if (isa<ConstantSDNode>(Inputs[i]))
13198       continue;
13199 
13200     SDValue InSrc = Inputs[i].getOperand(0);
13201     if (Inputs[i].getValueType() == N->getValueType(0))
13202       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13203     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13204       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13205         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13206     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13207       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13208         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13209     else
13210       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13211         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13212   }
13213 
13214   std::list<HandleSDNode> PromOpHandles;
13215   for (auto &PromOp : PromOps)
13216     PromOpHandles.emplace_back(PromOp);
13217 
13218   // Replace all operations (these are all the same, but have a different
13219   // (promoted) return type). DAG.getNode will validate that the types of
13220   // a binary operator match, so go through the list in reverse so that
13221   // we've likely promoted both operands first.
13222   while (!PromOpHandles.empty()) {
13223     SDValue PromOp = PromOpHandles.back().getValue();
13224     PromOpHandles.pop_back();
13225 
13226     unsigned C;
13227     switch (PromOp.getOpcode()) {
13228     default:             C = 0; break;
13229     case ISD::SELECT:    C = 1; break;
13230     case ISD::SELECT_CC: C = 2; break;
13231     }
13232 
13233     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13234          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13235         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13236          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13237       // The to-be-promoted operands of this node have not yet been
13238       // promoted (this should be rare because we're going through the
13239       // list backward, but if one of the operands has several users in
13240       // this cluster of to-be-promoted nodes, it is possible).
13241       PromOpHandles.emplace_front(PromOp);
13242       continue;
13243     }
13244 
13245     // For SELECT and SELECT_CC nodes, we do a similar check for any
13246     // to-be-promoted comparison inputs.
13247     if (PromOp.getOpcode() == ISD::SELECT ||
13248         PromOp.getOpcode() == ISD::SELECT_CC) {
13249       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13250            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13251           (SelectTruncOp[1].count(PromOp.getNode()) &&
13252            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13253         PromOpHandles.emplace_front(PromOp);
13254         continue;
13255       }
13256     }
13257 
13258     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13259                                 PromOp.getNode()->op_end());
13260 
13261     // If this node has constant inputs, then they'll need to be promoted here.
13262     for (unsigned i = 0; i < 2; ++i) {
13263       if (!isa<ConstantSDNode>(Ops[C+i]))
13264         continue;
13265       if (Ops[C+i].getValueType() == N->getValueType(0))
13266         continue;
13267 
13268       if (N->getOpcode() == ISD::SIGN_EXTEND)
13269         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13270       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13271         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13272       else
13273         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13274     }
13275 
13276     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13277     // truncate them again to the original value type.
13278     if (PromOp.getOpcode() == ISD::SELECT ||
13279         PromOp.getOpcode() == ISD::SELECT_CC) {
13280       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13281       if (SI0 != SelectTruncOp[0].end())
13282         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13283       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13284       if (SI1 != SelectTruncOp[1].end())
13285         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13286     }
13287 
13288     DAG.ReplaceAllUsesOfValueWith(PromOp,
13289       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13290   }
13291 
13292   // Now we're left with the initial extension itself.
13293   if (!ReallyNeedsExt)
13294     return N->getOperand(0);
13295 
13296   // To zero extend, just mask off everything except for the first bit (in the
13297   // i1 case).
13298   if (N->getOpcode() == ISD::ZERO_EXTEND)
13299     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13300                        DAG.getConstant(APInt::getLowBitsSet(
13301                                          N->getValueSizeInBits(0), PromBits),
13302                                        dl, N->getValueType(0)));
13303 
13304   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13305          "Invalid extension type");
13306   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13307   SDValue ShiftCst =
13308       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13309   return DAG.getNode(
13310       ISD::SRA, dl, N->getValueType(0),
13311       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13312       ShiftCst);
13313 }
13314 
13315 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13316                                         DAGCombinerInfo &DCI) const {
13317   assert(N->getOpcode() == ISD::SETCC &&
13318          "Should be called with a SETCC node");
13319 
13320   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13321   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13322     SDValue LHS = N->getOperand(0);
13323     SDValue RHS = N->getOperand(1);
13324 
13325     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13326     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13327         LHS.hasOneUse())
13328       std::swap(LHS, RHS);
13329 
13330     // x == 0-y --> x+y == 0
13331     // x != 0-y --> x+y != 0
13332     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13333         RHS.hasOneUse()) {
13334       SDLoc DL(N);
13335       SelectionDAG &DAG = DCI.DAG;
13336       EVT VT = N->getValueType(0);
13337       EVT OpVT = LHS.getValueType();
13338       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13339       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13340     }
13341   }
13342 
13343   return DAGCombineTruncBoolExt(N, DCI);
13344 }
13345 
13346 // Is this an extending load from an f32 to an f64?
13347 static bool isFPExtLoad(SDValue Op) {
13348   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13349     return LD->getExtensionType() == ISD::EXTLOAD &&
13350       Op.getValueType() == MVT::f64;
13351   return false;
13352 }
13353 
13354 /// Reduces the number of fp-to-int conversion when building a vector.
13355 ///
13356 /// If this vector is built out of floating to integer conversions,
13357 /// transform it to a vector built out of floating point values followed by a
13358 /// single floating to integer conversion of the vector.
13359 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13360 /// becomes (fptosi (build_vector ($A, $B, ...)))
13361 SDValue PPCTargetLowering::
13362 combineElementTruncationToVectorTruncation(SDNode *N,
13363                                            DAGCombinerInfo &DCI) const {
13364   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13365          "Should be called with a BUILD_VECTOR node");
13366 
13367   SelectionDAG &DAG = DCI.DAG;
13368   SDLoc dl(N);
13369 
13370   SDValue FirstInput = N->getOperand(0);
13371   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13372          "The input operand must be an fp-to-int conversion.");
13373 
13374   // This combine happens after legalization so the fp_to_[su]i nodes are
13375   // already converted to PPCSISD nodes.
13376   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13377   if (FirstConversion == PPCISD::FCTIDZ ||
13378       FirstConversion == PPCISD::FCTIDUZ ||
13379       FirstConversion == PPCISD::FCTIWZ ||
13380       FirstConversion == PPCISD::FCTIWUZ) {
13381     bool IsSplat = true;
13382     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13383       FirstConversion == PPCISD::FCTIWUZ;
13384     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13385     SmallVector<SDValue, 4> Ops;
13386     EVT TargetVT = N->getValueType(0);
13387     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13388       SDValue NextOp = N->getOperand(i);
13389       if (NextOp.getOpcode() != PPCISD::MFVSR)
13390         return SDValue();
13391       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13392       if (NextConversion != FirstConversion)
13393         return SDValue();
13394       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13395       // This is not valid if the input was originally double precision. It is
13396       // also not profitable to do unless this is an extending load in which
13397       // case doing this combine will allow us to combine consecutive loads.
13398       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13399         return SDValue();
13400       if (N->getOperand(i) != FirstInput)
13401         IsSplat = false;
13402     }
13403 
13404     // If this is a splat, we leave it as-is since there will be only a single
13405     // fp-to-int conversion followed by a splat of the integer. This is better
13406     // for 32-bit and smaller ints and neutral for 64-bit ints.
13407     if (IsSplat)
13408       return SDValue();
13409 
13410     // Now that we know we have the right type of node, get its operands
13411     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13412       SDValue In = N->getOperand(i).getOperand(0);
13413       if (Is32Bit) {
13414         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13415         // here, we know that all inputs are extending loads so this is safe).
13416         if (In.isUndef())
13417           Ops.push_back(DAG.getUNDEF(SrcVT));
13418         else {
13419           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13420                                       MVT::f32, In.getOperand(0),
13421                                       DAG.getIntPtrConstant(1, dl));
13422           Ops.push_back(Trunc);
13423         }
13424       } else
13425         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13426     }
13427 
13428     unsigned Opcode;
13429     if (FirstConversion == PPCISD::FCTIDZ ||
13430         FirstConversion == PPCISD::FCTIWZ)
13431       Opcode = ISD::FP_TO_SINT;
13432     else
13433       Opcode = ISD::FP_TO_UINT;
13434 
13435     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13436     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13437     return DAG.getNode(Opcode, dl, TargetVT, BV);
13438   }
13439   return SDValue();
13440 }
13441 
13442 /// Reduce the number of loads when building a vector.
13443 ///
13444 /// Building a vector out of multiple loads can be converted to a load
13445 /// of the vector type if the loads are consecutive. If the loads are
13446 /// consecutive but in descending order, a shuffle is added at the end
13447 /// to reorder the vector.
13448 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13449   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13450          "Should be called with a BUILD_VECTOR node");
13451 
13452   SDLoc dl(N);
13453 
13454   // Return early for non byte-sized type, as they can't be consecutive.
13455   if (!N->getValueType(0).getVectorElementType().isByteSized())
13456     return SDValue();
13457 
13458   bool InputsAreConsecutiveLoads = true;
13459   bool InputsAreReverseConsecutive = true;
13460   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13461   SDValue FirstInput = N->getOperand(0);
13462   bool IsRoundOfExtLoad = false;
13463 
13464   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13465       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13466     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13467     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13468   }
13469   // Not a build vector of (possibly fp_rounded) loads.
13470   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13471       N->getNumOperands() == 1)
13472     return SDValue();
13473 
13474   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13475     // If any inputs are fp_round(extload), they all must be.
13476     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13477       return SDValue();
13478 
13479     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13480       N->getOperand(i);
13481     if (NextInput.getOpcode() != ISD::LOAD)
13482       return SDValue();
13483 
13484     SDValue PreviousInput =
13485       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13486     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13487     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13488 
13489     // If any inputs are fp_round(extload), they all must be.
13490     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13491       return SDValue();
13492 
13493     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13494       InputsAreConsecutiveLoads = false;
13495     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13496       InputsAreReverseConsecutive = false;
13497 
13498     // Exit early if the loads are neither consecutive nor reverse consecutive.
13499     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13500       return SDValue();
13501   }
13502 
13503   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13504          "The loads cannot be both consecutive and reverse consecutive.");
13505 
13506   SDValue FirstLoadOp =
13507     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13508   SDValue LastLoadOp =
13509     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13510                        N->getOperand(N->getNumOperands()-1);
13511 
13512   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13513   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13514   if (InputsAreConsecutiveLoads) {
13515     assert(LD1 && "Input needs to be a LoadSDNode.");
13516     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13517                        LD1->getBasePtr(), LD1->getPointerInfo(),
13518                        LD1->getAlignment());
13519   }
13520   if (InputsAreReverseConsecutive) {
13521     assert(LDL && "Input needs to be a LoadSDNode.");
13522     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13523                                LDL->getBasePtr(), LDL->getPointerInfo(),
13524                                LDL->getAlignment());
13525     SmallVector<int, 16> Ops;
13526     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13527       Ops.push_back(i);
13528 
13529     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13530                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13531   }
13532   return SDValue();
13533 }
13534 
13535 // This function adds the required vector_shuffle needed to get
13536 // the elements of the vector extract in the correct position
13537 // as specified by the CorrectElems encoding.
13538 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13539                                       SDValue Input, uint64_t Elems,
13540                                       uint64_t CorrectElems) {
13541   SDLoc dl(N);
13542 
13543   unsigned NumElems = Input.getValueType().getVectorNumElements();
13544   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13545 
13546   // Knowing the element indices being extracted from the original
13547   // vector and the order in which they're being inserted, just put
13548   // them at element indices required for the instruction.
13549   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13550     if (DAG.getDataLayout().isLittleEndian())
13551       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13552     else
13553       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13554     CorrectElems = CorrectElems >> 8;
13555     Elems = Elems >> 8;
13556   }
13557 
13558   SDValue Shuffle =
13559       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13560                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13561 
13562   EVT VT = N->getValueType(0);
13563   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13564 
13565   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13566                                Input.getValueType().getVectorElementType(),
13567                                VT.getVectorNumElements());
13568   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13569                      DAG.getValueType(ExtVT));
13570 }
13571 
13572 // Look for build vector patterns where input operands come from sign
13573 // extended vector_extract elements of specific indices. If the correct indices
13574 // aren't used, add a vector shuffle to fix up the indices and create
13575 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13576 // during instruction selection.
13577 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13578   // This array encodes the indices that the vector sign extend instructions
13579   // extract from when extending from one type to another for both BE and LE.
13580   // The right nibble of each byte corresponds to the LE incides.
13581   // and the left nibble of each byte corresponds to the BE incides.
13582   // For example: 0x3074B8FC  byte->word
13583   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13584   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13585   // For example: 0x000070F8  byte->double word
13586   // For LE: the allowed indices are: 0x0,0x8
13587   // For BE: the allowed indices are: 0x7,0xF
13588   uint64_t TargetElems[] = {
13589       0x3074B8FC, // b->w
13590       0x000070F8, // b->d
13591       0x10325476, // h->w
13592       0x00003074, // h->d
13593       0x00001032, // w->d
13594   };
13595 
13596   uint64_t Elems = 0;
13597   int Index;
13598   SDValue Input;
13599 
13600   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13601     if (!Op)
13602       return false;
13603     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13604         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13605       return false;
13606 
13607     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13608     // of the right width.
13609     SDValue Extract = Op.getOperand(0);
13610     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13611       Extract = Extract.getOperand(0);
13612     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13613       return false;
13614 
13615     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13616     if (!ExtOp)
13617       return false;
13618 
13619     Index = ExtOp->getZExtValue();
13620     if (Input && Input != Extract.getOperand(0))
13621       return false;
13622 
13623     if (!Input)
13624       Input = Extract.getOperand(0);
13625 
13626     Elems = Elems << 8;
13627     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13628     Elems |= Index;
13629 
13630     return true;
13631   };
13632 
13633   // If the build vector operands aren't sign extended vector extracts,
13634   // of the same input vector, then return.
13635   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13636     if (!isSExtOfVecExtract(N->getOperand(i))) {
13637       return SDValue();
13638     }
13639   }
13640 
13641   // If the vector extract indicies are not correct, add the appropriate
13642   // vector_shuffle.
13643   int TgtElemArrayIdx;
13644   int InputSize = Input.getValueType().getScalarSizeInBits();
13645   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13646   if (InputSize + OutputSize == 40)
13647     TgtElemArrayIdx = 0;
13648   else if (InputSize + OutputSize == 72)
13649     TgtElemArrayIdx = 1;
13650   else if (InputSize + OutputSize == 48)
13651     TgtElemArrayIdx = 2;
13652   else if (InputSize + OutputSize == 80)
13653     TgtElemArrayIdx = 3;
13654   else if (InputSize + OutputSize == 96)
13655     TgtElemArrayIdx = 4;
13656   else
13657     return SDValue();
13658 
13659   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13660   CorrectElems = DAG.getDataLayout().isLittleEndian()
13661                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13662                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13663   if (Elems != CorrectElems) {
13664     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13665   }
13666 
13667   // Regular lowering will catch cases where a shuffle is not needed.
13668   return SDValue();
13669 }
13670 
13671 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13672                                                  DAGCombinerInfo &DCI) const {
13673   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13674          "Should be called with a BUILD_VECTOR node");
13675 
13676   SelectionDAG &DAG = DCI.DAG;
13677   SDLoc dl(N);
13678 
13679   if (!Subtarget.hasVSX())
13680     return SDValue();
13681 
13682   // The target independent DAG combiner will leave a build_vector of
13683   // float-to-int conversions intact. We can generate MUCH better code for
13684   // a float-to-int conversion of a vector of floats.
13685   SDValue FirstInput = N->getOperand(0);
13686   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13687     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13688     if (Reduced)
13689       return Reduced;
13690   }
13691 
13692   // If we're building a vector out of consecutive loads, just load that
13693   // vector type.
13694   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13695   if (Reduced)
13696     return Reduced;
13697 
13698   // If we're building a vector out of extended elements from another vector
13699   // we have P9 vector integer extend instructions. The code assumes legal
13700   // input types (i.e. it can't handle things like v4i16) so do not run before
13701   // legalization.
13702   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13703     Reduced = combineBVOfVecSExt(N, DAG);
13704     if (Reduced)
13705       return Reduced;
13706   }
13707 
13708 
13709   if (N->getValueType(0) != MVT::v2f64)
13710     return SDValue();
13711 
13712   // Looking for:
13713   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13714   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13715       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13716     return SDValue();
13717   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13718       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13719     return SDValue();
13720   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13721     return SDValue();
13722 
13723   SDValue Ext1 = FirstInput.getOperand(0);
13724   SDValue Ext2 = N->getOperand(1).getOperand(0);
13725   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13726      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13727     return SDValue();
13728 
13729   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13730   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13731   if (!Ext1Op || !Ext2Op)
13732     return SDValue();
13733   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13734       Ext1.getOperand(0) != Ext2.getOperand(0))
13735     return SDValue();
13736 
13737   int FirstElem = Ext1Op->getZExtValue();
13738   int SecondElem = Ext2Op->getZExtValue();
13739   int SubvecIdx;
13740   if (FirstElem == 0 && SecondElem == 1)
13741     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13742   else if (FirstElem == 2 && SecondElem == 3)
13743     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13744   else
13745     return SDValue();
13746 
13747   SDValue SrcVec = Ext1.getOperand(0);
13748   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13749     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13750   return DAG.getNode(NodeType, dl, MVT::v2f64,
13751                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13752 }
13753 
13754 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13755                                               DAGCombinerInfo &DCI) const {
13756   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13757           N->getOpcode() == ISD::UINT_TO_FP) &&
13758          "Need an int -> FP conversion node here");
13759 
13760   if (useSoftFloat() || !Subtarget.has64BitSupport())
13761     return SDValue();
13762 
13763   SelectionDAG &DAG = DCI.DAG;
13764   SDLoc dl(N);
13765   SDValue Op(N, 0);
13766 
13767   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13768   // from the hardware.
13769   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13770     return SDValue();
13771   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13772       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13773     return SDValue();
13774 
13775   SDValue FirstOperand(Op.getOperand(0));
13776   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13777     (FirstOperand.getValueType() == MVT::i8 ||
13778      FirstOperand.getValueType() == MVT::i16);
13779   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13780     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13781     bool DstDouble = Op.getValueType() == MVT::f64;
13782     unsigned ConvOp = Signed ?
13783       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13784       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13785     SDValue WidthConst =
13786       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13787                             dl, false);
13788     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13789     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13790     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13791                                          DAG.getVTList(MVT::f64, MVT::Other),
13792                                          Ops, MVT::i8, LDN->getMemOperand());
13793 
13794     // For signed conversion, we need to sign-extend the value in the VSR
13795     if (Signed) {
13796       SDValue ExtOps[] = { Ld, WidthConst };
13797       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13798       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13799     } else
13800       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13801   }
13802 
13803 
13804   // For i32 intermediate values, unfortunately, the conversion functions
13805   // leave the upper 32 bits of the value are undefined. Within the set of
13806   // scalar instructions, we have no method for zero- or sign-extending the
13807   // value. Thus, we cannot handle i32 intermediate values here.
13808   if (Op.getOperand(0).getValueType() == MVT::i32)
13809     return SDValue();
13810 
13811   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13812          "UINT_TO_FP is supported only with FPCVT");
13813 
13814   // If we have FCFIDS, then use it when converting to single-precision.
13815   // Otherwise, convert to double-precision and then round.
13816   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13817                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13818                                                             : PPCISD::FCFIDS)
13819                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13820                                                             : PPCISD::FCFID);
13821   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13822                   ? MVT::f32
13823                   : MVT::f64;
13824 
13825   // If we're converting from a float, to an int, and back to a float again,
13826   // then we don't need the store/load pair at all.
13827   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13828        Subtarget.hasFPCVT()) ||
13829       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13830     SDValue Src = Op.getOperand(0).getOperand(0);
13831     if (Src.getValueType() == MVT::f32) {
13832       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13833       DCI.AddToWorklist(Src.getNode());
13834     } else if (Src.getValueType() != MVT::f64) {
13835       // Make sure that we don't pick up a ppc_fp128 source value.
13836       return SDValue();
13837     }
13838 
13839     unsigned FCTOp =
13840       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13841                                                         PPCISD::FCTIDUZ;
13842 
13843     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13844     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13845 
13846     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13847       FP = DAG.getNode(ISD::FP_ROUND, dl,
13848                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13849       DCI.AddToWorklist(FP.getNode());
13850     }
13851 
13852     return FP;
13853   }
13854 
13855   return SDValue();
13856 }
13857 
13858 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13859 // builtins) into loads with swaps.
13860 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13861                                               DAGCombinerInfo &DCI) const {
13862   SelectionDAG &DAG = DCI.DAG;
13863   SDLoc dl(N);
13864   SDValue Chain;
13865   SDValue Base;
13866   MachineMemOperand *MMO;
13867 
13868   switch (N->getOpcode()) {
13869   default:
13870     llvm_unreachable("Unexpected opcode for little endian VSX load");
13871   case ISD::LOAD: {
13872     LoadSDNode *LD = cast<LoadSDNode>(N);
13873     Chain = LD->getChain();
13874     Base = LD->getBasePtr();
13875     MMO = LD->getMemOperand();
13876     // If the MMO suggests this isn't a load of a full vector, leave
13877     // things alone.  For a built-in, we have to make the change for
13878     // correctness, so if there is a size problem that will be a bug.
13879     if (MMO->getSize() < 16)
13880       return SDValue();
13881     break;
13882   }
13883   case ISD::INTRINSIC_W_CHAIN: {
13884     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13885     Chain = Intrin->getChain();
13886     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13887     // us what we want. Get operand 2 instead.
13888     Base = Intrin->getOperand(2);
13889     MMO = Intrin->getMemOperand();
13890     break;
13891   }
13892   }
13893 
13894   MVT VecTy = N->getValueType(0).getSimpleVT();
13895 
13896   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13897   // aligned and the type is a vector with elements up to 4 bytes
13898   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13899       VecTy.getScalarSizeInBits() <= 32) {
13900     return SDValue();
13901   }
13902 
13903   SDValue LoadOps[] = { Chain, Base };
13904   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13905                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13906                                          LoadOps, MVT::v2f64, MMO);
13907 
13908   DCI.AddToWorklist(Load.getNode());
13909   Chain = Load.getValue(1);
13910   SDValue Swap = DAG.getNode(
13911       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13912   DCI.AddToWorklist(Swap.getNode());
13913 
13914   // Add a bitcast if the resulting load type doesn't match v2f64.
13915   if (VecTy != MVT::v2f64) {
13916     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13917     DCI.AddToWorklist(N.getNode());
13918     // Package {bitcast value, swap's chain} to match Load's shape.
13919     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13920                        N, Swap.getValue(1));
13921   }
13922 
13923   return Swap;
13924 }
13925 
13926 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13927 // builtins) into stores with swaps.
13928 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13929                                                DAGCombinerInfo &DCI) const {
13930   SelectionDAG &DAG = DCI.DAG;
13931   SDLoc dl(N);
13932   SDValue Chain;
13933   SDValue Base;
13934   unsigned SrcOpnd;
13935   MachineMemOperand *MMO;
13936 
13937   switch (N->getOpcode()) {
13938   default:
13939     llvm_unreachable("Unexpected opcode for little endian VSX store");
13940   case ISD::STORE: {
13941     StoreSDNode *ST = cast<StoreSDNode>(N);
13942     Chain = ST->getChain();
13943     Base = ST->getBasePtr();
13944     MMO = ST->getMemOperand();
13945     SrcOpnd = 1;
13946     // If the MMO suggests this isn't a store of a full vector, leave
13947     // things alone.  For a built-in, we have to make the change for
13948     // correctness, so if there is a size problem that will be a bug.
13949     if (MMO->getSize() < 16)
13950       return SDValue();
13951     break;
13952   }
13953   case ISD::INTRINSIC_VOID: {
13954     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13955     Chain = Intrin->getChain();
13956     // Intrin->getBasePtr() oddly does not get what we want.
13957     Base = Intrin->getOperand(3);
13958     MMO = Intrin->getMemOperand();
13959     SrcOpnd = 2;
13960     break;
13961   }
13962   }
13963 
13964   SDValue Src = N->getOperand(SrcOpnd);
13965   MVT VecTy = Src.getValueType().getSimpleVT();
13966 
13967   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13968   // aligned and the type is a vector with elements up to 4 bytes
13969   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13970       VecTy.getScalarSizeInBits() <= 32) {
13971     return SDValue();
13972   }
13973 
13974   // All stores are done as v2f64 and possible bit cast.
13975   if (VecTy != MVT::v2f64) {
13976     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13977     DCI.AddToWorklist(Src.getNode());
13978   }
13979 
13980   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13981                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13982   DCI.AddToWorklist(Swap.getNode());
13983   Chain = Swap.getValue(1);
13984   SDValue StoreOps[] = { Chain, Swap, Base };
13985   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13986                                           DAG.getVTList(MVT::Other),
13987                                           StoreOps, VecTy, MMO);
13988   DCI.AddToWorklist(Store.getNode());
13989   return Store;
13990 }
13991 
13992 // Handle DAG combine for STORE (FP_TO_INT F).
13993 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13994                                                DAGCombinerInfo &DCI) const {
13995 
13996   SelectionDAG &DAG = DCI.DAG;
13997   SDLoc dl(N);
13998   unsigned Opcode = N->getOperand(1).getOpcode();
13999 
14000   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14001          && "Not a FP_TO_INT Instruction!");
14002 
14003   SDValue Val = N->getOperand(1).getOperand(0);
14004   EVT Op1VT = N->getOperand(1).getValueType();
14005   EVT ResVT = Val.getValueType();
14006 
14007   // Floating point types smaller than 32 bits are not legal on Power.
14008   if (ResVT.getScalarSizeInBits() < 32)
14009     return SDValue();
14010 
14011   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14012   bool ValidTypeForStoreFltAsInt =
14013         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14014          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14015 
14016   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14017       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14018     return SDValue();
14019 
14020   // Extend f32 values to f64
14021   if (ResVT.getScalarSizeInBits() == 32) {
14022     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14023     DCI.AddToWorklist(Val.getNode());
14024   }
14025 
14026   // Set signed or unsigned conversion opcode.
14027   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14028                           PPCISD::FP_TO_SINT_IN_VSR :
14029                           PPCISD::FP_TO_UINT_IN_VSR;
14030 
14031   Val = DAG.getNode(ConvOpcode,
14032                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14033   DCI.AddToWorklist(Val.getNode());
14034 
14035   // Set number of bytes being converted.
14036   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14037   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14038                     DAG.getIntPtrConstant(ByteSize, dl, false),
14039                     DAG.getValueType(Op1VT) };
14040 
14041   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14042           DAG.getVTList(MVT::Other), Ops,
14043           cast<StoreSDNode>(N)->getMemoryVT(),
14044           cast<StoreSDNode>(N)->getMemOperand());
14045 
14046   DCI.AddToWorklist(Val.getNode());
14047   return Val;
14048 }
14049 
14050 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14051                                                 LSBaseSDNode *LSBase,
14052                                                 DAGCombinerInfo &DCI) const {
14053   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14054         "Not a reverse memop pattern!");
14055 
14056   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14057     auto Mask = SVN->getMask();
14058     int i = 0;
14059     auto I = Mask.rbegin();
14060     auto E = Mask.rend();
14061 
14062     for (; I != E; ++I) {
14063       if (*I != i)
14064         return false;
14065       i++;
14066     }
14067     return true;
14068   };
14069 
14070   SelectionDAG &DAG = DCI.DAG;
14071   EVT VT = SVN->getValueType(0);
14072 
14073   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14074     return SDValue();
14075 
14076   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14077   // See comment in PPCVSXSwapRemoval.cpp.
14078   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14079   if (!Subtarget.hasP9Vector())
14080     return SDValue();
14081 
14082   if(!IsElementReverse(SVN))
14083     return SDValue();
14084 
14085   if (LSBase->getOpcode() == ISD::LOAD) {
14086     SDLoc dl(SVN);
14087     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14088     return DAG.getMemIntrinsicNode(
14089         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14090         LSBase->getMemoryVT(), LSBase->getMemOperand());
14091   }
14092 
14093   if (LSBase->getOpcode() == ISD::STORE) {
14094     SDLoc dl(LSBase);
14095     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14096                           LSBase->getBasePtr()};
14097     return DAG.getMemIntrinsicNode(
14098         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14099         LSBase->getMemoryVT(), LSBase->getMemOperand());
14100   }
14101 
14102   llvm_unreachable("Expected a load or store node here");
14103 }
14104 
14105 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14106                                              DAGCombinerInfo &DCI) const {
14107   SelectionDAG &DAG = DCI.DAG;
14108   SDLoc dl(N);
14109   switch (N->getOpcode()) {
14110   default: break;
14111   case ISD::ADD:
14112     return combineADD(N, DCI);
14113   case ISD::SHL:
14114     return combineSHL(N, DCI);
14115   case ISD::SRA:
14116     return combineSRA(N, DCI);
14117   case ISD::SRL:
14118     return combineSRL(N, DCI);
14119   case ISD::MUL:
14120     return combineMUL(N, DCI);
14121   case ISD::FMA:
14122   case PPCISD::FNMSUB:
14123     return combineFMALike(N, DCI);
14124   case PPCISD::SHL:
14125     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14126         return N->getOperand(0);
14127     break;
14128   case PPCISD::SRL:
14129     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14130         return N->getOperand(0);
14131     break;
14132   case PPCISD::SRA:
14133     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14134       if (C->isNullValue() ||   //  0 >>s V -> 0.
14135           C->isAllOnesValue())    // -1 >>s V -> -1.
14136         return N->getOperand(0);
14137     }
14138     break;
14139   case ISD::SIGN_EXTEND:
14140   case ISD::ZERO_EXTEND:
14141   case ISD::ANY_EXTEND:
14142     return DAGCombineExtBoolTrunc(N, DCI);
14143   case ISD::TRUNCATE:
14144     return combineTRUNCATE(N, DCI);
14145   case ISD::SETCC:
14146     if (SDValue CSCC = combineSetCC(N, DCI))
14147       return CSCC;
14148     LLVM_FALLTHROUGH;
14149   case ISD::SELECT_CC:
14150     return DAGCombineTruncBoolExt(N, DCI);
14151   case ISD::SINT_TO_FP:
14152   case ISD::UINT_TO_FP:
14153     return combineFPToIntToFP(N, DCI);
14154   case ISD::VECTOR_SHUFFLE:
14155     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14156       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14157       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14158     }
14159     break;
14160   case ISD::STORE: {
14161 
14162     EVT Op1VT = N->getOperand(1).getValueType();
14163     unsigned Opcode = N->getOperand(1).getOpcode();
14164 
14165     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14166       SDValue Val= combineStoreFPToInt(N, DCI);
14167       if (Val)
14168         return Val;
14169     }
14170 
14171     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14172       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14173       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14174       if (Val)
14175         return Val;
14176     }
14177 
14178     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14179     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14180         N->getOperand(1).getNode()->hasOneUse() &&
14181         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14182          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14183 
14184       // STBRX can only handle simple types and it makes no sense to store less
14185       // two bytes in byte-reversed order.
14186       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14187       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14188         break;
14189 
14190       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14191       // Do an any-extend to 32-bits if this is a half-word input.
14192       if (BSwapOp.getValueType() == MVT::i16)
14193         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14194 
14195       // If the type of BSWAP operand is wider than stored memory width
14196       // it need to be shifted to the right side before STBRX.
14197       if (Op1VT.bitsGT(mVT)) {
14198         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14199         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14200                               DAG.getConstant(Shift, dl, MVT::i32));
14201         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14202         if (Op1VT == MVT::i64)
14203           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14204       }
14205 
14206       SDValue Ops[] = {
14207         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14208       };
14209       return
14210         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14211                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14212                                 cast<StoreSDNode>(N)->getMemOperand());
14213     }
14214 
14215     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14216     // So it can increase the chance of CSE constant construction.
14217     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14218         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14219       // Need to sign-extended to 64-bits to handle negative values.
14220       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14221       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14222                                     MemVT.getSizeInBits());
14223       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14224 
14225       // DAG.getTruncStore() can't be used here because it doesn't accept
14226       // the general (base + offset) addressing mode.
14227       // So we use UpdateNodeOperands and setTruncatingStore instead.
14228       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14229                              N->getOperand(3));
14230       cast<StoreSDNode>(N)->setTruncatingStore(true);
14231       return SDValue(N, 0);
14232     }
14233 
14234     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14235     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14236     if (Op1VT.isSimple()) {
14237       MVT StoreVT = Op1VT.getSimpleVT();
14238       if (Subtarget.needsSwapsForVSXMemOps() &&
14239           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14240            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14241         return expandVSXStoreForLE(N, DCI);
14242     }
14243     break;
14244   }
14245   case ISD::LOAD: {
14246     LoadSDNode *LD = cast<LoadSDNode>(N);
14247     EVT VT = LD->getValueType(0);
14248 
14249     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14250     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14251     if (VT.isSimple()) {
14252       MVT LoadVT = VT.getSimpleVT();
14253       if (Subtarget.needsSwapsForVSXMemOps() &&
14254           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14255            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14256         return expandVSXLoadForLE(N, DCI);
14257     }
14258 
14259     // We sometimes end up with a 64-bit integer load, from which we extract
14260     // two single-precision floating-point numbers. This happens with
14261     // std::complex<float>, and other similar structures, because of the way we
14262     // canonicalize structure copies. However, if we lack direct moves,
14263     // then the final bitcasts from the extracted integer values to the
14264     // floating-point numbers turn into store/load pairs. Even with direct moves,
14265     // just loading the two floating-point numbers is likely better.
14266     auto ReplaceTwoFloatLoad = [&]() {
14267       if (VT != MVT::i64)
14268         return false;
14269 
14270       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14271           LD->isVolatile())
14272         return false;
14273 
14274       //  We're looking for a sequence like this:
14275       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14276       //      t16: i64 = srl t13, Constant:i32<32>
14277       //    t17: i32 = truncate t16
14278       //  t18: f32 = bitcast t17
14279       //    t19: i32 = truncate t13
14280       //  t20: f32 = bitcast t19
14281 
14282       if (!LD->hasNUsesOfValue(2, 0))
14283         return false;
14284 
14285       auto UI = LD->use_begin();
14286       while (UI.getUse().getResNo() != 0) ++UI;
14287       SDNode *Trunc = *UI++;
14288       while (UI.getUse().getResNo() != 0) ++UI;
14289       SDNode *RightShift = *UI;
14290       if (Trunc->getOpcode() != ISD::TRUNCATE)
14291         std::swap(Trunc, RightShift);
14292 
14293       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14294           Trunc->getValueType(0) != MVT::i32 ||
14295           !Trunc->hasOneUse())
14296         return false;
14297       if (RightShift->getOpcode() != ISD::SRL ||
14298           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14299           RightShift->getConstantOperandVal(1) != 32 ||
14300           !RightShift->hasOneUse())
14301         return false;
14302 
14303       SDNode *Trunc2 = *RightShift->use_begin();
14304       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14305           Trunc2->getValueType(0) != MVT::i32 ||
14306           !Trunc2->hasOneUse())
14307         return false;
14308 
14309       SDNode *Bitcast = *Trunc->use_begin();
14310       SDNode *Bitcast2 = *Trunc2->use_begin();
14311 
14312       if (Bitcast->getOpcode() != ISD::BITCAST ||
14313           Bitcast->getValueType(0) != MVT::f32)
14314         return false;
14315       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14316           Bitcast2->getValueType(0) != MVT::f32)
14317         return false;
14318 
14319       if (Subtarget.isLittleEndian())
14320         std::swap(Bitcast, Bitcast2);
14321 
14322       // Bitcast has the second float (in memory-layout order) and Bitcast2
14323       // has the first one.
14324 
14325       SDValue BasePtr = LD->getBasePtr();
14326       if (LD->isIndexed()) {
14327         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14328                "Non-pre-inc AM on PPC?");
14329         BasePtr =
14330           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14331                       LD->getOffset());
14332       }
14333 
14334       auto MMOFlags =
14335           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14336       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14337                                       LD->getPointerInfo(), LD->getAlignment(),
14338                                       MMOFlags, LD->getAAInfo());
14339       SDValue AddPtr =
14340         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14341                     BasePtr, DAG.getIntPtrConstant(4, dl));
14342       SDValue FloatLoad2 = DAG.getLoad(
14343           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14344           LD->getPointerInfo().getWithOffset(4),
14345           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14346 
14347       if (LD->isIndexed()) {
14348         // Note that DAGCombine should re-form any pre-increment load(s) from
14349         // what is produced here if that makes sense.
14350         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14351       }
14352 
14353       DCI.CombineTo(Bitcast2, FloatLoad);
14354       DCI.CombineTo(Bitcast, FloatLoad2);
14355 
14356       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14357                                     SDValue(FloatLoad2.getNode(), 1));
14358       return true;
14359     };
14360 
14361     if (ReplaceTwoFloatLoad())
14362       return SDValue(N, 0);
14363 
14364     EVT MemVT = LD->getMemoryVT();
14365     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14366     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14367     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14368     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14369     if (LD->isUnindexed() && VT.isVector() &&
14370         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14371           // P8 and later hardware should just use LOAD.
14372           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14373                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14374          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14375           LD->getAlignment() >= ScalarABIAlignment)) &&
14376         LD->getAlignment() < ABIAlignment) {
14377       // This is a type-legal unaligned Altivec or QPX load.
14378       SDValue Chain = LD->getChain();
14379       SDValue Ptr = LD->getBasePtr();
14380       bool isLittleEndian = Subtarget.isLittleEndian();
14381 
14382       // This implements the loading of unaligned vectors as described in
14383       // the venerable Apple Velocity Engine overview. Specifically:
14384       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14385       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14386       //
14387       // The general idea is to expand a sequence of one or more unaligned
14388       // loads into an alignment-based permutation-control instruction (lvsl
14389       // or lvsr), a series of regular vector loads (which always truncate
14390       // their input address to an aligned address), and a series of
14391       // permutations.  The results of these permutations are the requested
14392       // loaded values.  The trick is that the last "extra" load is not taken
14393       // from the address you might suspect (sizeof(vector) bytes after the
14394       // last requested load), but rather sizeof(vector) - 1 bytes after the
14395       // last requested vector. The point of this is to avoid a page fault if
14396       // the base address happened to be aligned. This works because if the
14397       // base address is aligned, then adding less than a full vector length
14398       // will cause the last vector in the sequence to be (re)loaded.
14399       // Otherwise, the next vector will be fetched as you might suspect was
14400       // necessary.
14401 
14402       // We might be able to reuse the permutation generation from
14403       // a different base address offset from this one by an aligned amount.
14404       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14405       // optimization later.
14406       Intrinsic::ID Intr, IntrLD, IntrPerm;
14407       MVT PermCntlTy, PermTy, LDTy;
14408       if (Subtarget.hasAltivec()) {
14409         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14410                                  Intrinsic::ppc_altivec_lvsl;
14411         IntrLD = Intrinsic::ppc_altivec_lvx;
14412         IntrPerm = Intrinsic::ppc_altivec_vperm;
14413         PermCntlTy = MVT::v16i8;
14414         PermTy = MVT::v4i32;
14415         LDTy = MVT::v4i32;
14416       } else {
14417         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14418                                        Intrinsic::ppc_qpx_qvlpcls;
14419         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14420                                        Intrinsic::ppc_qpx_qvlfs;
14421         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14422         PermCntlTy = MVT::v4f64;
14423         PermTy = MVT::v4f64;
14424         LDTy = MemVT.getSimpleVT();
14425       }
14426 
14427       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14428 
14429       // Create the new MMO for the new base load. It is like the original MMO,
14430       // but represents an area in memory almost twice the vector size centered
14431       // on the original address. If the address is unaligned, we might start
14432       // reading up to (sizeof(vector)-1) bytes below the address of the
14433       // original unaligned load.
14434       MachineFunction &MF = DAG.getMachineFunction();
14435       MachineMemOperand *BaseMMO =
14436         MF.getMachineMemOperand(LD->getMemOperand(),
14437                                 -(long)MemVT.getStoreSize()+1,
14438                                 2*MemVT.getStoreSize()-1);
14439 
14440       // Create the new base load.
14441       SDValue LDXIntID =
14442           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14443       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14444       SDValue BaseLoad =
14445         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14446                                 DAG.getVTList(PermTy, MVT::Other),
14447                                 BaseLoadOps, LDTy, BaseMMO);
14448 
14449       // Note that the value of IncOffset (which is provided to the next
14450       // load's pointer info offset value, and thus used to calculate the
14451       // alignment), and the value of IncValue (which is actually used to
14452       // increment the pointer value) are different! This is because we
14453       // require the next load to appear to be aligned, even though it
14454       // is actually offset from the base pointer by a lesser amount.
14455       int IncOffset = VT.getSizeInBits() / 8;
14456       int IncValue = IncOffset;
14457 
14458       // Walk (both up and down) the chain looking for another load at the real
14459       // (aligned) offset (the alignment of the other load does not matter in
14460       // this case). If found, then do not use the offset reduction trick, as
14461       // that will prevent the loads from being later combined (as they would
14462       // otherwise be duplicates).
14463       if (!findConsecutiveLoad(LD, DAG))
14464         --IncValue;
14465 
14466       SDValue Increment =
14467           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14468       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14469 
14470       MachineMemOperand *ExtraMMO =
14471         MF.getMachineMemOperand(LD->getMemOperand(),
14472                                 1, 2*MemVT.getStoreSize()-1);
14473       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14474       SDValue ExtraLoad =
14475         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14476                                 DAG.getVTList(PermTy, MVT::Other),
14477                                 ExtraLoadOps, LDTy, ExtraMMO);
14478 
14479       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14480         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14481 
14482       // Because vperm has a big-endian bias, we must reverse the order
14483       // of the input vectors and complement the permute control vector
14484       // when generating little endian code.  We have already handled the
14485       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14486       // and ExtraLoad here.
14487       SDValue Perm;
14488       if (isLittleEndian)
14489         Perm = BuildIntrinsicOp(IntrPerm,
14490                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14491       else
14492         Perm = BuildIntrinsicOp(IntrPerm,
14493                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14494 
14495       if (VT != PermTy)
14496         Perm = Subtarget.hasAltivec() ?
14497                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14498                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14499                                DAG.getTargetConstant(1, dl, MVT::i64));
14500                                // second argument is 1 because this rounding
14501                                // is always exact.
14502 
14503       // The output of the permutation is our loaded result, the TokenFactor is
14504       // our new chain.
14505       DCI.CombineTo(N, Perm, TF);
14506       return SDValue(N, 0);
14507     }
14508     }
14509     break;
14510     case ISD::INTRINSIC_WO_CHAIN: {
14511       bool isLittleEndian = Subtarget.isLittleEndian();
14512       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14513       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14514                                            : Intrinsic::ppc_altivec_lvsl);
14515       if ((IID == Intr ||
14516            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14517            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14518         N->getOperand(1)->getOpcode() == ISD::ADD) {
14519         SDValue Add = N->getOperand(1);
14520 
14521         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14522                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14523 
14524         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14525                                   APInt::getAllOnesValue(Bits /* alignment */)
14526                                       .zext(Add.getScalarValueSizeInBits()))) {
14527           SDNode *BasePtr = Add->getOperand(0).getNode();
14528           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14529                                     UE = BasePtr->use_end();
14530                UI != UE; ++UI) {
14531             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14532                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14533               // We've found another LVSL/LVSR, and this address is an aligned
14534               // multiple of that one. The results will be the same, so use the
14535               // one we've just found instead.
14536 
14537               return SDValue(*UI, 0);
14538             }
14539           }
14540         }
14541 
14542         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14543           SDNode *BasePtr = Add->getOperand(0).getNode();
14544           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14545                UE = BasePtr->use_end(); UI != UE; ++UI) {
14546             if (UI->getOpcode() == ISD::ADD &&
14547                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14548                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14549                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14550                 (1ULL << Bits) == 0) {
14551               SDNode *OtherAdd = *UI;
14552               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14553                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14554                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14555                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14556                   return SDValue(*VI, 0);
14557                 }
14558               }
14559             }
14560           }
14561         }
14562       }
14563 
14564       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14565       // Expose the vabsduw/h/b opportunity for down stream
14566       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14567           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14568            IID == Intrinsic::ppc_altivec_vmaxsh ||
14569            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14570         SDValue V1 = N->getOperand(1);
14571         SDValue V2 = N->getOperand(2);
14572         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14573              V1.getSimpleValueType() == MVT::v8i16 ||
14574              V1.getSimpleValueType() == MVT::v16i8) &&
14575             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14576           // (0-a, a)
14577           if (V1.getOpcode() == ISD::SUB &&
14578               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14579               V1.getOperand(1) == V2) {
14580             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14581           }
14582           // (a, 0-a)
14583           if (V2.getOpcode() == ISD::SUB &&
14584               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14585               V2.getOperand(1) == V1) {
14586             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14587           }
14588           // (x-y, y-x)
14589           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14590               V1.getOperand(0) == V2.getOperand(1) &&
14591               V1.getOperand(1) == V2.getOperand(0)) {
14592             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14593           }
14594         }
14595       }
14596     }
14597 
14598     break;
14599   case ISD::INTRINSIC_W_CHAIN:
14600     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14601     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14602     if (Subtarget.needsSwapsForVSXMemOps()) {
14603       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14604       default:
14605         break;
14606       case Intrinsic::ppc_vsx_lxvw4x:
14607       case Intrinsic::ppc_vsx_lxvd2x:
14608         return expandVSXLoadForLE(N, DCI);
14609       }
14610     }
14611     break;
14612   case ISD::INTRINSIC_VOID:
14613     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14614     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14615     if (Subtarget.needsSwapsForVSXMemOps()) {
14616       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14617       default:
14618         break;
14619       case Intrinsic::ppc_vsx_stxvw4x:
14620       case Intrinsic::ppc_vsx_stxvd2x:
14621         return expandVSXStoreForLE(N, DCI);
14622       }
14623     }
14624     break;
14625   case ISD::BSWAP:
14626     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14627     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14628         N->getOperand(0).hasOneUse() &&
14629         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14630          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14631           N->getValueType(0) == MVT::i64))) {
14632       SDValue Load = N->getOperand(0);
14633       LoadSDNode *LD = cast<LoadSDNode>(Load);
14634       // Create the byte-swapping load.
14635       SDValue Ops[] = {
14636         LD->getChain(),    // Chain
14637         LD->getBasePtr(),  // Ptr
14638         DAG.getValueType(N->getValueType(0)) // VT
14639       };
14640       SDValue BSLoad =
14641         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14642                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14643                                               MVT::i64 : MVT::i32, MVT::Other),
14644                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14645 
14646       // If this is an i16 load, insert the truncate.
14647       SDValue ResVal = BSLoad;
14648       if (N->getValueType(0) == MVT::i16)
14649         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14650 
14651       // First, combine the bswap away.  This makes the value produced by the
14652       // load dead.
14653       DCI.CombineTo(N, ResVal);
14654 
14655       // Next, combine the load away, we give it a bogus result value but a real
14656       // chain result.  The result value is dead because the bswap is dead.
14657       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14658 
14659       // Return N so it doesn't get rechecked!
14660       return SDValue(N, 0);
14661     }
14662     break;
14663   case PPCISD::VCMP:
14664     // If a VCMPo node already exists with exactly the same operands as this
14665     // node, use its result instead of this node (VCMPo computes both a CR6 and
14666     // a normal output).
14667     //
14668     if (!N->getOperand(0).hasOneUse() &&
14669         !N->getOperand(1).hasOneUse() &&
14670         !N->getOperand(2).hasOneUse()) {
14671 
14672       // Scan all of the users of the LHS, looking for VCMPo's that match.
14673       SDNode *VCMPoNode = nullptr;
14674 
14675       SDNode *LHSN = N->getOperand(0).getNode();
14676       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14677            UI != E; ++UI)
14678         if (UI->getOpcode() == PPCISD::VCMPo &&
14679             UI->getOperand(1) == N->getOperand(1) &&
14680             UI->getOperand(2) == N->getOperand(2) &&
14681             UI->getOperand(0) == N->getOperand(0)) {
14682           VCMPoNode = *UI;
14683           break;
14684         }
14685 
14686       // If there is no VCMPo node, or if the flag value has a single use, don't
14687       // transform this.
14688       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14689         break;
14690 
14691       // Look at the (necessarily single) use of the flag value.  If it has a
14692       // chain, this transformation is more complex.  Note that multiple things
14693       // could use the value result, which we should ignore.
14694       SDNode *FlagUser = nullptr;
14695       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14696            FlagUser == nullptr; ++UI) {
14697         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14698         SDNode *User = *UI;
14699         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14700           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14701             FlagUser = User;
14702             break;
14703           }
14704         }
14705       }
14706 
14707       // If the user is a MFOCRF instruction, we know this is safe.
14708       // Otherwise we give up for right now.
14709       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14710         return SDValue(VCMPoNode, 0);
14711     }
14712     break;
14713   case ISD::BRCOND: {
14714     SDValue Cond = N->getOperand(1);
14715     SDValue Target = N->getOperand(2);
14716 
14717     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14718         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14719           Intrinsic::loop_decrement) {
14720 
14721       // We now need to make the intrinsic dead (it cannot be instruction
14722       // selected).
14723       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14724       assert(Cond.getNode()->hasOneUse() &&
14725              "Counter decrement has more than one use");
14726 
14727       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14728                          N->getOperand(0), Target);
14729     }
14730   }
14731   break;
14732   case ISD::BR_CC: {
14733     // If this is a branch on an altivec predicate comparison, lower this so
14734     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14735     // lowering is done pre-legalize, because the legalizer lowers the predicate
14736     // compare down to code that is difficult to reassemble.
14737     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14738     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14739 
14740     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14741     // value. If so, pass-through the AND to get to the intrinsic.
14742     if (LHS.getOpcode() == ISD::AND &&
14743         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14744         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14745           Intrinsic::loop_decrement &&
14746         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14747         !isNullConstant(LHS.getOperand(1)))
14748       LHS = LHS.getOperand(0);
14749 
14750     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14751         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14752           Intrinsic::loop_decrement &&
14753         isa<ConstantSDNode>(RHS)) {
14754       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14755              "Counter decrement comparison is not EQ or NE");
14756 
14757       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14758       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14759                     (CC == ISD::SETNE && !Val);
14760 
14761       // We now need to make the intrinsic dead (it cannot be instruction
14762       // selected).
14763       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14764       assert(LHS.getNode()->hasOneUse() &&
14765              "Counter decrement has more than one use");
14766 
14767       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14768                          N->getOperand(0), N->getOperand(4));
14769     }
14770 
14771     int CompareOpc;
14772     bool isDot;
14773 
14774     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14775         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14776         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14777       assert(isDot && "Can't compare against a vector result!");
14778 
14779       // If this is a comparison against something other than 0/1, then we know
14780       // that the condition is never/always true.
14781       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14782       if (Val != 0 && Val != 1) {
14783         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14784           return N->getOperand(0);
14785         // Always !=, turn it into an unconditional branch.
14786         return DAG.getNode(ISD::BR, dl, MVT::Other,
14787                            N->getOperand(0), N->getOperand(4));
14788       }
14789 
14790       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14791 
14792       // Create the PPCISD altivec 'dot' comparison node.
14793       SDValue Ops[] = {
14794         LHS.getOperand(2),  // LHS of compare
14795         LHS.getOperand(3),  // RHS of compare
14796         DAG.getConstant(CompareOpc, dl, MVT::i32)
14797       };
14798       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14799       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14800 
14801       // Unpack the result based on how the target uses it.
14802       PPC::Predicate CompOpc;
14803       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14804       default:  // Can't happen, don't crash on invalid number though.
14805       case 0:   // Branch on the value of the EQ bit of CR6.
14806         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14807         break;
14808       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14809         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14810         break;
14811       case 2:   // Branch on the value of the LT bit of CR6.
14812         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14813         break;
14814       case 3:   // Branch on the inverted value of the LT bit of CR6.
14815         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14816         break;
14817       }
14818 
14819       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14820                          DAG.getConstant(CompOpc, dl, MVT::i32),
14821                          DAG.getRegister(PPC::CR6, MVT::i32),
14822                          N->getOperand(4), CompNode.getValue(1));
14823     }
14824     break;
14825   }
14826   case ISD::BUILD_VECTOR:
14827     return DAGCombineBuildVector(N, DCI);
14828   case ISD::ABS:
14829     return combineABS(N, DCI);
14830   case ISD::VSELECT:
14831     return combineVSelect(N, DCI);
14832   }
14833 
14834   return SDValue();
14835 }
14836 
14837 SDValue
14838 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14839                                  SelectionDAG &DAG,
14840                                  SmallVectorImpl<SDNode *> &Created) const {
14841   // fold (sdiv X, pow2)
14842   EVT VT = N->getValueType(0);
14843   if (VT == MVT::i64 && !Subtarget.isPPC64())
14844     return SDValue();
14845   if ((VT != MVT::i32 && VT != MVT::i64) ||
14846       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14847     return SDValue();
14848 
14849   SDLoc DL(N);
14850   SDValue N0 = N->getOperand(0);
14851 
14852   bool IsNegPow2 = (-Divisor).isPowerOf2();
14853   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14854   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14855 
14856   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14857   Created.push_back(Op.getNode());
14858 
14859   if (IsNegPow2) {
14860     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14861     Created.push_back(Op.getNode());
14862   }
14863 
14864   return Op;
14865 }
14866 
14867 //===----------------------------------------------------------------------===//
14868 // Inline Assembly Support
14869 //===----------------------------------------------------------------------===//
14870 
14871 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14872                                                       KnownBits &Known,
14873                                                       const APInt &DemandedElts,
14874                                                       const SelectionDAG &DAG,
14875                                                       unsigned Depth) const {
14876   Known.resetAll();
14877   switch (Op.getOpcode()) {
14878   default: break;
14879   case PPCISD::LBRX: {
14880     // lhbrx is known to have the top bits cleared out.
14881     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14882       Known.Zero = 0xFFFF0000;
14883     break;
14884   }
14885   case ISD::INTRINSIC_WO_CHAIN: {
14886     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14887     default: break;
14888     case Intrinsic::ppc_altivec_vcmpbfp_p:
14889     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14890     case Intrinsic::ppc_altivec_vcmpequb_p:
14891     case Intrinsic::ppc_altivec_vcmpequh_p:
14892     case Intrinsic::ppc_altivec_vcmpequw_p:
14893     case Intrinsic::ppc_altivec_vcmpequd_p:
14894     case Intrinsic::ppc_altivec_vcmpgefp_p:
14895     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14896     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14897     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14898     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14899     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14900     case Intrinsic::ppc_altivec_vcmpgtub_p:
14901     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14902     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14903     case Intrinsic::ppc_altivec_vcmpgtud_p:
14904       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14905       break;
14906     }
14907   }
14908   }
14909 }
14910 
14911 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14912   switch (Subtarget.getCPUDirective()) {
14913   default: break;
14914   case PPC::DIR_970:
14915   case PPC::DIR_PWR4:
14916   case PPC::DIR_PWR5:
14917   case PPC::DIR_PWR5X:
14918   case PPC::DIR_PWR6:
14919   case PPC::DIR_PWR6X:
14920   case PPC::DIR_PWR7:
14921   case PPC::DIR_PWR8:
14922   case PPC::DIR_PWR9:
14923   case PPC::DIR_PWR10:
14924   case PPC::DIR_PWR_FUTURE: {
14925     if (!ML)
14926       break;
14927 
14928     if (!DisableInnermostLoopAlign32) {
14929       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14930       // so that we can decrease cache misses and branch-prediction misses.
14931       // Actual alignment of the loop will depend on the hotness check and other
14932       // logic in alignBlocks.
14933       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14934         return Align(32);
14935     }
14936 
14937     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14938 
14939     // For small loops (between 5 and 8 instructions), align to a 32-byte
14940     // boundary so that the entire loop fits in one instruction-cache line.
14941     uint64_t LoopSize = 0;
14942     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14943       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14944         LoopSize += TII->getInstSizeInBytes(*J);
14945         if (LoopSize > 32)
14946           break;
14947       }
14948 
14949     if (LoopSize > 16 && LoopSize <= 32)
14950       return Align(32);
14951 
14952     break;
14953   }
14954   }
14955 
14956   return TargetLowering::getPrefLoopAlignment(ML);
14957 }
14958 
14959 /// getConstraintType - Given a constraint, return the type of
14960 /// constraint it is for this target.
14961 PPCTargetLowering::ConstraintType
14962 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14963   if (Constraint.size() == 1) {
14964     switch (Constraint[0]) {
14965     default: break;
14966     case 'b':
14967     case 'r':
14968     case 'f':
14969     case 'd':
14970     case 'v':
14971     case 'y':
14972       return C_RegisterClass;
14973     case 'Z':
14974       // FIXME: While Z does indicate a memory constraint, it specifically
14975       // indicates an r+r address (used in conjunction with the 'y' modifier
14976       // in the replacement string). Currently, we're forcing the base
14977       // register to be r0 in the asm printer (which is interpreted as zero)
14978       // and forming the complete address in the second register. This is
14979       // suboptimal.
14980       return C_Memory;
14981     }
14982   } else if (Constraint == "wc") { // individual CR bits.
14983     return C_RegisterClass;
14984   } else if (Constraint == "wa" || Constraint == "wd" ||
14985              Constraint == "wf" || Constraint == "ws" ||
14986              Constraint == "wi" || Constraint == "ww") {
14987     return C_RegisterClass; // VSX registers.
14988   }
14989   return TargetLowering::getConstraintType(Constraint);
14990 }
14991 
14992 /// Examine constraint type and operand type and determine a weight value.
14993 /// This object must already have been set up with the operand type
14994 /// and the current alternative constraint selected.
14995 TargetLowering::ConstraintWeight
14996 PPCTargetLowering::getSingleConstraintMatchWeight(
14997     AsmOperandInfo &info, const char *constraint) const {
14998   ConstraintWeight weight = CW_Invalid;
14999   Value *CallOperandVal = info.CallOperandVal;
15000     // If we don't have a value, we can't do a match,
15001     // but allow it at the lowest weight.
15002   if (!CallOperandVal)
15003     return CW_Default;
15004   Type *type = CallOperandVal->getType();
15005 
15006   // Look at the constraint type.
15007   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15008     return CW_Register; // an individual CR bit.
15009   else if ((StringRef(constraint) == "wa" ||
15010             StringRef(constraint) == "wd" ||
15011             StringRef(constraint) == "wf") &&
15012            type->isVectorTy())
15013     return CW_Register;
15014   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15015     return CW_Register; // just hold 64-bit integers data.
15016   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15017     return CW_Register;
15018   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15019     return CW_Register;
15020 
15021   switch (*constraint) {
15022   default:
15023     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15024     break;
15025   case 'b':
15026     if (type->isIntegerTy())
15027       weight = CW_Register;
15028     break;
15029   case 'f':
15030     if (type->isFloatTy())
15031       weight = CW_Register;
15032     break;
15033   case 'd':
15034     if (type->isDoubleTy())
15035       weight = CW_Register;
15036     break;
15037   case 'v':
15038     if (type->isVectorTy())
15039       weight = CW_Register;
15040     break;
15041   case 'y':
15042     weight = CW_Register;
15043     break;
15044   case 'Z':
15045     weight = CW_Memory;
15046     break;
15047   }
15048   return weight;
15049 }
15050 
15051 std::pair<unsigned, const TargetRegisterClass *>
15052 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15053                                                 StringRef Constraint,
15054                                                 MVT VT) const {
15055   if (Constraint.size() == 1) {
15056     // GCC RS6000 Constraint Letters
15057     switch (Constraint[0]) {
15058     case 'b':   // R1-R31
15059       if (VT == MVT::i64 && Subtarget.isPPC64())
15060         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15061       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15062     case 'r':   // R0-R31
15063       if (VT == MVT::i64 && Subtarget.isPPC64())
15064         return std::make_pair(0U, &PPC::G8RCRegClass);
15065       return std::make_pair(0U, &PPC::GPRCRegClass);
15066     // 'd' and 'f' constraints are both defined to be "the floating point
15067     // registers", where one is for 32-bit and the other for 64-bit. We don't
15068     // really care overly much here so just give them all the same reg classes.
15069     case 'd':
15070     case 'f':
15071       if (Subtarget.hasSPE()) {
15072         if (VT == MVT::f32 || VT == MVT::i32)
15073           return std::make_pair(0U, &PPC::GPRCRegClass);
15074         if (VT == MVT::f64 || VT == MVT::i64)
15075           return std::make_pair(0U, &PPC::SPERCRegClass);
15076       } else {
15077         if (VT == MVT::f32 || VT == MVT::i32)
15078           return std::make_pair(0U, &PPC::F4RCRegClass);
15079         if (VT == MVT::f64 || VT == MVT::i64)
15080           return std::make_pair(0U, &PPC::F8RCRegClass);
15081         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15082           return std::make_pair(0U, &PPC::QFRCRegClass);
15083         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15084           return std::make_pair(0U, &PPC::QSRCRegClass);
15085       }
15086       break;
15087     case 'v':
15088       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15089         return std::make_pair(0U, &PPC::QFRCRegClass);
15090       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15091         return std::make_pair(0U, &PPC::QSRCRegClass);
15092       if (Subtarget.hasAltivec())
15093         return std::make_pair(0U, &PPC::VRRCRegClass);
15094       break;
15095     case 'y':   // crrc
15096       return std::make_pair(0U, &PPC::CRRCRegClass);
15097     }
15098   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15099     // An individual CR bit.
15100     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15101   } else if ((Constraint == "wa" || Constraint == "wd" ||
15102              Constraint == "wf" || Constraint == "wi") &&
15103              Subtarget.hasVSX()) {
15104     return std::make_pair(0U, &PPC::VSRCRegClass);
15105   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15106     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15107       return std::make_pair(0U, &PPC::VSSRCRegClass);
15108     else
15109       return std::make_pair(0U, &PPC::VSFRCRegClass);
15110   }
15111 
15112   // If we name a VSX register, we can't defer to the base class because it
15113   // will not recognize the correct register (their names will be VSL{0-31}
15114   // and V{0-31} so they won't match). So we match them here.
15115   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15116     int VSNum = atoi(Constraint.data() + 3);
15117     assert(VSNum >= 0 && VSNum <= 63 &&
15118            "Attempted to access a vsr out of range");
15119     if (VSNum < 32)
15120       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15121     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15122   }
15123   std::pair<unsigned, const TargetRegisterClass *> R =
15124       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15125 
15126   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15127   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15128   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15129   // register.
15130   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15131   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15132   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15133       PPC::GPRCRegClass.contains(R.first))
15134     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15135                             PPC::sub_32, &PPC::G8RCRegClass),
15136                           &PPC::G8RCRegClass);
15137 
15138   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15139   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15140     R.first = PPC::CR0;
15141     R.second = &PPC::CRRCRegClass;
15142   }
15143 
15144   return R;
15145 }
15146 
15147 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15148 /// vector.  If it is invalid, don't add anything to Ops.
15149 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15150                                                      std::string &Constraint,
15151                                                      std::vector<SDValue>&Ops,
15152                                                      SelectionDAG &DAG) const {
15153   SDValue Result;
15154 
15155   // Only support length 1 constraints.
15156   if (Constraint.length() > 1) return;
15157 
15158   char Letter = Constraint[0];
15159   switch (Letter) {
15160   default: break;
15161   case 'I':
15162   case 'J':
15163   case 'K':
15164   case 'L':
15165   case 'M':
15166   case 'N':
15167   case 'O':
15168   case 'P': {
15169     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15170     if (!CST) return; // Must be an immediate to match.
15171     SDLoc dl(Op);
15172     int64_t Value = CST->getSExtValue();
15173     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15174                          // numbers are printed as such.
15175     switch (Letter) {
15176     default: llvm_unreachable("Unknown constraint letter!");
15177     case 'I':  // "I" is a signed 16-bit constant.
15178       if (isInt<16>(Value))
15179         Result = DAG.getTargetConstant(Value, dl, TCVT);
15180       break;
15181     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15182       if (isShiftedUInt<16, 16>(Value))
15183         Result = DAG.getTargetConstant(Value, dl, TCVT);
15184       break;
15185     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15186       if (isShiftedInt<16, 16>(Value))
15187         Result = DAG.getTargetConstant(Value, dl, TCVT);
15188       break;
15189     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15190       if (isUInt<16>(Value))
15191         Result = DAG.getTargetConstant(Value, dl, TCVT);
15192       break;
15193     case 'M':  // "M" is a constant that is greater than 31.
15194       if (Value > 31)
15195         Result = DAG.getTargetConstant(Value, dl, TCVT);
15196       break;
15197     case 'N':  // "N" is a positive constant that is an exact power of two.
15198       if (Value > 0 && isPowerOf2_64(Value))
15199         Result = DAG.getTargetConstant(Value, dl, TCVT);
15200       break;
15201     case 'O':  // "O" is the constant zero.
15202       if (Value == 0)
15203         Result = DAG.getTargetConstant(Value, dl, TCVT);
15204       break;
15205     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15206       if (isInt<16>(-Value))
15207         Result = DAG.getTargetConstant(Value, dl, TCVT);
15208       break;
15209     }
15210     break;
15211   }
15212   }
15213 
15214   if (Result.getNode()) {
15215     Ops.push_back(Result);
15216     return;
15217   }
15218 
15219   // Handle standard constraint letters.
15220   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15221 }
15222 
15223 // isLegalAddressingMode - Return true if the addressing mode represented
15224 // by AM is legal for this target, for a load/store of the specified type.
15225 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15226                                               const AddrMode &AM, Type *Ty,
15227                                               unsigned AS, Instruction *I) const {
15228   // PPC does not allow r+i addressing modes for vectors!
15229   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15230     return false;
15231 
15232   // PPC allows a sign-extended 16-bit immediate field.
15233   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15234     return false;
15235 
15236   // No global is ever allowed as a base.
15237   if (AM.BaseGV)
15238     return false;
15239 
15240   // PPC only support r+r,
15241   switch (AM.Scale) {
15242   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15243     break;
15244   case 1:
15245     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15246       return false;
15247     // Otherwise we have r+r or r+i.
15248     break;
15249   case 2:
15250     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15251       return false;
15252     // Allow 2*r as r+r.
15253     break;
15254   default:
15255     // No other scales are supported.
15256     return false;
15257   }
15258 
15259   return true;
15260 }
15261 
15262 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15263                                            SelectionDAG &DAG) const {
15264   MachineFunction &MF = DAG.getMachineFunction();
15265   MachineFrameInfo &MFI = MF.getFrameInfo();
15266   MFI.setReturnAddressIsTaken(true);
15267 
15268   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15269     return SDValue();
15270 
15271   SDLoc dl(Op);
15272   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15273 
15274   // Make sure the function does not optimize away the store of the RA to
15275   // the stack.
15276   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15277   FuncInfo->setLRStoreRequired();
15278   bool isPPC64 = Subtarget.isPPC64();
15279   auto PtrVT = getPointerTy(MF.getDataLayout());
15280 
15281   if (Depth > 0) {
15282     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15283     SDValue Offset =
15284         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15285                         isPPC64 ? MVT::i64 : MVT::i32);
15286     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15287                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15288                        MachinePointerInfo());
15289   }
15290 
15291   // Just load the return address off the stack.
15292   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15293   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15294                      MachinePointerInfo());
15295 }
15296 
15297 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15298                                           SelectionDAG &DAG) const {
15299   SDLoc dl(Op);
15300   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15301 
15302   MachineFunction &MF = DAG.getMachineFunction();
15303   MachineFrameInfo &MFI = MF.getFrameInfo();
15304   MFI.setFrameAddressIsTaken(true);
15305 
15306   EVT PtrVT = getPointerTy(MF.getDataLayout());
15307   bool isPPC64 = PtrVT == MVT::i64;
15308 
15309   // Naked functions never have a frame pointer, and so we use r1. For all
15310   // other functions, this decision must be delayed until during PEI.
15311   unsigned FrameReg;
15312   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15313     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15314   else
15315     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15316 
15317   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15318                                          PtrVT);
15319   while (Depth--)
15320     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15321                             FrameAddr, MachinePointerInfo());
15322   return FrameAddr;
15323 }
15324 
15325 // FIXME? Maybe this could be a TableGen attribute on some registers and
15326 // this table could be generated automatically from RegInfo.
15327 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15328                                               const MachineFunction &MF) const {
15329   bool isPPC64 = Subtarget.isPPC64();
15330 
15331   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15332   if (!is64Bit && VT != LLT::scalar(32))
15333     report_fatal_error("Invalid register global variable type");
15334 
15335   Register Reg = StringSwitch<Register>(RegName)
15336                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15337                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15338                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15339                      .Default(Register());
15340 
15341   if (Reg)
15342     return Reg;
15343   report_fatal_error("Invalid register name global variable");
15344 }
15345 
15346 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15347   // 32-bit SVR4 ABI access everything as got-indirect.
15348   if (Subtarget.is32BitELFABI())
15349     return true;
15350 
15351   // AIX accesses everything indirectly through the TOC, which is similar to
15352   // the GOT.
15353   if (Subtarget.isAIXABI())
15354     return true;
15355 
15356   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15357   // If it is small or large code model, module locals are accessed
15358   // indirectly by loading their address from .toc/.got.
15359   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15360     return true;
15361 
15362   // JumpTable and BlockAddress are accessed as got-indirect.
15363   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15364     return true;
15365 
15366   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15367     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15368 
15369   return false;
15370 }
15371 
15372 bool
15373 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15374   // The PowerPC target isn't yet aware of offsets.
15375   return false;
15376 }
15377 
15378 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15379                                            const CallInst &I,
15380                                            MachineFunction &MF,
15381                                            unsigned Intrinsic) const {
15382   switch (Intrinsic) {
15383   case Intrinsic::ppc_qpx_qvlfd:
15384   case Intrinsic::ppc_qpx_qvlfs:
15385   case Intrinsic::ppc_qpx_qvlfcd:
15386   case Intrinsic::ppc_qpx_qvlfcs:
15387   case Intrinsic::ppc_qpx_qvlfiwa:
15388   case Intrinsic::ppc_qpx_qvlfiwz:
15389   case Intrinsic::ppc_altivec_lvx:
15390   case Intrinsic::ppc_altivec_lvxl:
15391   case Intrinsic::ppc_altivec_lvebx:
15392   case Intrinsic::ppc_altivec_lvehx:
15393   case Intrinsic::ppc_altivec_lvewx:
15394   case Intrinsic::ppc_vsx_lxvd2x:
15395   case Intrinsic::ppc_vsx_lxvw4x: {
15396     EVT VT;
15397     switch (Intrinsic) {
15398     case Intrinsic::ppc_altivec_lvebx:
15399       VT = MVT::i8;
15400       break;
15401     case Intrinsic::ppc_altivec_lvehx:
15402       VT = MVT::i16;
15403       break;
15404     case Intrinsic::ppc_altivec_lvewx:
15405       VT = MVT::i32;
15406       break;
15407     case Intrinsic::ppc_vsx_lxvd2x:
15408       VT = MVT::v2f64;
15409       break;
15410     case Intrinsic::ppc_qpx_qvlfd:
15411       VT = MVT::v4f64;
15412       break;
15413     case Intrinsic::ppc_qpx_qvlfs:
15414       VT = MVT::v4f32;
15415       break;
15416     case Intrinsic::ppc_qpx_qvlfcd:
15417       VT = MVT::v2f64;
15418       break;
15419     case Intrinsic::ppc_qpx_qvlfcs:
15420       VT = MVT::v2f32;
15421       break;
15422     default:
15423       VT = MVT::v4i32;
15424       break;
15425     }
15426 
15427     Info.opc = ISD::INTRINSIC_W_CHAIN;
15428     Info.memVT = VT;
15429     Info.ptrVal = I.getArgOperand(0);
15430     Info.offset = -VT.getStoreSize()+1;
15431     Info.size = 2*VT.getStoreSize()-1;
15432     Info.align = Align(1);
15433     Info.flags = MachineMemOperand::MOLoad;
15434     return true;
15435   }
15436   case Intrinsic::ppc_qpx_qvlfda:
15437   case Intrinsic::ppc_qpx_qvlfsa:
15438   case Intrinsic::ppc_qpx_qvlfcda:
15439   case Intrinsic::ppc_qpx_qvlfcsa:
15440   case Intrinsic::ppc_qpx_qvlfiwaa:
15441   case Intrinsic::ppc_qpx_qvlfiwza: {
15442     EVT VT;
15443     switch (Intrinsic) {
15444     case Intrinsic::ppc_qpx_qvlfda:
15445       VT = MVT::v4f64;
15446       break;
15447     case Intrinsic::ppc_qpx_qvlfsa:
15448       VT = MVT::v4f32;
15449       break;
15450     case Intrinsic::ppc_qpx_qvlfcda:
15451       VT = MVT::v2f64;
15452       break;
15453     case Intrinsic::ppc_qpx_qvlfcsa:
15454       VT = MVT::v2f32;
15455       break;
15456     default:
15457       VT = MVT::v4i32;
15458       break;
15459     }
15460 
15461     Info.opc = ISD::INTRINSIC_W_CHAIN;
15462     Info.memVT = VT;
15463     Info.ptrVal = I.getArgOperand(0);
15464     Info.offset = 0;
15465     Info.size = VT.getStoreSize();
15466     Info.align = Align(1);
15467     Info.flags = MachineMemOperand::MOLoad;
15468     return true;
15469   }
15470   case Intrinsic::ppc_qpx_qvstfd:
15471   case Intrinsic::ppc_qpx_qvstfs:
15472   case Intrinsic::ppc_qpx_qvstfcd:
15473   case Intrinsic::ppc_qpx_qvstfcs:
15474   case Intrinsic::ppc_qpx_qvstfiw:
15475   case Intrinsic::ppc_altivec_stvx:
15476   case Intrinsic::ppc_altivec_stvxl:
15477   case Intrinsic::ppc_altivec_stvebx:
15478   case Intrinsic::ppc_altivec_stvehx:
15479   case Intrinsic::ppc_altivec_stvewx:
15480   case Intrinsic::ppc_vsx_stxvd2x:
15481   case Intrinsic::ppc_vsx_stxvw4x: {
15482     EVT VT;
15483     switch (Intrinsic) {
15484     case Intrinsic::ppc_altivec_stvebx:
15485       VT = MVT::i8;
15486       break;
15487     case Intrinsic::ppc_altivec_stvehx:
15488       VT = MVT::i16;
15489       break;
15490     case Intrinsic::ppc_altivec_stvewx:
15491       VT = MVT::i32;
15492       break;
15493     case Intrinsic::ppc_vsx_stxvd2x:
15494       VT = MVT::v2f64;
15495       break;
15496     case Intrinsic::ppc_qpx_qvstfd:
15497       VT = MVT::v4f64;
15498       break;
15499     case Intrinsic::ppc_qpx_qvstfs:
15500       VT = MVT::v4f32;
15501       break;
15502     case Intrinsic::ppc_qpx_qvstfcd:
15503       VT = MVT::v2f64;
15504       break;
15505     case Intrinsic::ppc_qpx_qvstfcs:
15506       VT = MVT::v2f32;
15507       break;
15508     default:
15509       VT = MVT::v4i32;
15510       break;
15511     }
15512 
15513     Info.opc = ISD::INTRINSIC_VOID;
15514     Info.memVT = VT;
15515     Info.ptrVal = I.getArgOperand(1);
15516     Info.offset = -VT.getStoreSize()+1;
15517     Info.size = 2*VT.getStoreSize()-1;
15518     Info.align = Align(1);
15519     Info.flags = MachineMemOperand::MOStore;
15520     return true;
15521   }
15522   case Intrinsic::ppc_qpx_qvstfda:
15523   case Intrinsic::ppc_qpx_qvstfsa:
15524   case Intrinsic::ppc_qpx_qvstfcda:
15525   case Intrinsic::ppc_qpx_qvstfcsa:
15526   case Intrinsic::ppc_qpx_qvstfiwa: {
15527     EVT VT;
15528     switch (Intrinsic) {
15529     case Intrinsic::ppc_qpx_qvstfda:
15530       VT = MVT::v4f64;
15531       break;
15532     case Intrinsic::ppc_qpx_qvstfsa:
15533       VT = MVT::v4f32;
15534       break;
15535     case Intrinsic::ppc_qpx_qvstfcda:
15536       VT = MVT::v2f64;
15537       break;
15538     case Intrinsic::ppc_qpx_qvstfcsa:
15539       VT = MVT::v2f32;
15540       break;
15541     default:
15542       VT = MVT::v4i32;
15543       break;
15544     }
15545 
15546     Info.opc = ISD::INTRINSIC_VOID;
15547     Info.memVT = VT;
15548     Info.ptrVal = I.getArgOperand(1);
15549     Info.offset = 0;
15550     Info.size = VT.getStoreSize();
15551     Info.align = Align(1);
15552     Info.flags = MachineMemOperand::MOStore;
15553     return true;
15554   }
15555   default:
15556     break;
15557   }
15558 
15559   return false;
15560 }
15561 
15562 /// It returns EVT::Other if the type should be determined using generic
15563 /// target-independent logic.
15564 EVT PPCTargetLowering::getOptimalMemOpType(
15565     const MemOp &Op, const AttributeList &FuncAttributes) const {
15566   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15567     // When expanding a memset, require at least two QPX instructions to cover
15568     // the cost of loading the value to be stored from the constant pool.
15569     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15570         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15571         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15572       return MVT::v4f64;
15573     }
15574 
15575     // We should use Altivec/VSX loads and stores when available. For unaligned
15576     // addresses, unaligned VSX loads are only fast starting with the P8.
15577     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15578         (Op.isAligned(Align(16)) ||
15579          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15580       return MVT::v4i32;
15581   }
15582 
15583   if (Subtarget.isPPC64()) {
15584     return MVT::i64;
15585   }
15586 
15587   return MVT::i32;
15588 }
15589 
15590 /// Returns true if it is beneficial to convert a load of a constant
15591 /// to just the constant itself.
15592 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15593                                                           Type *Ty) const {
15594   assert(Ty->isIntegerTy());
15595 
15596   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15597   return !(BitSize == 0 || BitSize > 64);
15598 }
15599 
15600 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15601   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15602     return false;
15603   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15604   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15605   return NumBits1 == 64 && NumBits2 == 32;
15606 }
15607 
15608 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15609   if (!VT1.isInteger() || !VT2.isInteger())
15610     return false;
15611   unsigned NumBits1 = VT1.getSizeInBits();
15612   unsigned NumBits2 = VT2.getSizeInBits();
15613   return NumBits1 == 64 && NumBits2 == 32;
15614 }
15615 
15616 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15617   // Generally speaking, zexts are not free, but they are free when they can be
15618   // folded with other operations.
15619   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15620     EVT MemVT = LD->getMemoryVT();
15621     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15622          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15623         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15624          LD->getExtensionType() == ISD::ZEXTLOAD))
15625       return true;
15626   }
15627 
15628   // FIXME: Add other cases...
15629   //  - 32-bit shifts with a zext to i64
15630   //  - zext after ctlz, bswap, etc.
15631   //  - zext after and by a constant mask
15632 
15633   return TargetLowering::isZExtFree(Val, VT2);
15634 }
15635 
15636 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15637   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15638          "invalid fpext types");
15639   // Extending to float128 is not free.
15640   if (DestVT == MVT::f128)
15641     return false;
15642   return true;
15643 }
15644 
15645 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15646   return isInt<16>(Imm) || isUInt<16>(Imm);
15647 }
15648 
15649 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15650   return isInt<16>(Imm) || isUInt<16>(Imm);
15651 }
15652 
15653 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15654                                                        unsigned,
15655                                                        unsigned,
15656                                                        MachineMemOperand::Flags,
15657                                                        bool *Fast) const {
15658   if (DisablePPCUnaligned)
15659     return false;
15660 
15661   // PowerPC supports unaligned memory access for simple non-vector types.
15662   // Although accessing unaligned addresses is not as efficient as accessing
15663   // aligned addresses, it is generally more efficient than manual expansion,
15664   // and generally only traps for software emulation when crossing page
15665   // boundaries.
15666 
15667   if (!VT.isSimple())
15668     return false;
15669 
15670   if (VT.isFloatingPoint() && !VT.isVector() &&
15671       !Subtarget.allowsUnalignedFPAccess())
15672     return false;
15673 
15674   if (VT.getSimpleVT().isVector()) {
15675     if (Subtarget.hasVSX()) {
15676       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15677           VT != MVT::v4f32 && VT != MVT::v4i32)
15678         return false;
15679     } else {
15680       return false;
15681     }
15682   }
15683 
15684   if (VT == MVT::ppcf128)
15685     return false;
15686 
15687   if (Fast)
15688     *Fast = true;
15689 
15690   return true;
15691 }
15692 
15693 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15694                                                    EVT VT) const {
15695   return isFMAFasterThanFMulAndFAdd(
15696       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15697 }
15698 
15699 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15700                                                    Type *Ty) const {
15701   switch (Ty->getScalarType()->getTypeID()) {
15702   case Type::FloatTyID:
15703   case Type::DoubleTyID:
15704     return true;
15705   case Type::FP128TyID:
15706     return EnableQuadPrecision && Subtarget.hasP9Vector();
15707   default:
15708     return false;
15709   }
15710 }
15711 
15712 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15713 // FIXME: add more patterns which are profitable to hoist.
15714 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15715   if (I->getOpcode() != Instruction::FMul)
15716     return true;
15717 
15718   if (!I->hasOneUse())
15719     return true;
15720 
15721   Instruction *User = I->user_back();
15722   assert(User && "A single use instruction with no uses.");
15723 
15724   if (User->getOpcode() != Instruction::FSub &&
15725       User->getOpcode() != Instruction::FAdd)
15726     return true;
15727 
15728   const TargetOptions &Options = getTargetMachine().Options;
15729   const Function *F = I->getFunction();
15730   const DataLayout &DL = F->getParent()->getDataLayout();
15731   Type *Ty = User->getOperand(0)->getType();
15732 
15733   return !(
15734       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15735       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15736       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15737 }
15738 
15739 const MCPhysReg *
15740 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15741   // LR is a callee-save register, but we must treat it as clobbered by any call
15742   // site. Hence we include LR in the scratch registers, which are in turn added
15743   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15744   // to CTR, which is used by any indirect call.
15745   static const MCPhysReg ScratchRegs[] = {
15746     PPC::X12, PPC::LR8, PPC::CTR8, 0
15747   };
15748 
15749   return ScratchRegs;
15750 }
15751 
15752 Register PPCTargetLowering::getExceptionPointerRegister(
15753     const Constant *PersonalityFn) const {
15754   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15755 }
15756 
15757 Register PPCTargetLowering::getExceptionSelectorRegister(
15758     const Constant *PersonalityFn) const {
15759   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15760 }
15761 
15762 bool
15763 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15764                      EVT VT , unsigned DefinedValues) const {
15765   if (VT == MVT::v2i64)
15766     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15767 
15768   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15769     return true;
15770 
15771   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15772 }
15773 
15774 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15775   if (DisableILPPref || Subtarget.enableMachineScheduler())
15776     return TargetLowering::getSchedulingPreference(N);
15777 
15778   return Sched::ILP;
15779 }
15780 
15781 // Create a fast isel object.
15782 FastISel *
15783 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15784                                   const TargetLibraryInfo *LibInfo) const {
15785   return PPC::createFastISel(FuncInfo, LibInfo);
15786 }
15787 
15788 // 'Inverted' means the FMA opcode after negating one multiplicand.
15789 // For example, (fma -a b c) = (fnmsub a b c)
15790 static unsigned invertFMAOpcode(unsigned Opc) {
15791   switch (Opc) {
15792   default:
15793     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15794   case ISD::FMA:
15795     return PPCISD::FNMSUB;
15796   case PPCISD::FNMSUB:
15797     return ISD::FMA;
15798   }
15799 }
15800 
15801 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15802                                                 bool LegalOps, bool OptForSize,
15803                                                 NegatibleCost &Cost,
15804                                                 unsigned Depth) const {
15805   if (Depth > SelectionDAG::MaxRecursionDepth)
15806     return SDValue();
15807 
15808   unsigned Opc = Op.getOpcode();
15809   EVT VT = Op.getValueType();
15810   SDNodeFlags Flags = Op.getNode()->getFlags();
15811 
15812   switch (Opc) {
15813   case PPCISD::FNMSUB:
15814     // TODO: QPX subtarget is deprecated. No transformation here.
15815     if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX())
15816       break;
15817 
15818     const TargetOptions &Options = getTargetMachine().Options;
15819     SDValue N0 = Op.getOperand(0);
15820     SDValue N1 = Op.getOperand(1);
15821     SDValue N2 = Op.getOperand(2);
15822     SDLoc Loc(Op);
15823 
15824     NegatibleCost N2Cost = NegatibleCost::Expensive;
15825     SDValue NegN2 =
15826         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15827 
15828     if (!NegN2)
15829       return SDValue();
15830 
15831     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15832     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15833     // These transformations may change sign of zeroes. For example,
15834     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15835     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15836       // Try and choose the cheaper one to negate.
15837       NegatibleCost N0Cost = NegatibleCost::Expensive;
15838       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15839                                            N0Cost, Depth + 1);
15840 
15841       NegatibleCost N1Cost = NegatibleCost::Expensive;
15842       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15843                                            N1Cost, Depth + 1);
15844 
15845       if (NegN0 && N0Cost <= N1Cost) {
15846         Cost = std::min(N0Cost, N2Cost);
15847         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15848       } else if (NegN1) {
15849         Cost = std::min(N1Cost, N2Cost);
15850         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15851       }
15852     }
15853 
15854     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15855     if (isOperationLegal(ISD::FMA, VT)) {
15856       Cost = N2Cost;
15857       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15858     }
15859 
15860     break;
15861   }
15862 
15863   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15864                                               Cost, Depth);
15865 }
15866 
15867 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15868 bool PPCTargetLowering::useLoadStackGuardNode() const {
15869   if (!Subtarget.isTargetLinux())
15870     return TargetLowering::useLoadStackGuardNode();
15871   return true;
15872 }
15873 
15874 // Override to disable global variable loading on Linux.
15875 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15876   if (!Subtarget.isTargetLinux())
15877     return TargetLowering::insertSSPDeclarations(M);
15878 }
15879 
15880 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15881                                      bool ForCodeSize) const {
15882   if (!VT.isSimple() || !Subtarget.hasVSX())
15883     return false;
15884 
15885   switch(VT.getSimpleVT().SimpleTy) {
15886   default:
15887     // For FP types that are currently not supported by PPC backend, return
15888     // false. Examples: f16, f80.
15889     return false;
15890   case MVT::f32:
15891   case MVT::f64:
15892   case MVT::ppcf128:
15893     return Imm.isPosZero();
15894   }
15895 }
15896 
15897 // For vector shift operation op, fold
15898 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15899 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15900                                   SelectionDAG &DAG) {
15901   SDValue N0 = N->getOperand(0);
15902   SDValue N1 = N->getOperand(1);
15903   EVT VT = N0.getValueType();
15904   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15905   unsigned Opcode = N->getOpcode();
15906   unsigned TargetOpcode;
15907 
15908   switch (Opcode) {
15909   default:
15910     llvm_unreachable("Unexpected shift operation");
15911   case ISD::SHL:
15912     TargetOpcode = PPCISD::SHL;
15913     break;
15914   case ISD::SRL:
15915     TargetOpcode = PPCISD::SRL;
15916     break;
15917   case ISD::SRA:
15918     TargetOpcode = PPCISD::SRA;
15919     break;
15920   }
15921 
15922   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15923       N1->getOpcode() == ISD::AND)
15924     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15925       if (Mask->getZExtValue() == OpSizeInBits - 1)
15926         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15927 
15928   return SDValue();
15929 }
15930 
15931 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15932   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15933     return Value;
15934 
15935   SDValue N0 = N->getOperand(0);
15936   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15937   if (!Subtarget.isISA3_0() ||
15938       N0.getOpcode() != ISD::SIGN_EXTEND ||
15939       N0.getOperand(0).getValueType() != MVT::i32 ||
15940       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15941     return SDValue();
15942 
15943   // We can't save an operation here if the value is already extended, and
15944   // the existing shift is easier to combine.
15945   SDValue ExtsSrc = N0.getOperand(0);
15946   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15947       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15948     return SDValue();
15949 
15950   SDLoc DL(N0);
15951   SDValue ShiftBy = SDValue(CN1, 0);
15952   // We want the shift amount to be i32 on the extswli, but the shift could
15953   // have an i64.
15954   if (ShiftBy.getValueType() == MVT::i64)
15955     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15956 
15957   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15958                          ShiftBy);
15959 }
15960 
15961 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15962   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15963     return Value;
15964 
15965   return SDValue();
15966 }
15967 
15968 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15969   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15970     return Value;
15971 
15972   return SDValue();
15973 }
15974 
15975 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15976 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15977 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15978 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15979 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15980                                  const PPCSubtarget &Subtarget) {
15981   if (!Subtarget.isPPC64())
15982     return SDValue();
15983 
15984   SDValue LHS = N->getOperand(0);
15985   SDValue RHS = N->getOperand(1);
15986 
15987   auto isZextOfCompareWithConstant = [](SDValue Op) {
15988     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15989         Op.getValueType() != MVT::i64)
15990       return false;
15991 
15992     SDValue Cmp = Op.getOperand(0);
15993     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15994         Cmp.getOperand(0).getValueType() != MVT::i64)
15995       return false;
15996 
15997     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15998       int64_t NegConstant = 0 - Constant->getSExtValue();
15999       // Due to the limitations of the addi instruction,
16000       // -C is required to be [-32768, 32767].
16001       return isInt<16>(NegConstant);
16002     }
16003 
16004     return false;
16005   };
16006 
16007   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16008   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16009 
16010   // If there is a pattern, canonicalize a zext operand to the RHS.
16011   if (LHSHasPattern && !RHSHasPattern)
16012     std::swap(LHS, RHS);
16013   else if (!LHSHasPattern && !RHSHasPattern)
16014     return SDValue();
16015 
16016   SDLoc DL(N);
16017   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16018   SDValue Cmp = RHS.getOperand(0);
16019   SDValue Z = Cmp.getOperand(0);
16020   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16021 
16022   assert(Constant && "Constant Should not be a null pointer.");
16023   int64_t NegConstant = 0 - Constant->getSExtValue();
16024 
16025   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16026   default: break;
16027   case ISD::SETNE: {
16028     //                                 when C == 0
16029     //                             --> addze X, (addic Z, -1).carry
16030     //                            /
16031     // add X, (zext(setne Z, C))--
16032     //                            \    when -32768 <= -C <= 32767 && C != 0
16033     //                             --> addze X, (addic (addi Z, -C), -1).carry
16034     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16035                               DAG.getConstant(NegConstant, DL, MVT::i64));
16036     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16037     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16038                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16039     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16040                        SDValue(Addc.getNode(), 1));
16041     }
16042   case ISD::SETEQ: {
16043     //                                 when C == 0
16044     //                             --> addze X, (subfic Z, 0).carry
16045     //                            /
16046     // add X, (zext(sete  Z, C))--
16047     //                            \    when -32768 <= -C <= 32767 && C != 0
16048     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16049     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16050                               DAG.getConstant(NegConstant, DL, MVT::i64));
16051     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16052     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16053                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16054     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16055                        SDValue(Subc.getNode(), 1));
16056     }
16057   }
16058 
16059   return SDValue();
16060 }
16061 
16062 // Transform
16063 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16064 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16065 // In this case both C1 and C2 must be known constants.
16066 // C1+C2 must fit into a 34 bit signed integer.
16067 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16068                                           const PPCSubtarget &Subtarget) {
16069   if (!Subtarget.isUsingPCRelativeCalls())
16070     return SDValue();
16071 
16072   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16073   // If we find that node try to cast the Global Address and the Constant.
16074   SDValue LHS = N->getOperand(0);
16075   SDValue RHS = N->getOperand(1);
16076 
16077   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16078     std::swap(LHS, RHS);
16079 
16080   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16081     return SDValue();
16082 
16083   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16084   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16085   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16086 
16087   // Check that both casts succeeded.
16088   if (!GSDN || !ConstNode)
16089     return SDValue();
16090 
16091   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16092   SDLoc DL(GSDN);
16093 
16094   // The signed int offset needs to fit in 34 bits.
16095   if (!isInt<34>(NewOffset))
16096     return SDValue();
16097 
16098   // The new global address is a copy of the old global address except
16099   // that it has the updated Offset.
16100   SDValue GA =
16101       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16102                                  NewOffset, GSDN->getTargetFlags());
16103   SDValue MatPCRel =
16104       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16105   return MatPCRel;
16106 }
16107 
16108 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16109   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16110     return Value;
16111 
16112   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16113     return Value;
16114 
16115   return SDValue();
16116 }
16117 
16118 // Detect TRUNCATE operations on bitcasts of float128 values.
16119 // What we are looking for here is the situtation where we extract a subset
16120 // of bits from a 128 bit float.
16121 // This can be of two forms:
16122 // 1) BITCAST of f128 feeding TRUNCATE
16123 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16124 // The reason this is required is because we do not have a legal i128 type
16125 // and so we want to prevent having to store the f128 and then reload part
16126 // of it.
16127 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16128                                            DAGCombinerInfo &DCI) const {
16129   // If we are using CRBits then try that first.
16130   if (Subtarget.useCRBits()) {
16131     // Check if CRBits did anything and return that if it did.
16132     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16133       return CRTruncValue;
16134   }
16135 
16136   SDLoc dl(N);
16137   SDValue Op0 = N->getOperand(0);
16138 
16139   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16140   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16141     EVT VT = N->getValueType(0);
16142     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16143       return SDValue();
16144     SDValue Sub = Op0.getOperand(0);
16145     if (Sub.getOpcode() == ISD::SUB) {
16146       SDValue SubOp0 = Sub.getOperand(0);
16147       SDValue SubOp1 = Sub.getOperand(1);
16148       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16149           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16150         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16151                                SubOp1.getOperand(0),
16152                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16153       }
16154     }
16155   }
16156 
16157   // Looking for a truncate of i128 to i64.
16158   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16159     return SDValue();
16160 
16161   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16162 
16163   // SRL feeding TRUNCATE.
16164   if (Op0.getOpcode() == ISD::SRL) {
16165     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16166     // The right shift has to be by 64 bits.
16167     if (!ConstNode || ConstNode->getZExtValue() != 64)
16168       return SDValue();
16169 
16170     // Switch the element number to extract.
16171     EltToExtract = EltToExtract ? 0 : 1;
16172     // Update Op0 past the SRL.
16173     Op0 = Op0.getOperand(0);
16174   }
16175 
16176   // BITCAST feeding a TRUNCATE possibly via SRL.
16177   if (Op0.getOpcode() == ISD::BITCAST &&
16178       Op0.getValueType() == MVT::i128 &&
16179       Op0.getOperand(0).getValueType() == MVT::f128) {
16180     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16181     return DCI.DAG.getNode(
16182         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16183         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16184   }
16185   return SDValue();
16186 }
16187 
16188 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16189   SelectionDAG &DAG = DCI.DAG;
16190 
16191   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16192   if (!ConstOpOrElement)
16193     return SDValue();
16194 
16195   // An imul is usually smaller than the alternative sequence for legal type.
16196   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16197       isOperationLegal(ISD::MUL, N->getValueType(0)))
16198     return SDValue();
16199 
16200   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16201     switch (this->Subtarget.getCPUDirective()) {
16202     default:
16203       // TODO: enhance the condition for subtarget before pwr8
16204       return false;
16205     case PPC::DIR_PWR8:
16206       //  type        mul     add    shl
16207       // scalar        4       1      1
16208       // vector        7       2      2
16209       return true;
16210     case PPC::DIR_PWR9:
16211     case PPC::DIR_PWR10:
16212     case PPC::DIR_PWR_FUTURE:
16213       //  type        mul     add    shl
16214       // scalar        5       2      2
16215       // vector        7       2      2
16216 
16217       // The cycle RATIO of related operations are showed as a table above.
16218       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16219       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16220       // are 4, it is always profitable; but for 3 instrs patterns
16221       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16222       // So we should only do it for vector type.
16223       return IsAddOne && IsNeg ? VT.isVector() : true;
16224     }
16225   };
16226 
16227   EVT VT = N->getValueType(0);
16228   SDLoc DL(N);
16229 
16230   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16231   bool IsNeg = MulAmt.isNegative();
16232   APInt MulAmtAbs = MulAmt.abs();
16233 
16234   if ((MulAmtAbs - 1).isPowerOf2()) {
16235     // (mul x, 2^N + 1) => (add (shl x, N), x)
16236     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16237 
16238     if (!IsProfitable(IsNeg, true, VT))
16239       return SDValue();
16240 
16241     SDValue Op0 = N->getOperand(0);
16242     SDValue Op1 =
16243         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16244                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16245     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16246 
16247     if (!IsNeg)
16248       return Res;
16249 
16250     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16251   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16252     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16253     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16254 
16255     if (!IsProfitable(IsNeg, false, VT))
16256       return SDValue();
16257 
16258     SDValue Op0 = N->getOperand(0);
16259     SDValue Op1 =
16260         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16261                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16262 
16263     if (!IsNeg)
16264       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16265     else
16266       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16267 
16268   } else {
16269     return SDValue();
16270   }
16271 }
16272 
16273 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16274 // in combiner since we need to check SD flags and other subtarget features.
16275 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16276                                           DAGCombinerInfo &DCI) const {
16277   SDValue N0 = N->getOperand(0);
16278   SDValue N1 = N->getOperand(1);
16279   SDValue N2 = N->getOperand(2);
16280   SDNodeFlags Flags = N->getFlags();
16281   EVT VT = N->getValueType(0);
16282   SelectionDAG &DAG = DCI.DAG;
16283   const TargetOptions &Options = getTargetMachine().Options;
16284   unsigned Opc = N->getOpcode();
16285   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16286   bool LegalOps = !DCI.isBeforeLegalizeOps();
16287   SDLoc Loc(N);
16288 
16289   // TODO: QPX subtarget is deprecated. No transformation here.
16290   if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT) ||
16291       (VT.isVector() && !Subtarget.hasVSX()))
16292     return SDValue();
16293 
16294   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16295   // since (fnmsub a b c)=-0 while c-ab=+0.
16296   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16297     return SDValue();
16298 
16299   // (fma (fneg a) b c) => (fnmsub a b c)
16300   // (fnmsub (fneg a) b c) => (fma a b c)
16301   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16302     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16303 
16304   // (fma a (fneg b) c) => (fnmsub a b c)
16305   // (fnmsub a (fneg b) c) => (fma a b c)
16306   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16307     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16308 
16309   return SDValue();
16310 }
16311 
16312 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16313   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16314   if (!Subtarget.is64BitELFABI())
16315     return false;
16316 
16317   // If not a tail call then no need to proceed.
16318   if (!CI->isTailCall())
16319     return false;
16320 
16321   // If sibling calls have been disabled and tail-calls aren't guaranteed
16322   // there is no reason to duplicate.
16323   auto &TM = getTargetMachine();
16324   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16325     return false;
16326 
16327   // Can't tail call a function called indirectly, or if it has variadic args.
16328   const Function *Callee = CI->getCalledFunction();
16329   if (!Callee || Callee->isVarArg())
16330     return false;
16331 
16332   // Make sure the callee and caller calling conventions are eligible for tco.
16333   const Function *Caller = CI->getParent()->getParent();
16334   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16335                                            CI->getCallingConv()))
16336       return false;
16337 
16338   // If the function is local then we have a good chance at tail-calling it
16339   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16340 }
16341 
16342 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16343   if (!Subtarget.hasVSX())
16344     return false;
16345   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16346     return true;
16347   return VT == MVT::f32 || VT == MVT::f64 ||
16348     VT == MVT::v4f32 || VT == MVT::v2f64;
16349 }
16350 
16351 bool PPCTargetLowering::
16352 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16353   const Value *Mask = AndI.getOperand(1);
16354   // If the mask is suitable for andi. or andis. we should sink the and.
16355   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16356     // Can't handle constants wider than 64-bits.
16357     if (CI->getBitWidth() > 64)
16358       return false;
16359     int64_t ConstVal = CI->getZExtValue();
16360     return isUInt<16>(ConstVal) ||
16361       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16362   }
16363 
16364   // For non-constant masks, we can always use the record-form and.
16365   return true;
16366 }
16367 
16368 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16369 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16370 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16371 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16372 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16373 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16374   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16375   assert(Subtarget.hasP9Altivec() &&
16376          "Only combine this when P9 altivec supported!");
16377   EVT VT = N->getValueType(0);
16378   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16379     return SDValue();
16380 
16381   SelectionDAG &DAG = DCI.DAG;
16382   SDLoc dl(N);
16383   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16384     // Even for signed integers, if it's known to be positive (as signed
16385     // integer) due to zero-extended inputs.
16386     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16387     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16388     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16389          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16390         (SubOpcd1 == ISD::ZERO_EXTEND ||
16391          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16392       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16393                          N->getOperand(0)->getOperand(0),
16394                          N->getOperand(0)->getOperand(1),
16395                          DAG.getTargetConstant(0, dl, MVT::i32));
16396     }
16397 
16398     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16399     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16400         N->getOperand(0).hasOneUse()) {
16401       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16402                          N->getOperand(0)->getOperand(0),
16403                          N->getOperand(0)->getOperand(1),
16404                          DAG.getTargetConstant(1, dl, MVT::i32));
16405     }
16406   }
16407 
16408   return SDValue();
16409 }
16410 
16411 // For type v4i32/v8ii16/v16i8, transform
16412 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16413 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16414 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16415 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16416 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16417                                           DAGCombinerInfo &DCI) const {
16418   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16419   assert(Subtarget.hasP9Altivec() &&
16420          "Only combine this when P9 altivec supported!");
16421 
16422   SelectionDAG &DAG = DCI.DAG;
16423   SDLoc dl(N);
16424   SDValue Cond = N->getOperand(0);
16425   SDValue TrueOpnd = N->getOperand(1);
16426   SDValue FalseOpnd = N->getOperand(2);
16427   EVT VT = N->getOperand(1).getValueType();
16428 
16429   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16430       FalseOpnd.getOpcode() != ISD::SUB)
16431     return SDValue();
16432 
16433   // ABSD only available for type v4i32/v8i16/v16i8
16434   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16435     return SDValue();
16436 
16437   // At least to save one more dependent computation
16438   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16439     return SDValue();
16440 
16441   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16442 
16443   // Can only handle unsigned comparison here
16444   switch (CC) {
16445   default:
16446     return SDValue();
16447   case ISD::SETUGT:
16448   case ISD::SETUGE:
16449     break;
16450   case ISD::SETULT:
16451   case ISD::SETULE:
16452     std::swap(TrueOpnd, FalseOpnd);
16453     break;
16454   }
16455 
16456   SDValue CmpOpnd1 = Cond.getOperand(0);
16457   SDValue CmpOpnd2 = Cond.getOperand(1);
16458 
16459   // SETCC CmpOpnd1 CmpOpnd2 cond
16460   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16461   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16462   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16463       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16464       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16465       FalseOpnd.getOperand(1) == CmpOpnd1) {
16466     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16467                        CmpOpnd1, CmpOpnd2,
16468                        DAG.getTargetConstant(0, dl, MVT::i32));
16469   }
16470 
16471   return SDValue();
16472 }
16473